-1

is there a way if repeat is "false", then i dont want to use repeat and repeatMode anymore ? Instead of Overload, Can method ignore those params ?

void task(String title,boolean repeat, String repeatMode){

}
Meghana
  • 111
  • 7
  • is there a way if param "repeat" is "false", then i dont want "repeat" and "repeatMode" anymore ? I want my method to ignore these – Meghana Jan 29 '20 at 21:35
  • 2
    Method overloading: `void task(String title) { task(title, false, null); }` – Andreas Jan 29 '20 at 21:37

2 Answers2

0

I think you are finding something different: overload. This is when you have two or more methods with the same name and return type, but different arguments. Then, you can have:

void task(String title){
 // do something
}

void task(String title, repeatMode){
 // do something and repeat in some monner
}

and somewhere when you know if repeat is true or not

if(repeat){
   task(title);
}else{
   task(title, repeatMode);
}
Renato
  • 2,077
  • 1
  • 11
  • 22
  • Thanks for your answer. Instead of overload, can method ignore those params when found false ? – Meghana Jan 29 '20 at 21:41
  • Sure, the body of a method doesn't have to use all the parameters it has available. Did I answer to your question? – Renato Jan 29 '20 at 21:44
  • But still the param repeatMode is taken by the method right? can i do the if condition in params list instead of doing it inside the method ? so that if it is false then method no need to bare with extra useless param – Meghana Jan 29 '20 at 21:52
  • @Meghana That kind of logic should be handled before your method call, not by the method itself. You would have a check for which method to call (with multiple parameters or with few parameters) in the code before you call the method. – Tim Hunter Jan 29 '20 at 21:53
  • 1
    No @Meghana, in Java you cannot have an if in parameters list – Renato Jan 29 '20 at 21:55
  • Thank You @Renato – Meghana Jan 29 '20 at 22:00
0

I believe something like this should be the structuring of the code, based on what else you have been asking:

void someMethodThatCallsTheOtherMethods() {
  boolean repeat = true; //or false, whatever it should be
  String title = "SomeTitle";
  String repeatMode = "SomeValue";

  if(repeat) {
    task(title, repeatMode);
  } else {
    task(title);
  }
}

void task(String title) {
  //Do something with title alone
}

void task(String title, String repeatMode) {
  //Do something with title and repeatMode
}

The check for which parameters to use for a method should be checked before the actual method call. You cannot determine that during the method call itself, so use a logic branch to determine that before the method call.

Tim Hunter
  • 826
  • 5
  • 10