Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>move declaration and initialization together

Another, even better reason to do this is to prevent the declared object ever being in an invalid (e.g., undefined or null) state. If it's born in a valid state, and every method call leaves it in a valid state, it's harder for things to go wrong.

In the C++ world this approach is encouraged, finding its highest form as RAII: the convention of designing classes to be declared as objects (not references to them), with constructors that leave them fully formed, and destructors that silently and automatically clean them up (thanks to deterministic destructor calls -- one of the best decisions made by the language designers.)

Sadly Java prefers the "bean" convention of new-ing up a "blank" object and then calling setAbc(), ..., setXyz() on it. I hope every time you create an object, you remember to call set...() for every field! Including when you add a new field later!



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.


Good 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.


Am I the only one who thinks that code where declarations are mixed with statements is harder to read?


Nope!

Keep the declarations, ditch the statements.


Pure declarative programming.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: