Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact Java syntax for conditional arguments?

Tags:

java

syntax

What is the best (most compact) way to hand this situation: One or more arguments to a method call depends on some condition, while the rest of the arguments are identical?

For example-- you want to

DeathRay mynewWpn = new DeathRay(particle.proton, chassisColor.BLACK, oem.ACME)

if

enemy_composition == nature.ANTIMATTER

but

DeathRay mynewWpn = new DeathRay(particle.anti-proton, chassisColor.BLACK, oem.ACME)

if

enemy_composition == nature.MATTER

Obviously you can if-else but it looks unnecessarily long when there are a lot of arguments or more than one conditional argument. I have also done this creating an argument with an if-else beforehand and then calling the method. Again, that seems kind of clunky. Is there some sort of inline syntax similar to an Excel if-statement?

like image 533
Pete Avatar asked Sep 07 '26 09:09

Pete


1 Answers

You can do

new DeathRay(enemy_composition == nature.ANTIMATTER ? particle.proton : particle.anti-proton, chassisColor.BLACK, oem.ACME)

… but I think we can all agree that's hideous. It also assumes that there are only two kinds of particle.

Here are some better alternatives.

switch:

particle type;
switch (enemy_composition) { /* Assuming "nature" is an enum. */
  case ANTIMATTER : 
    type = particle.proton;
    break;
  case MATTER : 
    type = particle.antiproton;
    break;
}
DeathRay mynewWpn = new DeathRay(type, chassisColor.BLACK, oem.ACME);

enum method:

Add a method to your enum, Nature.

public enum Nature
{

  MATTER
  {
    public Particle getCounterWeapon()
    {
      return Particle.ANTIPROTON;
    }
  },
  ANTIMATTER
  {
    public Particle getCounterWeapon()
    {
      return Particle.PROTON;
    }
  };

  public abstract Particle getCounterWeapon();

}

Then use it.

DeathRay mynewWpn = new DeathRay(enemy_composition.getCounterWeapon(), chassisColor.BLACK, oem.ACME);

Map:

particle type = counterWeapons.get(enemy_composition);
DeathRay mynewWpn = new DeathRay(type, chassisColor.BLACK, oem.ACME);
like image 67
erickson Avatar answered Sep 09 '26 23:09

erickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!