sooprise
sooprise

Reputation: 23207

Constructors With Same Arguments?

I have a WinForm that I want to be able to construct using two different ID values. So for instance:

var f1 = new Form(table1Id);
var f2 = new Form(table2Id);

The first constructor would build the form based on data in table1, the second constructor would build the form based on data in table2. The problem is, if I have two constructors that take an int, there is no differentiating between the two. What is the best way around this problem?

Upvotes: 3

Views: 325

Answers (5)

Austin Salonen
Austin Salonen

Reputation: 50245

Without seeing code it's hard to confirm this, but by your very explanation this class is violating the Single Responsibility Principle.

Assuming the forms only differ by data, have the constructor take the actual data instead IDs, which I assume are used to get the data.

If they differ substantially by the content, they should be two distinct forms (possible with a common, abstract parent class).

Based on my past experiences, having that one form to rule them all mentality is just going to create a maintenance nightmare. Spend some time studying the SOLID principles (S = Single Responsibility Principle) and you'll be pleasantly surprised with the code you start writing.

Upvotes: 2

Itamar Marom
Itamar Marom

Reputation: 525

In this case I'd create an Enum and pass one of its values as an argument, indicating what kind of table is given.

Upvotes: 0

MatthiasG
MatthiasG

Reputation: 4532

I would use an Initialize method, something like:

var f1  = new Form();
f1.InitA(table1Id);
var f2  = new Form();
f2.InitB(table2Id);

Upvotes: -2

Bala R
Bala R

Reputation: 109027

class MyForm : Form
{
    public MyForm(int id)
    {
         // logic to distinguish id goes here
    }
}

Upvotes: 4

Anthony Pegram
Anthony Pegram

Reputation: 126992

Consider a factory approach instead of a constructor. Named methods are a way to disambiguate when the parameter types are the same but mean different things. For example

public static Form CreateFromTable1(int id)
{
    // instantiate, build form
    return form;
}

public static Form CreateFromTable2(int id)
{
    // instantiate, build form
    return form;
}

Upvotes: 4

Related Questions