Thirdly, most methods generally assume that the object is already complete when they're executing, not half way through being constructed. Secondly the method may have potentially been overridden unless it's marked final, and calling potentially overridden methods from a constructor is a big no-no in my book. Firstly something like this.x = x is just as clear, if not more so than calling a separate method that does the same thing. My preference is to set them directly in the constructor for a few reasons. Some references about constructors calling non-final, non-private methods: The more non-private, overridable methods that the constructor calls, the greater the risk of leaking this. While the previous rule was about methods inside the class and subclasses accessing ivars, you must also be careful about (even final/private) methods passing this to other classes and utility functions before this is fully initialized. ]Ĭonstructors should be cautious about leaking this before the instance is fully initialized. Is all that extra cognitive baggage worth it? You could allow an exception for simple mutators that only assign a value to an instance variable, since there's little benefit, even that doesn't seem worth it. This problem gets worse the deeper down the inheritance hierarchy the superclass with the "evil" constructor is.
0 Comments
Leave a Reply. |