Jump to content
  • Advertisement
Sign in to follow this  
Mikea15

Constructor Chaining Order to Parameters or Parameterless.

This topic is 2025 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello.

 

So I've been dwelling on this topic today. Which is, which way do you want to chain your constructor.

 

Say you have a basic BaseMap class.

public class BaseMap
{
    protected int _height;
    protected int _width;

    protected Node[,] _map;

    public BaseMap()
    {
        _width = 0;
        _height = 0;
        _map = null;
    }

    public BaseMap(int width, int height)
    {
        _width = width;
        _height = height;
        _map = new Node[_width, _height];

        for (int x = 0; x < _width; x++)
        {
            for (int y = 0; y < _height; y++)
            {
                _map[x, y] = new Node(x, y);
            }
        }
    }
}

Now my question is, how you chain the constructors? So far, I've been chaining them this way:

public class BaseMap
{
    protected int _height;
    protected int _width;

    protected Node[,] _map;

    public BaseMap()
    {
        _width = 0;
        _height = 0;
        _map = null;
    }

    public BaseMap(int width, int height) 
        : this( )
    {
        _width = width;
        _height = height;
        _map = new Node[_width, _height];

        for (int x = 0; x < _width; x++)
        {
            for (int y = 0; y < _height; y++)
            {
                _map[x, y] = new Node(x, y);
            }
        }
    }
}

But I've searched online and found people where chaining the other way around. Like this:

public class BaseMap
{
    protected int _height;
    protected int _width;

    protected Node[,] _map;

    public BaseMap()
        : this( 10, 10 ) // default values
    {

    }

    public BaseMap(int width, int height) 
    {
        _width = width;
        _height = height;
        _map = new Node[_width, _height];

        for (int x = 0; x < _width; x++)
        {
            for (int y = 0; y < _height; y++)
            {
                _map[x, y] = new Node(x, y);
            }
        }
    }
}

So, from what I understand, people are instantiating with default values, when calling the default constructor, leaving it empty. My Approach was to start with the constructors with parameters, and call this( ) to instantiate variables, before getting into the parameter constructor's body. This particular example isn't the most obvious tho, but say you have a node with edges.

public Node( )
{
	Adjacents = new List<Node>();
	State = EnumNodeState.UNKNOWN;
}

public Node( int x, int y )
	: this( )
{
	PosX = x;
	PosY = y;
}

This makes sense, right? I instantiate the List and state, then define position, when calling Node( 10 , 10 );
Is it 'better' to do it the other way around?

 

Thanks. smile.png

Share this post


Link to post
Share on other sites
Advertisement

By the end of construction your object should be left in a valid state. You also want to reduce/eliminate code duplication. If you can't do this by chaining constructors then consider factoring out the common code into a separate method and calling that from within your constructor.

Share this post


Link to post
Share on other sites

By the end of construction your object should be left in a valid state. You also want to reduce/eliminate code duplication. If you can't do this by chaining constructors then consider factoring out the common code into a separate method and calling that from within your constructor.

 

Exactly.  Choose whichever method makes sense for the given class.

Share this post


Link to post
Share on other sites

Okay, so there is no "best way" to do it. That's what I wanted to know. smile.png

 

Thanks for the feedback. smile.png

 

Edit:

To get a better view. Here's the main difference with another class.

public X( )
{
    Left = 0;
    Right = 0;
    BreakLeft = false;
    BreakRight = false;
    BreakTime = 0;
}

public X(int speed)
    : this( )
{
    Left = speed;
    Right = speed;
}

public X(int left, int right)
    : this( )
{
    Left = left;
    Right = right;
}

public X(int left, int right, int time, bool breakWheel)
{
    Left = left;
    Right = right;

    BreakLeft = breakWheel;
    BreakRight = breakWheel;

    BreakTime = time;
}

public X(int left, int right, int time, bool breakLeft, bool breakRight)
{
    Left = left;
    Right = right;

    BreakLeft = breakLeft;
    BreakRight = breakRight;

    BreakTime = time;
}

And Method 2:

public X( )
    : this( 0 )
{

}

public X(int speed)
    : this( speed, speed )
{
    
}

public X(int left, int right)
    : this( left, right, 0, false )
{

}

public X(int left, int right, int time, bool breakWheel)
    : this( left, right, time, breakWheel, breakWheel )
{

}

