3 ms·
Why should one not use setter methods?
by mongol 12y ago
Why should one not use setter methods?
- chrisguitarguy 12y agoIf your objects require dependencies to do their jobs, it should be impossible to create objects without those dependencies. The objects' constructors should require them. Having setters is, arguably, fine (but probably unnecessary) as long as invalid objects can't be created.
- Roboprog 12y agohttp://en.wikipedia.org/wiki/Class_invariant http://en.wikipedia.org/wiki/Class_invariant (above is a special case of below) http://en.wikipedia.org/wiki/Design_by_contract http://en.wikipedia.org/wiki/Design_by_contract Alas, Eiffel looked like Modula (Pascal), rather than like C/C++, so it never caught on. The important part, though, was the idea of class invariants + method pre-conditions + method post-conditions. Meyer's book, from years before Java and "Java beans" infected the group-think, talked about classes that explicitly were constructed in a valid state (which also meshes well with the practice of immutability), and methods with explicit conditions of their requirements and what they were guaranteeing they would accomplish. "Java beans" pretty much took these otherwise sound engineering principles and pissed all over them. Rather than having a constructor that builds an object that you can then start using, you have to guess (unless documentation is very good, which it won't be) which setters must be called before "bean" is non-crap. Yes, I'm bitter that such an obviously flawed practice became standard operating procedure, to the point that doing things right is viewed as suspect.
- dack 12y agoSetters basically send a signal to the developer that the dependency is "optional", since someone can create the object and simply not call the setter. Most of the time, the dependencies are assumed to be set in, and will blow up at run-time when they are attempted to be accessed. By using constructor injection you prevent this from happening. Also, consider a case of refactoring. You have a class that is being created from a few places and add a new dependency via a setter to it. Compile your code, and it looks fine but actually isn't - you need to find all the places you create that object and provide the extra dependency. If you use constructor injection, you'd have a compile error (in a statically typed language) in all the places that need to be fixed.
- kasey_junk 12y agoUsing dependency injection adds complexity. You have to reason about how the injected functionality can change. If you use setter based injection (as opposed to constructor or parametric injection) then you also add the complexity of reasoning about when it can change.