Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the name just because of Null?

Tags:

c#

api

I work on developing an external API. I added a method to my public interface :

public void AddMode(TypeA mode);
public void AddMode(TypeB mode); // the new method, TypeB and TypeA are not related at all

It looked good, until one test broke that was passing a null . That made the compiler confused with ambiguous call. I fixed the test with casting the null.

However my question is :

  • Should I change the name just because of this?
  • Or should let the client do the cast as I did? (if they pass null for whatever reason)

What is the best in this case while designing APIs ?

Edit :

the call was like this AddMode(null) , not like :

TypeA vl = null; 
AddMode(v1); // this doesn't cause a problem
like image 410
MBen Avatar asked Jun 26 '12 09:06

MBen


Video Answer


2 Answers

An API should be designed so that it's easy to use correctly and hard to use incorrectly. Your API is easy to use correctly:

AddMode(new TypeA());

does compile.

It's harder to use incorrectly:

AddMode(null);

does not compile. The user ist forced to do something like

AddMode((TypeA)null);

Which should make him think, whether this is expected usage. So I think your API is OK as it is.

like image 71
Henrik Avatar answered Sep 28 '22 07:09

Henrik


I think that depends on how exceptional null as a value for the respective argument is.

Compare, for example, this ArgumentNullException constructor: It is most frequently called when an internal exception has to be set. Otherwise, this constructor, which excepts the name of the illegal argument, is passed. On odd occasions, the former has to be invoked because a custom message has to be supplied, but no internal exception is supplied (I usually do this when I'm throwing the exception for an array/collection argument that contains null, but is not null itself). So, in this case, I need the explicit cast, and I'd say it is acceptable there.

If your methods really do the same, but null is still a usual value, you might want to add a parameterless overload for the null variant (i.e. the explicit cast is still possible, but users can also call the parameterless overload instead).

If your methods do something somewhat different, and yet something else for null, you can think about disallowing null altogether for the methods you've shown and adding a parameterless overload for the null case.

Update: If null is not acceptable anyway (and will result in an exception), then you should leave the method as it is. Other than for testing purposes, there should never be any whatsoever situation in which a literal null would be passed to the method, as this will invariably yield an exception. Therefore, do not change your overload names in this case.

like image 41
O. R. Mapper Avatar answered Sep 28 '22 07:09

O. R. Mapper