public X(int left, int right, int time, bool breakLeft, bool breakRight)
{
    Left = left;
    Right = right;

    BreakLeft = breakLeft;
    BreakRight = breakRight;

    BreakTime = time;
}

For this particular case. This is the better approach. It has less code, Its easier to maintain and is cleaner. smile.png

Edited by Mikea15

Share this post


Link to post
Share on other sites

Okay, so there is no "best way" to do it. That's what I wanted to know. smile.png

 

Thanks for the feedback. smile.png

 

Edit:

To get a better view. Here's the main difference with another class.

public X( )
{
    Left = 0;
    Right = 0;
    BreakLeft = false;
    BreakRight = false;
    BreakTime = 0;
}

public X(int speed)
    : this( )
{
    Left = speed;
    Right = speed;
}

public X(int left, int right)
    : this( )
{
    Left = left;
    Right = right;
}

public X(int left, int right, int time, bool breakWheel)
{
    Left = left;
    Right = right;

    BreakLeft = breakWheel;
    BreakRight = breakWheel;

    BreakTime = time;
}

public X(int left, int right, int time, bool breakLeft, bool breakRight)
{
    Left = left;
    Right = right;

    BreakLeft = breakLeft;
    BreakRight = breakRight;

    BreakTime = time;
}

And Method 2:

public WiGoSpeed( )
    : this( 0 )
{

}

public X(int speed)
    : this( speed, speed )
{
    
}

public X(int left, int right)
    : this( left, right, 0, false )
{

}

public X(int left, int right, int time, bool breakWheel)
    : this( left, right, time, breakWheel, breakWheel )
{

}

public X(int left, int right, int time, bool breakLeft, bool breakRight)
{
    Left = left;
    Right = right;

    BreakLeft = breakLeft;
    BreakRight = breakRight;

    BreakTime = time;
}

For this particular case. This is the better approach. It has less code, Its easier to maintain and is cleaner. smile.png

 

In that case I would avoid the multi-chaining since it's hard to follow what the end result of construction will be. Rather call you 'main' constructor, i.e. the one doing all the work, directly from the others and make it explicit what each parameter is being set to.

 

Like so:

public WiGoSpeed( )
    : this( 0 )
{

}

public X(int speed)
    : this( speed, speed, 0, false, false )
{
    
}

public X(int left, int right)
    : this( left, right, 0, false, false )
{

}

public X(int left, int right, int time, bool breakWheel)
    : this( left, right, time, breakWheel, breakWheel )
{

}

public X(int left, int right, int time, bool breakLeft, bool breakRight)
{
    Left = left;
    Right = right;

    BreakLeft = breakLeft;
    BreakRight = breakRight;

    BreakTime = time;
}

Share this post


Link to post
Share on other sites


This makes sense, right? I instantiate the List and state, then define position, when calling Node( 10 , 10 );

You are going to end up with some mighty long chains when you have a class with more than a couple of constructors.

 

I wouldn't say there is a "right way", per se, but I lean heavily towards the clarity provided by having a single canonical constructor providing all required functionality, and a handful of 'utility constructors' which just manipulate the arguments thereof.

Share this post


Link to post
Share on other sites

There are a few other options to consider.
 
You could use a combination of default values and named parameters:

public class Test
{
    private readonly int _x;
    private readonly int _y;
    private readonly int _z;
    private readonly string _name;
    private readonly double _speed;

    public Test(int x = 0, 
        int y = 0, 
        int z = 0, 
        string name = null, 
        double speed = 0.0)
    {
        _x = x;
        _y = y;
        _z = z;
        _name = name;
        _speed = speed;
    }
}

var t = new Test(y: 3, name: "bob", speed: 66.6);

pros: one constructor, sensible defaults defined in one place, user can choose what params they need to set
cons: easier for user to set some incompatible set of parameters, optional argument change issue (in practice this is pretty rare)
 
Another option (similar to above) is to make the values properties and use a property initialiser

public class Test
{
    public int X {get;set;}
    public int Y {get;set;}
    public int Z {get;set;}
    public string Name {get;set;}
    public double Speed {get;set;}
}

var t = new Test
{
    X = 3,
    Name = "Alice",
    Z = 4
};

pros: minimal code, easy for user of class to set values
cons: no defaults (although you could modify the properties to be backing props with sensible defaults), same issue with setting incompatible set of default params

 

 

I'm not advocating any of these choices, merely presenting them as options. Each has it's pros and cons, but ultimately, the choice of initialisation method is dependant on the class you are creating and the invariants you need to preserve.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!