Question

How could I limit the user to creating objects with certain variable values? In other words, if some class has variables a, b, and c, the class should only be created if the value of c is part of a certain set of values. if the value of c is not in that set of values, then simply prevent the creation of that class object. This in reference to Java.

Was it helpful?

Solution

Yes, you can simply throw an exception in your constructor. If you're simply creating a guard statement to prevent someone from providing bad arguments, then that's fine.

public MyClass(int a, int b, int c)
{
    if(c != 1 && c != 2)
        throw new ArgumentException(...);
    ...
}

But if the calling code will want to know whether the arguments are valid before attempting to construct the object, you may be better off using some kind of Builder class to validate your parameters and allow you to programmatically know if there's going to be a problem beforehand.

OTHER TIPS

If you don't want to create an object to even check for its validity, try creating an instance via a static method of the same class that checks for the allowed parameters before returning an object/calling the constructor (which is private).

public class Test {

private String a;
private static final ArrayList<String> allowed_a = new ArrayList<>
                                        (Arrays.asList("a1", "a2", "a2"));
private Test(String a){
    this.a = a;
}

public static Test getObject(String poss_a){
    if(allowed_a.contains(poss_a))
    {
        return new Test(poss_a);
    }
    return null;
}

An object of the class would then be created as follows:

public static void main(String[] args) {

    Test object1 = Test.getObject("invalid_a");
    Test object2 = Test.getObject("a1");

    if (object1 == null) {
        System.out.println("Object1 could not be created.");
    }
    else{
        System.out.println("Object1 was successfully created.");
    }

    if (object2 == null) {
        System.out.println("Object2 could not be created.");
    }
    else{
        System.out.println("Object2 was successfully created.");
    }
}    

It returns the following output when run:

run:
Object1 could not be created.
Object2 was successfully created.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top