Jump to content

  • Log In with Google      Sign In   
  • Create Account

Constructor Chaining Order to Parameters or Parameterless.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 Mikea15   Members   -  Reputation: 225

Like
0Likes
Like

Posted 06 April 2014 - 10:54 AM

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


---

Cinder Interative - Indie Game Studio | MikeaDev.net - My Blog | Michael Adaixo - My Website.


Sponsor:

#2 Ectara   Crossbones+   -  Reputation: 3057

Like
5Likes
Like

Posted 06 April 2014 - 12:13 PM

I think that in your first chaining example, calling the default constructor from the constructor taking two parameters is meaningless; it sets variables that are immediately overwritten. The second example is the only one that makes sense.

 

As for the Node example, it's hard to know which makes sense without seeing the context. If the Node is default constructed, its position isn't set, and without knowing the context of the calling code, it isn't known whether or not it is more important to have Adjacents and State always set, or PosX and PosY always set.



#3 Lantre   Members   -  Reputation: 184

Like
2Likes
Like

Posted 06 April 2014 - 02:16 PM

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.



#4 Ryan_001   Prime Members   -  Reputation: 1457

Like
1Likes
Like

Posted 06 April 2014 - 10:38 PM

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.



#5 Mikea15   Members   -  Reputation: 225

Like
1Likes
Like

Posted 07 April 2014 - 02:16 AM

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, 07 April 2014 - 04:36 AM.

---

Cinder Interative - Indie Game Studio | MikeaDev.net - My Blog | Michael Adaixo - My Website.


#6 Lantre   Members   -  Reputation: 184

Like
1Likes
Like

Posted 07 April 2014 - 04:12 AM

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;
}


#7 swiftcoder   Senior Moderators   -  Reputation: 10364

Like
4Likes
Like

Posted 07 April 2014 - 03:28 PM


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.


Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#8 Mikea15   Members   -  Reputation: 225

Like
1Likes
Like

Posted 07 April 2014 - 03:39 PM

So I guess, I would have to re-think on how much control those classes provide. Thank you :)


---

Cinder Interative - Indie Game Studio | MikeaDev.net - My Blog | Michael Adaixo - My Website.


#9 ChaosEngine   Crossbones+   -  Reputation: 2499

Like
2Likes
Like

Posted 07 April 2014 - 04:09 PM

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.


if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS