Java configuration configuration / parameters

Often I find a need for designing objects with custom functionality.

To demonstrate, suppose I create a DateIterator . Configurable options can be whether to iterate a closed interval [start, end] or an open interval [start, end) .


  • (1) In my opinion, an indecent solution limited to only one true / false configuration parameter
 new DateIterator(boolean openInterval); 
  • (2) A typical enumeration method is usually a bit cumbersome
 new DateIterator(Interval.OPEN_END); 
  • (3) An unconventional attempt is good, but not too direct.
 new DateIterator().openEnd(); 
  • (4) The inheritance approach - often over-engineering
 new OpenEndedDateIterator(); 

For this, several alternatives arise that I consider incomplete, for example, the integer-based configuration new DateIterator(Interval.OPEN_END); or property based configuration.

Are there any other approaches? Which approach do you prefer?

+8
java parameter-passing design configuration
source share
2 answers

I would say that the Builder template makes sense here:

 DateIterator di = DateIterator.builder() .withStartDate(new Date()) .withOpenEnd() .build(); 

That way, your actual DateIterator may be immutable, and the builder returned by DateIterator.builder() does the customization.

+6
source share

While there is no good answer, and it depends heavily on taste, I follow the following rule, with plenty of room for exceptions to avoid over engineering:

  • If your only configuration is one “parameter”, taking a fixed set and changing the behavior (as in your example), proceed to subclasses. Although this may be overly designed if many methods in your class start with "if (this.parameter == x) ... else if (this.parameter == y) ..", it will make the code unreadable.
  • If your parameter is not a fixed set, but a string or a number, and you need the class to work correctly, put it in the constructor, if it is not mandatory, I would like to name the solution number (3), an unconventional attempt:)
  • If you have several parameters in a fixed set (for example, START_OPEN_ENDED and STOP_OPEN_ENDED), subclassing may mean creating a subclass for each permutation. In this case, consider encapsulation. For example (I would not do this in this particular case, perhaps, but this is a good example), create one DateComparator class with a subclass for the open end and encapsulate DateComparator for the beginning and one for the end, having only one DateIterator.

Again, this rule of thumb that I use is by no means mandatory, and often I believe that I do not follow them verbatim.

+1
source share

All Articles