Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java configuration/parameter passing design

Often I find the need to engineer objects with configurable functionality.

To exemplify, assume I'm creating a DateIterator. The configurable option(s) might be whether to iterate the closed interval [start, end] or the open-end interval [start, end).


  • (1) The, in my opinion, ungraceful solution - limited to only one true/false configuration option
new DateIterator(boolean openInterval);
  • (2) The typesafe enum way - typically a bit bulky
new DateIterator(Interval.OPEN_END);
  • (3) The unconventional attempt - nice but not too straight forward
new DateIterator().openEnd();
  • (4) The inheritance approach - often over-engineering
new OpenEndedDateIterator();

To this comes a few alternatives which I consider inferior, like integer-based configuration new DateIterator(Interval.OPEN_END); or property based configuration.

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

like image 756
Johan Sjöberg Avatar asked Aug 29 '11 12:08

Johan Sjöberg


1 Answers

I'd say the Builder pattern makes sense here:

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

That way your actual DateIterator can be immutable, while the builder returned by DateIterator.builder() does the configuration work.

like image 102
Sean Patrick Floyd Avatar answered Sep 17 '22 15:09

Sean Patrick Floyd