What is the Specification Pattern

Untangle Code With Specification Pattern

Milos Zivkovic
Level Up Coding
Published in
4 min readFeb 22, 2021

--

Photo by Sergey Zolkin on Unsplash

You need to select, validate, or add constraints to your domain. Specification pattern, in a clear OOP way, does the before-mentioned.

Let’s go into details. Next up, specification pattern in Java.

Problem

Selection: You need to select a subset of objects based on some criteria, and to refresh the selection at various times

Validation: You need to check that only suitable objects are used for a certain purpose

Construction-to-order: You need to describe what an object might do, without explaining the details of how the object does it, but in such a way that a candidate might be built to fulfill the requirement — Eric Evans

Specification Versions

Hard-Coded Specification

Polluted Code — code by author

You’ve seen this code. You need to select data based on an argument. This is what you see in most codebases. It is painful to debug, hard to test, and duplication of code is through the roof.

What can you improve here?

This class knows more than it should. You should always follow the principle of least astonishment. You can see, validation rules pollute the code, so you need to extract them.

You can extract those using the specification pattern. Let’s see the specification approach to decouple the previous code.

Hard-Coded Specification pattern implementation
Specification Pattern Code — code by author

According to docs(page 2.) on the specification pattern. This is “Hard-Coded Specification”.

Parametrized Specification

--

--