1

I came across similar kind of solution to my problem but I need further info. According to my use case, I have created a method which takes two parameters in which one is required and the other is optional.

public void myMethod(Required req){ ... }

In my application there are lot of methods calling myMethod. I need to update it by adding one more not-required parameter to myMethod as in:

public void myMethod(Required req, NotRequired nr){ ... }

I want to add one optional parameter without affecting the pre-existing caller methods. I mean to say is that I want to call myMethod using the following ways:

Required req = new Required();
NotRequired nr = new NotRequired();
myMethod(req);
myMethod(nr);

I came across java optional parameter in methods which made me think that it is only possible in Java using Builder pattern but I guess my case here is pretty different. If it can be done any suggestions will be appreciated!

Siddharth Shankar
  • 489
  • 1
  • 10
  • 21

3 Answers3

4

What about creating two methods :

public void myMethod(Required req){ }

public void myMethod(Required req, NotRequired nr){ }

When you need just the method which took the Required param, then call the first one, If you need the method which need both required and non required call the second

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

You can just use both methods and myMethod(req) calls myMethod(req, nr):

public void myMethod(Required req){
    myMethod(req, new NotRequired());
}

public void myMethod(Required req, NotRequired nr){
    // ...
}

So you can either call myMethod(req) if you only want to use the required param or myMethod(req, nr) if you want to use both params.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
0

Overload your methods with different signatures. The signatures of the pre-existing methods do not change.