views:

115

answers:

2

Hi people,

I would like to hear from you guys on how do you decide when you should be using concrete parameterized type vs. bounded parameterized type when designing API, esp. (that I care most) of defining a class/interface.

For instance,

public interface Event<S>{
  void setSource(S s);
}

public interface UserEvent extends EVent<User> // OR: UserEvent<S extends User> extends Event<S>
  // It will therefore be void setSource(User s);
}

The problem of using concrete parameter is that, I can't bring this compile-time benefit I earn when using setSource() to a new interface say,

public interface AdminUserEvent extends UserEvent{
  void setSource(AdminUser s); // WHERE: AdminUser extends User. This is a method overloading, we also have a void setSource(User s) inherited from UserEvent.
}

What I can work around for this is to do a type checking on the User object when AdminUserEvent.setSource() is called.

Have you ever had this question raised when you design your API? And what are the practices or rules that you will go for when this sort of situation arises? Thanks.

yc

A: 

If I understand right this does not have much to do with generics in itself, but rather to do with parallel hierarchy. B extends A, BHandler extends AHandler and AHandler.handle(A) but BHandler.handle(B).

Yes, I believe this can be made typesafe with the use of generics. That is, if I have understood your problem correctly.

Hemal Pandya
Yes, sorry if the subject doesn't come too clear, this question is about using the generics feature for type safety.yc
yclian
+1  A: 

I think your commented-out UserEvent<S extends User> approach is the right one -- then you can declare AdminUserEvent extends UserEvent<AdminUser>. Is that all you need?

David Moles