Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it standard way to use javaargs instead of overloading in Java?

Is it a standard way to code or any other alternatives are there? I thinking this a while about the code that I've written. Finally gave up and thought to check with you guys.

Here is the scenario I had.

private String functionNameXYZ(String a,String b) {
   //Logic goes here
}
private String functionNameXYZ(String a,String b,String c) {
   //Same logic goes here , Nothing much difference because of String c
}

So I tho ught to skip two functions for same purpose and I created a single function as below.

private String functionNameXYZ(String a, String b,String... c){
   return performlogic(a,b,(c.lenght!=0)? c[0]:null);
}
private String performlogic(String a,String b, String c) {
   //logic , return "string"
}

Which is standard way of coding? Was it to seperate logic into new method instead of repeating[Second case] or Was it other way? Kindly suggest if you find any better ways?

like image 547
hasanac Avatar asked Feb 08 '23 19:02

hasanac


2 Answers

If your only two valid options are two String arguments and three String arguments, using varargs is a tad overkill, and worse - it's confusing, as it implies that you could also pass five or ten or a gazillion arguments. Instead, you could do something much simpler:

private String functionNameXYZ(String a, String b) {
   functionNameXYZ(a, b, null);
}

private String functionNameXYZ(String a, String b, String c) {
   // One place for the logic
}
like image 65
Mureinik Avatar answered May 10 '23 21:05

Mureinik


Your first scenario is fine, except you want to maybe take any large bulk of common code in the functions and put it in a separate function (or more easily, have the function with less params call the one with more).

The overloading is fine, but rewriting the same code both places is not good practice.

Also, since Java doesn't have default parameters, I'm not too keen on having a public method's argument that is nullable, even if noted on the JavaDocs. Overloading is the way to go.

like image 27
ryuu9187 Avatar answered May 10 '23 21:05

ryuu9187