简体   繁体   中英

Is it good practice to pass multiple references to the same object into a method?

If you have:

class Component
{ 
   public Component(Interface1 interface1Instance, Interface2 interface2Instance)
   {

   this.interface1Instance = interface1Instance;
   this.interface2Instance = interface2Instance;

   }
}

then in the class which you use this in:

class ComponentGroup implements Interface1, Interface2
{
    public ComponentGroup()
    {

    this.component = new Component(this, this);

    }

}

While using composition, is it good practice to pass the same instance as separate parameters for to the component?

(edited):

Is it better to do what I presented above or to:

class Component
{ 
   public Component(Object object)
   {
       if(object instanceof Interface1){
           this.interface1Instance = interface1Instance;
       }
       if(object instanceof Interface2){
           this.interface2Instance = interface2Instance;
       }

   }
}

and

class ComponentGroup implements Interface1, Interface2
{
    public ComponentGroup()
    {

    this.component = new Component(this);

    }

}

In your case the first example is better design, because in the second example you are not specifying what Interfaces need to be passed as parameters to Component. Having a parameter of type Object is not good practice since other users of your class will have to read the constructor to know what should be passed in.

If you always use these two interfaces together you should combine them. Or if you're not the author, then create an abstract class A that inherits from both and have Component take an object of type A as a parameter.

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