Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling instance method from a constructor in C#

I have a rather lengthy constructor which is performing various initialisation work, and as such I wanted to factor out some of this work into some functions. This led to me wonder whether I should make the said functions instance or static methods. I understand the risk of calling a virtual function from a constructor but I also think there is something not right about calling an instance method on an object which is not 100% instantiated. Surely this is a contradiction in terms.

I'd be interested in peoples opinion on this matter. I also found that by using a static method to return an initialised variable I could make the member target read-only. Here's a simplified illustration of my scenario.

public class A
{
   private readonly string _foo;

   public A()
   {  
       _foo = InitialiseFoo();
   }

   private static InitialiseFoo()
   {
       // Do stuff
       return new string ("foo");
   }
}
like image 753
Mr Davies Avatar asked Oct 14 '11 08:10

Mr Davies


2 Answers

This is pretty normal to call instance method in a constructor, moreover method which doing Initialization. So basically this is a kind of Extract Method refactorig to reduce a constructor method body, so you are extracting part of initialization into a separate method and constructor is aware on saving of the input arguments, etc...

Regarding the static modifier.. sometimes (I believe when no other ways to refactor because this looks not good - from my point of view) you need to call a method to pass results in a base constructor so in this case you have to mark it as static to call in a static context in other cases leave it without the static modifier

public A() 
: base(GetLogger())
{
}

private static ILog GetLogger() ...
like image 153
sll Avatar answered Sep 25 '22 14:09

sll


I can understand the desire to only use static members in a constructor, because it DOES make the code more straightforward to use without having to track what has been initialized and what hasn't, but you're likely making things needlessly complicated for yourself. Calling an instance method in C# is fine as long as you have a good reason to do it. For instance, if you have a number of constructors that all perform some common tasks, creating a single member function to do the work is easier to maintain than copy-and-pasting the code for each constructor. You can also imagine a case where the method can be re-used outside of the constructor for something like reseting the class to the initialized state.

The static method, is fine, but will only work in the case where you are doing some isolated work and putting the result into a member variable. It provides a very clean, functional programming-like feel. If any of the work involves class state, however, it's going to get ugly.

like image 20
user995048 Avatar answered Sep 24 '22 14:09

user995048