2 ms·
Current Java practices seem to prefer the 'builder pattern' where you chain a few setter functions and the call a .build() function that returns the object. If
by bzzzt 3y ago
Current Java practices seem to prefer the 'builder pattern' where you chain a few setter functions and the call a .build() function that returns the object. If a new field is required you can add an assertion in the builder.
The 'never and invalid state' pattern has one downside: there always seem to be exceptions in business logic and models so it's very hard to require things to be there 100% of the time. I've seen a system being built over a few years that started with valid objects/hard requirements that were partly removed when business needs and exceptions to the rule became more clear. Those changes caused bugs due to code not handling the null/doesn't exist case. Handling that from the start would have been a lot less work.
- akoboldfrying 3y agoGood point about the Builder pattern. Not a fan of the additional boilerplate but it does give the class developer the opportunity to detect forgotten fields and fail fast.