tags:

views:

83

answers:

6

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;
+1  A: 

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.

Tal Pressman
+4  A: 

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"?

Joey
+5  A: 

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.

ChrisF
+1  A: 

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

Ahmed Said
+3  A: 

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

PulsarBlow
+1  A: 

Putting a lot of logic in the constructor can lead to a few problems:

  • If the constructor calls methods of the object, those methods run in a partially constructed object. This can really bite you when you override the method in subclasses: in Java and C# the subclass' implementation will run before the subclass' constructor has initialised the extended state of the object and so fail with null pointer exceptions. C++ works more "correctly" but can cause different confusing effects.
  • It makes unit testing with mock objects a bit more complicated if the constructor calls back out to objects passes as parameters.

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.

Nat