Duplicate constructor code issue

S

Steven Blair

I have encountered this problem a few times and would like to see how
other people deal with it.

A library has a Constructor that takes in n params and does some basic
validation and populates the class member.
I then get a requirement to add another paramter in at initialisation
time so the options I have (as far as I can see) are:

1. Change the current interface with the new param(s). No duplicate code
but the existing interface is changed and can cause me backwards
compatibilty problems.

2. Create a new constructor and give the user the choice. Problem is the
code in Constructor one must be copied in here as the same
initialisation is required.

3. I don't allow the user to pass in the new params. I simply make a
public member (or a get/set) and hope the user picks this up.

4. Create a base constructor common to all constructors.
This involves another class but might be the best solution.
The base constructor has all the standard validation I need, and the
child classes have the specific params validation etc.

Interested to hear other peoples views on this.

Regards,

Steven
 
F

Fred Mellender

use the "this" construct to invoke the other constructor, as in

public Foo(p1, p2, p3) //original constructor
{
//do assignments/logic with p1, p2, p3
}


public Foo (p1, p2, p3, p4):this(p1, p2, p3) //new constructor, with
p4, invokes
//prev
construct. via "this"
{
//assign/logic with p4
}
 
B

Bill Butler

Fred Mellender said:
use the "this" construct to invoke the other constructor, as in

public Foo(p1, p2, p3) //original constructor
{
//do assignments/logic with p1, p2, p3
}


public Foo (p1, p2, p3, p4):this(p1, p2, p3) //new constructor,
with p4, invokes

//prev construct. via "this"
{
//assign/logic with p4
}

It is generally a better Idea to have the constructor with less
parameters call the one with more parameters, passing in some default
value for the additional parameter

Change this
public Foo(p1, p2, p3) //original constructor
{
//do assignments/logic with p1, p2, p3
}

to this
public Foo(p1, p2, p3) : this (p1, p2, p3, 0) //new 3 param constructor
{ }

public Foo(p1, p2, p3, p4) //new 4 param constructor
{
//do assignments/logic with p1, p2, p3, p4
}

The library code continues to call the 3 param constructor, but it is
now a passthrough to the 4 param constructor.

This allows you to put the initialization in ONE constructor and simply
have the others call that constructor with the appropriate defaults.

Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top