What is the best way to make sure all the required properties of the class are set before returning the object to be used somewhere else
I have a class that requires a special method that will be called before being used by other objects, this method implements all the necessary logic and sets the properties of the class to the appropriate 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 a constructor, so I cannot call this method in a constructor. An example code for this type of implementation looks like this:
SomeClass myClass = new SomeClass("someName");
//Class must call this method if object is to be of any use
myClass.ConvertNameToFunnyCharacters();
return myClass;
a source to share
Putting a lot of logic in the constructor can lead to several problems:
- If the constructor calls methods on an object, those methods are executed on the partially constructed object. This can bite you when you override a method in subclasses: in Java and C #, the subclass implementation will execute before the subclass's constructor initializes the extended state of the object and thus terminates with null pointer exceptions. C ++ works more "correctly" but can cause various confusing effects.
- This makes unit testing with mock objects a little more difficult if the constructor refers to objects passing as parameters.
So, I prefer keeping the constructors as simple as possible: just assign parameters to instance variables. If I need to perform more complex logic to initialize an object, I write a static factory function that calculates the parameter values of the constructor and passes them to a simple constructor.
a source to share