1

I'm reading Bloch's Effective Java and now I'm at the 2nd item (Builder pattern). Here is what he said:

Like a constructor, a builder can impose invariants on its parameters. The build method can check these invariants.

What does the invariants mean? Couldn't you explain it?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

4

Invariants are simple constraints that should not be violated for the object to be in a safe state.

An invariant can be simple like a

simple regex check on some string property of a class. 

It can be a complex/combined invariant which means two parameters combined make a valid combination. eg. -

A class can hold type of animal and type of sound it produces.
so , a combination of dog and bark is valid but a combination of dog and meow is not valid. (just a case)

For simple cases, a builder can check the invariant itself in the corresponding property method in the builder or even the constructor of the builder if it accepts any such parameter with invariant.

For combined invariants, the check can be done in the constructor of the class which has the builder inside it. Or, the build method of the builder can also do all such combined invariant validation.

I hope this provides some help regarding the concept.

Mukul Anand
  • 606
  • 6
  • 24
2

As far as I am aware, invariants are simply properties of the parameters that are always true. For instance, one might say that calories must always be greater than 0. So I believe the book is just saying that the build method can check this and throw exceptions if it is violated.

Aaron G
  • 969
  • 1
  • 6
  • 7
  • However, invariants are rather about things that are always true for the internal state. Input parameter checking is usually called 'validation'. – dzidzitop Jun 21 '15 at 13:33
  • @dzidzitop I am not 100% familiar with the term but yes, I think you are right – Aaron G Jun 21 '15 at 13:38