Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Constructor chaining?

After reading this Constructor chaining question I am just curious to know why would any one do constructor chaining?

Could some one please shed some light on type of scenarios where this might be useful.

Is this a good programming practice?

like image 803
Sandeep Avatar asked Sep 28 '11 02:09

Sandeep


1 Answers

It's absolutely a 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 enforce 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's the base class do it's thing
        // while extending behavior
    }
}
like image 101
Josh Avatar answered Sep 29 '22 08:09

Josh