简体   繁体   中英

class have two constructors

My class has two constructors

class test()

    // declare
    par1 as object, par2 as  object , par3 as object

    // constructors
    public test(par1, par2) {,,,,}
    public test(par1, par2, par3) {,,,,,}

    // Methods 
     fct1() 
     {
          '' do something with par1 and par2
     }


     fct2(){

           if(par3 is null) 
             throw exception ('be sure to use the right constructor ) 
           else
           '' do something with par1 and par2
             and par3
     }

my question :

is it OK to have two constructors like that :

because if some one need to use fct2 he should use constructor number 2 (with 3 parameters) else it is going to throw an exception

is it OK or is there any other better solution

ps: this class is implemented every where if i change first constructor i need to change every place where the class is called

thank you .

So you have a class with two methods, and the second method adds functionality to the first. Sounds like an ideal candidate for inheritance:

public class FirstImplementation
{
    public FirstImplementation(param1, param2)
    {
    }

    public virtual Bar Foo()
    {
        // do something with param1, param2
    }
}

Then inherit it to adapt its behavior:

public class SecondImplementation : FirstImplementation
{
    public SecondImplementation(param1, param2, param3)
        : base(param1, param2)
    {
    }

    public override Bar Foo()
    {
        // do something with param1, param2 and param3, perhaps by calling base.Foo().
    }
}

Because you don't want a class that contains the same code twice with slight alterations, that requires the caller to know which constructor to call prior to calling one of its methods, or that throws an InvalidOperationException when the wrong constructor was called. That's unusable and unmaintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM