tags:

views:

119

answers:

3

Is it necessary to parametrize the entire interface for this scenario, even though Bar is only being used in a single method?

public interface IFoo<T>{

    void method1(Bar<T> bar);

    //Many other methods that don't use Bar....

}  

public class Foo1 implements IFoo<Yellow>{

    void method1(Bar<Yellow> bar){...};

    //Many other methods that don't use Bar....

}


public class Foo2 implements IFoo<Green>{

    void method1(Bar<Green> bar){...};

    //Many other methods that don't use Bar....

}
A: 

You're not extending the interface. Is that deliberate? You can do this:

public class Foo2 implements IFoo<Green> {
  void method1(Bar<Green> bar);
}

Just doing this:

public class Foo<Green> {
  void method1(Bar<Green> bar);
}

won't compile.

cletus
sorry, should've been implementing.
yankee2905
I'm glad you pointed that out. It improved the question a lot, so I believe more people will try to answer it now :-)
KLE
+2  A: 

I would ask the question a bit differently, because the need suggests a cost, which is not actual. I don't think it actually matter if it is used on only one, or several methods.

When you make several calls to the instance, how does the type parameter vary?:

  • if constant once you instantiated the instance, you parameterize the entire interface.
  • if it may be different on each call, you parameterize the method.

That way, the type of parameter actually gives information about the code, improve the meaning and clarity.


Edited: Example

If sometimes, the type parameter varies from call to call, for the same instance ...
It has to be a method parameter.

KLE
It is likely that some implementation of IFoo will keep the parameter type constant, while other implementation it may vary :)
yankee2905
I don't think there would be any way for some implementations to enforce a particular type parameter while others allow it to change.
ColinD
+3  A: 

No, it's not necessary from a syntactic standpoint. You can also do this:

public interface IFoo {

  <T> void method1(Bar<T> bar);

  /* Many other methods that don't use Bar…  */

}

Or this:

public interface IFoo {

  void method1(Bar<?> bar);

  /* Many other methods that don't use Bar…  */

}

The correct choice depends on the semantics of IFoo and what its implementations are likely to do with the Bar instances they receive through method1.

erickson
+1 Good code samples, might help readers...
KLE