Reputation: 16354
I have a class that requires a specific method to be called before being used by other objects, this method implements all the required logic and sets the properties of the class to their respective values. How can I ensure that the method of this class is called before the object is returned for use by other objects? I heard that it is a bad idea to implement logic in the constructor so I cannot call this method in the constructor. A code example for this sort of implementation is as follows:
SomeClass myClass = new SomeClass("someName");
//Class must call this method if object is to be of any use
myClass.ConvertNameToFunnyCharacters();
return myClass;
Upvotes: 1
Views: 177
Reputation: 137158
If it's essential that the object is constructed correctly then it's not a bad idea to put the logic in the constructor. You should consider putting the logic in another method - which should be public
if you want to be able to "reset" the object back to its default state.
Upvotes: 5
Reputation: 9951
Putting a lot of logic in the constructor can lead to a few problems:
So, I prefer to keep constructors as simple as possible: just assign parameters to instance variables. If I need to perform more complex logic to initialise an object I write a static factory function that calculates the constructor parameter values and passes them to a simple constructor.
Upvotes: 1
Reputation: 1545
Make your constructor internal, protected or private according to your needs and implement a Factory pattern. This is how to proceed when you need some object initialization to avoid high object dependencies.
http://msdn.microsoft.com/en-us/library/ms954600.aspx
Upvotes: 3
Reputation: 7238
According to me I will call it in the constructor or you'll make a burden on the class user to call this method before using it
Upvotes: 1
Reputation: 354694
If that method needs to be called before the class can be used then it sounds to me much like what a constructor should be doing. And a constructor is also just a special method, so what should be wrong about "implementing logic in the constructor"?
Upvotes: 4
Reputation: 7317
The reason it isn't recommended to have a lot of logic in the c'tor is that while in the c'tor the object still isn't valid. If that's what your "other" method does, then it's fine as part of the c'tor.
Upvotes: 1