Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • I don't think your given example satisfies either rule. There's nothing stopping me creating a Cfg in an invalid state, and while the parameters have been moved out of the ctor they've just been moved to a less idiomatic and more verbose place. fooBuilder.withBar(2).withBang("Hello").withBaz(someComplexObject).build() offers a succinct API for building foos and can offer actual error checking in the builder itself. Without the builder the object itself has to check its inputs, which means we're no better off than we used to be. Commented Feb 17, 2014 at 16:10
  • DTOs can have their properties validated in numerous ways declaratively with annotations, on the setter, however you want to go about it - validation is a separate problem and in his builder approach he shows validation occuring in the constructor, that same logic would fit perfectly well in my approach. However it would generally be better to use the DTO to have it validate because as I show - the DTO can be used to construct multiple types and so having validation on it would lend itself to validating multiple types. The builder only validates for the one particular type it's made for. Commented Feb 17, 2014 at 21:15
  • Perhaps the most flexible way would be to have a static validation function in the builder, which accepts a single Fieldable parameter. I would call this validation function from the ToBeBuilt constructor, but it could be called by anything, from anywhere. This eliminates the potential for redundant code, without forcing a specific implementation. (And there's nothing to stop you from passing in individual fields to the validation function, if you don't like the Fieldable concept--but now there would be at least three places in which the field-list would have to be maintained.) Commented Feb 17, 2014 at 21:29
  • +1 And an a class that has too many dependencies in its constructor is obviously not cohesive enough and should be refactored into smaller classes. Commented Feb 18, 2014 at 3:21
  • @JimmyHoffa: Ah, I see, you just omitted that. I'm not sure I see the difference between this and a builder, then, other than this passes a config instance into the ctor instead of calling .build on some builder, and that a builder has a more obvious path for correctness checking on all the data. Each individual variable could be within its valid ranges, but invalid in that particular permutation. .build can check this, but passing the item into the ctor requires error checking inside the object itself--icky! Commented Feb 18, 2014 at 9:24