0

I need to create a instance of ScanOptions. The correct code as below.

String pattern = "mykeyprefix_*";
Long cnt = 2000L;
ScanOptions options = ScanOptions.scanOptions().match(pattern).count(cnt).build();

My question is why not just use constructor to create object directly?

scanOptions = new ScanOptions(parttern, cnt);

Or use object Factory to create instance?

options = ScanOptionsFactory.create(parttern, cnt);

So is there any benefit to design code as first case? Could you please explain for me in detailed? thank you very much! here is the spring source code:

org.springframework.data.redis.core.ScanOptions

Farwell_Liu
  • 645
  • 1
  • 7
  • 17
  • 2
    I guess that they designed it that way, because it allows them to easily create new options and won't break existing code. – Lino Mar 01 '19 at 10:56
  • Possible duplicate of [When would you use the Builder Pattern?](https://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern) – jaco0646 Mar 01 '19 at 21:56

2 Answers2

2
  1. Optional options, saving variations

Imagine some more (optional) options. Then one would need several constructors, or a factory with several create methods.

The builder pattern that was used allows to have mutable fields, that a next option still might change in some way. And on creation the produced class has only immutable final fields.

  1. Clarity on many parameters

Also mind, that with many options, a builder pattern names every single option; compare:

.withX(y).withY(x)

with

(y, x)
  1. (Like a factory.) Hiding the exact implementing child class [Not the case here]

An other usage is to return a derived class by the builder, in fact hiding an implementing class.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
2

The benefit is that number of option can potentially grow in the future. They probably counted with that so they used builder pattern right from the start as the change from factory or constructor could be really hard.

There is nice reference to this problem in second chapter (Item 2) of Effective Java by Joshua Bloch.

Natrezim
  • 303
  • 2
  • 10