1

I am trying to create a method which should accept minimum one and maximum two parameters. First parameter is must but second is optional.

I've tried following

myFunction(String param1, String param2){

}

But in this case both parameter need to be passed, which I don't want.

myFunction(String... params){
}

In this case it can accept more than two parameters also, which also I don't want.

Could someone please tell if it's accomplished in java?

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85

4 Answers4

5

Overload the method:

myFunction(String param1){
  ...
}

myFunction(String param1, String param2){
  ...
}

Consider making the "one parameter version" invoke the other version with a default value for the second parameter to simplify things.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
  • This could be done, however in this case I need to duplicate my whole logic. – Mehraj Malik Nov 08 '17 at 08:36
  • 2
    @MehrajMalik: In most cases, you'd just make the single-parameter overload call the two-parameter overload with a default value. No duplication needed. If you need to know which overload was called, create a third private method that the first two call, with three parameters: `param1`, `param2`, `param2UserSupplied` (the last being a boolean) or similar. – Jon Skeet Nov 08 '17 at 08:37
1

In this exact case, since both possible parameters are strings, you could refactor your method to accept an array of strings, and then validate inside the method, e.g.

void myMethod (String... params) throws IllegalArgumentException {
    if (params == null || params.length < 1 ||
        params.length > 2 || params[0] == null) {
        throw new IllegalArgumentException("wrong no. of arguments");
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

By overloading methods, you can achieve this with the following:

void foo(String param1, String param2) {
    // your logic here
}

void foo(String param1) {
    foo(param1, DEFAULT_VALUE_FOR_PARAM2);
}

Please see this answer for a complete overview of what is possible with optional arguments within Java.

Sync
  • 3,571
  • 23
  • 30
0

Maby will good to use overload approach? create two methods with same name but wit different attribute numbers

myFunction(param1)
myFunction(para1,param2)

Also, you can move the same logic from on abstract level, and use them on your myFunction().

Skytrace
  • 58
  • 4