Search code examples
javareadability

How best to make readable excessive constructor parameters


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?


Solution

  • 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)