The goal of the constructor chain?

After reading this question about the constructor chain, I'm just curious to know why someone is making the constructor chain?

Can someone shed light on the types of scenarios where this might be useful.

Is this a good programming practice?

+5
source share
4 answers

This is absolutely good practice for two main reasons:

To avoid code duplication

class Foo
{
    public Foo(String myString, Int32 myInt){
        //Some Initialization stuff here
    }

    //Default value for myInt
    public Foo(String myString) : this(myString, 42){}

    //Default value for both
    public Foo() : this("The Answer", 42){}
}

To provide good encapsulation

public abstract class Foo
{
    protected Foo(String someString)
    {
        //Important Stuff Here
    }
}

public class Bar : Foo
{
    public Bar(String someString, Int32 myInt): base(someString)
    {
        //Let the base class do it thing
        // while extending behavior
    }
}
+3
source

. .

+2

' - , . , , . , Person . , ; , . . " ", :

:

public class Person
    {
        private int Age;
        private string Name;
        private string HairColour;


        public Person(int theAge)
        {
           Age = theAge;
        }

        public Person(int theAge, string theName)
        {
            Age = theAge;
            Name = theName;
        }

        public Person(int theAge, string theName, string theHairColour)
        {
            Age = theAge;
            Name = theName;
            HairColour = theHairColour;
        }

    }

, Age, . Name , . , Age, Name HairColour . , . . , " ".

:

public class Person
    {
        private int Age;
        private string Name;
        private string HairColour;


        public Person(int theAge):this(theAge, "", "")
        {
            //One parameter
        }

        public Person(int theAge, string theName):this(theAge, theName, "")
        {
            //Two Parameters
        }

        public Person(int theAge, string theName, string theHairColour)
        {
            //Three parameters
            Age = theAge;
            Name = theName;
            HairColour = theHairColour;
        }

    }

, - .

"" ( ):

,

+1

I saw this when you did a heavy lift during construction, and you have many different ways to create an object. (So ​​many buttons with different parameter signatures).

You can only have a private member function that does the common work through ctors. You do not need one ctor to call another in the same class. (Which is not even allowed in most languages).

0
source

All Articles