• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generic method question

 
ben oliver
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have jdk 4 code

private String name;
public void setName (String n) {
this.name = n;
}

If I use generic feature, shall I rewrite it as

private String name;
public <T extends Object> void setName(T n) {
this.name = n.toString();
}

Is this correct ? then what if n is null ? the original code is OK but the new code breaks !
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by ben oliver:
I have jdk 4 code

private String name;
public void setName (String n) {
this.name = n;
}

If I use generic feature, shall I rewrite it as

private String name;
public <T extends Object> void setName(T n) {
this.name = n.toString();
}

Is this correct ? then what if n is null ? the original code is OK but the new code breaks !

This is correct, although you should replace your code with this:

This will remove the NullPointerException.

Now as for generics - what does generics add here? T is only available to this method, and you're not actually using T inside. So the following is identical:

Now it would have been different if you used T to limit the types you want to allow. However, that also can be achieved by putting the limiting type as parameter type. So yes, it is correct use of generics, but not really appropriate.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:

This is correct, although you should replace your code with this:

This will remove the NullPointerException.


Not necessarily. There is nothing to say that this is the correct behaviour. It might be more appropriate for the code to throw a NullPointerException or IllegalArgumentException, or it might be better if it set name to "null". We cannot know, because there is no javadoc or other documentation of the method's contract.

It is my view that code should not try to cope with null arguments, unless that is part of the method's contract. To do so only covers up bugs and makes them harder to find (because something fails much further down the line, far removed from the original problem). Also, the null-handling code complicates the method, making it bigger, slower and harder to maintain. Methods that aren't contracted to handle null should not check for null.

A halfway house might be to assert that the argument is not null, but then to work around a null after the assertion. That way, developers running with asserts see the problem, but release code running without asserts makes a best effort not to crash (at this point anyway).
[ January 04, 2008: Message edited by: Peter Chase ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic