1

I am making a manaCount object for an emulator game that I am working on.

The constructor looks as follows:

public ManaCount(int red, int white, int blue, int green, int black, int colorless){
    redManaCount = red;
    whiteManaCount = white;
    blueManaCount = blue;
    greenManaCount = green;
    blackManaCount = black;
    colorlessManaCount = colorless;
}

I don't see any way around using so many arguments in the constructor, but I was hoping that there was a way to make the instantiation of the manaCount object more descriptive than the following:

ManaCount test = new ManaCount(0,0,0,0,0,0);

As it appears currently, it is impossible to know which color goes in which argument without having seen the implementation. Are there any forms of java wizardry that can accomplish this?

Merceus
  • 61
  • 1
  • 6

2 Answers2

2

I would suggest you to Use Lombok. This is how you use @Builder .

//ManaCount.Java
import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class ManaCount {
    private final int redManaCount;
    private final int whiteManaCount;

    private final int blueManaCount;
    private final int greenManaCount;

    private final int blackManaCount;
    private final int colorlessManaCount;

}

Ussage:

//   ManaMain.java

public class ManaMain {

    public static void main(String[] args) {
        ManaCount manaCount = ManaCount.builder()
                .redManaCount(0)
                .whiteManaCount(0)
                .blueManaCount(0)
                .greenManaCount(0)
                .blackManaCount(0)
                .build();
        System.out.println(manaCount);
    }
}

Output :

ManaCount(redManaCount=0, whiteManaCount=0, blueManaCount=0, greenManaCount=0, blackManaCount=0, colorlessManaCount=0)
Mahendra Kapadne
  • 426
  • 1
  • 3
  • 10
1

Maybe it sounds very trivial but once you want to let an user to explicitly set your class components with their names articulated, it should be a good idea to use a no-argument constructor then some setters:

c = new ManaCount();
  c.setRed(red);
  c.setGreen(green);

If you still wish to implement such a mechanism via a constructor, you may want to use some constants defined in your class to identify components. If your constructor takes an array of component ids as its first argument and an array of component ids as its second argument, a call may look like

c = new ManaCount(new int[]{ManaCount.RED,ManaCount.GREEN}, new int[]{red, green});

Of course you may implement another variant of syntax to call a constructor with an user-defined id->value mapping lists, maybe taking an array of name-value pairs, or/and taking java.util.Map interface to initialize etc.

AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27