Jmp Start

…where the Geek shall Inherit the Word

Archive for the ‘Architecture’ Category

Do NOT recreate a ctor, use it!

Posted by CKret on July 19, 2012

Stackoverflow is a very popular site for developers.
There are tons of questions and answers and there is a good chance you’ll find the solution to your specific problem if you take the time to search a bit.

This post however is not about the correct answers but more about the ones who on the surface seem correct.

A question was asked and an answer was given.

The answer itself is not bad. It is a working solution. For now.
And that’s the key: for now.

An example (where A is a class in a third party assembly):

public class A
{
  public A()
  {
    Init();
  }

  protected void Init()
  {
    ...
    Initialize everything.
    ...
  }
}

public class B : A
{
  private int theNumber;
  public B(int num)
  {
    Init();

    theNumber = num;
  }
}

The constrcutor of B does exactly what the constructor of A does, calls Init, and some more.
So far so good.

But what happens if the constructor of A in an later update changed to:

public class A
{
  public A()
  {
    Init();
    FixSecurityProblem();
  }

  public void Init()
  {
    ...
    Initialize everything.
    ...
  }

  protected void FixSecurityProblem()
  {
    ...
    Do fix the security problem.
    ...
  }
}

This isn’t a breaking change. The code only introduces some internal security checks not visible to the “outside”.

How does this affect B?
Well. The creator of B would have to add a call to FixSecurityProblem in it’s constructor and distribute the new version to all clients.
Will this work?
Sure, but there will be a lot of headache.

Since all clients might not have the new A,
B has to determine exactly which version is installed and make some decisions based on that.
Then the new version of B has to be distributed to all clients.

An even bigger problem would be if FixSecurityProblem was a private method:

public class A
{
  private void FixSecurityProblem()
  {
    ...
    Do fix the security problem.
    ...
  }
}

Now B would have to call A‘s constructor instead! Which is exactly the point in this post.

Even if someone finds this a valid solution, the fundamental problem here is the negligance of NOT utilizing the existing constructor of A:

public class B : A
{
  private int theNumber;
  public B(int num) : base()
  {
    theNumber = num;
  }
}

This would, for all who have an updated class A, fix the security problem. Whithout any changes to B!
For those who have not updated, changes in B would not affect them anyway!

So, as the title says, “Do NOT recreate a ctor, use it!”.

Posted in .NET, Architecture, C# | Tagged: , , | Leave a Comment »