0

How can I make a method parameter mandatory or optional based on another parameter in Java?

For example, I have a Java method public void example(int x, int y);. Now I want that if x is provided as 0, then method should be called without providing y, i.e. example(0); should work. However, if x is not 0 then method should also require y, i.e. example(1); should not work in this case.

Techy
  • 11
  • 3
  • 1
    This can be a coded logic for runtime, but not compile time. – Sid Mar 09 '22 at 07:18
  • Java has no optional arguments and you also can not enforce any of these contraints at compile-time. Unless you add specific annotations and compile with a plugin that checks those contraints. That said, if run-time is also okay, you can add two method overloads (one with, one without the second value) and then assert the check using a basic `if` at the beginning of the method, throwing an exception. That said, your setup is way too complex already and you should step back and go for a simpler design to achieve whatever you want to achieve with this in the first place. This is too error-prone. – Zabuzard Mar 09 '22 at 07:22
  • Note that the clean code answer would rather be: you have two methods: one that takes **zero** arguments, and one that takes **two** arguments (and the second throws an exception when the first argument is 0. And the real answer would be: to step back, and understand the requirements better, to then decide whats the best way of handling in java. – GhostCat Mar 09 '22 at 07:32

0 Answers0