It seems to me that there is a certain kind of method that we should be able to declare. Something to the effect of ‘Constructor Method’ or ‘Constructor Helper’.
These would be methods that can only be called from constructors. There are a few reasons I can see for doing this:
-
First, I like my constructors to be clean. If I have to dump a lot of logic into a constructor, I would like to organize it. But then, the methods that I organize that logic into are probably not methods that I should ever call outside of a constructor. I would like to be able to declare constructor-only methods.
-
Secondly and similarly, readonly member variables can only be initialized inside a constructor. You can’t, for example, initialize a readonly variable in a method, even if you call that method from a constructor. I would like to be able to declare the method ‘constructor-only’, and then I would be able to initialize read only member variables in it.
-
Lastly, while I can see the argument that ‘if your constructors are complex enough to need to be reduced to multiple method calls, you’re doing too much in them‘, there is the case of having more than one constructor that might need the exact same logic as another. If I have three constructors that all need to initialize a readonly member variable, I should pull that initialization logic into a separate method. While I could set up such a method that returns the initialization value, as opposed to actually doing the initialization, I still would like to be able to declare such a method as ‘constructor-only’, since it probably shouldn’t be used anywhere else.
EDIT: Turning this into a question: are there problems that I’m not aware of with this idea, is it unnecessary, or could this actually be a useful feature?
Thanks
Like you said in your last point. Having lot of logic in constructor is somehow wrong. At least for me. You should either do it somewhere else or don’t do it at all. Something like creating separate class that doest this and then pass this class as parameter into constuctor.
And if your want to generalize constructor calls, you can chain different constructors, so when one is called, another is called too along with separate logic in the first one. Then some of those constructors can be private, so they cannot be called from outside.