Timeline for How to guarantee invariants / Inner logic in setter methods
Current License: CC BY-SA 3.0
6 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Feb 14, 2017 at 15:14 | comment | added | amon | @inf3rno Calling instance methods inside a constructor is generally considered an antipattern. When the method is called, the object is in a half-initialized state. However, methods may reasonably assume that the object they are receiving is complete, just like they can assume that this != null. That is particularly ugly if a subclass overrides the method. This is not an issue for static methods since they do not have access to this object and cannot be overridden. | |
| Feb 14, 2017 at 15:07 | comment | added | inf3rno | Why don't you call the setter from the constructor? | |
| Apr 8, 2014 at 11:55 | comment | added | Doval | @shylynx Not a problem if null is forbidden. | |
| Apr 8, 2014 at 9:49 | comment | added | amon | @shylynx good point, but sometimes throwing exceptions is the best thing to do, even in constructors – constructing an object in an illegal state is a worse problem. If you really want to avoid this, you need the builder pattern. | |
| Apr 8, 2014 at 9:47 | comment | added | shylynx | It's bad practice to use logic in constructors that can throw exceptions. Especially the example can throw NPE, if username is null. Not really smart. | |
| Apr 8, 2014 at 9:28 | history | answered | amon | CC BY-SA 3.0 |