Search code examples
javaapiprimitive

Avoid Primitives in API design?


I am designing an API. It will have a lot of methods which do the same, but have a different parameter primitives.

public void someMethod1(int x);
public void someMethod1(float x);
public void someMethod1(double x);
public void someMethod2(int x, int y);
...
public void someMethod3(int x, int y, int z);
...

Due to the primitives, I have to copy & paste a lot, which I think is quite unmaintainable over time. Is it a good idea to avoid primitives in methods and constructors? For instance, the replacement of the above will be:

public <T extends Number> void someMethod1(T x);
public <T extends Number> void someMethod2(T x, T y);
public <T extends Number> void someMethod3(T x, T y, T z);

Edit:

What are the downsides of this?


Solution

  • It will be usable, because of autoboxing / autounboxing in Java 1.5 and later. You can pass an int to something that expects an Integer, or vice versa, and the cast will happen automatically. The same applies to return values.

    Keep in mind that in the body of your method, you will know little more about your arguments than that they are some form of Number. This will only be suitable if you don't care to differentiate between integer and floating-point representations.

    It will not increase your performance - there will be some small penalty for the cast, but you shouldn't worry about that until you discover you have a bottleneck. For most applications, the difference will be insignificant.

    Whether you use a List rather than an array should really be decided by your design, but it is generally advisable to use a List unless an array is necessarily needed. Lists tend to be more flexible, don't need to be resized, have all of the benefits of the Collections API, etc.