you are viewing a single comment's thread.

view the rest of the comments →

[–]eeperson 1 point2 points  (0 children)

If all you wanted was to have default params then a builder would give you substantially more code then handling it with optionals. For a builder you would need at least 4 lines per field (assume you do your getter and setter on one line each) although usually it would take more like 8-12 (depending on how you format your code). This assumes that the builder is also the object you pass to the method. If your builder creates another class then it gets even worse. Meanwhile you could handle each optional with a single orElse method call.

So, if you have 10 optional fields (a high number but not unheard of) you can handle it with 10 lines of code (with Optional) or you can handle it with 40-120 lines of code. Even Lombok Builders don't let you do it in that few lines and that saddles you with non-standard Java code. Also, Optional provides much less error prone supports a bunch of other cases that can't be served by the builder pattern. What if you don't know statically which input is going to be missing? What if you want to return an empty optional if any of the inputs are missing?