0

I have admittedly the following poorly implemented class:

public class Fari{
    String name;
    String[] group;

    public Fari(String name, String... group) {
        this.name = name;
        this.group = group;
    }
    // getters, setters
}

This was actually planned in such a way that the name and at least one group label is passed. But i can create a new Fari object with only one parameter without a compile erorr:

Fari f = new Fari("A");

ending in an object with null for the group attribute. Is there a way to force that at least one string should be passed as the varargs parameter?

I could change the parameter String... group to a List<String> but then I have to touch all other classes as well. Apart from that an empty list could be passed, which doesn't really help me. How do I go about this if the created object should have a name and at least one group lable?

nopens
  • 721
  • 1
  • 4
  • 20
  • 1
    Do you want to check it at compile time or at runtime? – Progman Aug 04 '19 at 20:36
  • 3
    If you require parameter to be passed, it is not vararg. You can change constructor as `public Fari(String name, String group, String... otherGroups)` to force at least one group to be specified – uaraven Aug 04 '19 at 20:38
  • @Progman During runtime at the at the most no object should exist without a group name. If it can already be checked during compilation it is of course even better – nopens Aug 04 '19 at 20:42

2 Answers2

3

The typical way to solve this would be have

public Fari(String name, String requiredGroup, String... group)
Matt Berteaux
  • 763
  • 4
  • 12
0

You can also check group size and throw error if the size is < 1. Something like this:

public class Fari {

    String name;
    String[] group;

    public Fari(String name, String... group) throws Exception {
        this.name = name;
        if (group.length < 1) throw new Exception();
        this.group = group;
    }
}

Of course you can use your own Exception implementation to identify it in your code.

Alex
  • 888
  • 2
  • 7
  • 21