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;

      

+1


a source to share


6 answers


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.

+1


a source


If it is important that the object is constructed correctly, then it would be a good idea to put the logic in the constructor. You should consider putting your logic in a different method that should be public

if you want to be able to "reset" the object to its default state.



+5


a source


If this method needs to be called before the class is used, it will sound the same as the constructor. And a constructor is also just a special method, so what should be wrong about "implementing logic in a constructor"?

+4


a source


Make your constructor internal, secure, or private as per your needs and implement the Factory pattern. Here's how to do it when you need object initialization to avoid object dependencies.

http://msdn.microsoft.com/en-us/library/ms954600.aspx

+3


a source


The reason it is not recommended to have a lot of logic in c'tor is because although in c'tor the object is still invalid. If that's what your "other" method does, then that's fine as part of the c'tor.

+1


a source


According to me, I will call it in the constructor or you will click on the user of the class to call this method before using it.

+1


a source







All Articles