So my Programming professor wants me to write a Kingdom class with a variable name that's at least 12 characters long. Normally one would just implement this class with a String name variable and an error message if the invariant of 12 characters min is broken, something like this in Java:
import java.lang.annotation.AnnotationTypeMismatchException;
public class Kingdom {
private String name;
public String getName(){return name;}
public Kingdom(String name) {
if (name.length() < 12){
throw new IllegalArgumentException("name must have at least 12 characters");
}
this.name = name;
}
}
or that in Kotlin:
import java.lang.IllegalArgumentException
class KingdomName (name: String) {
public val name: String = if (name.length >= 12) name else throw IllegalArgumentException("name must have at least 12 characters")
}
But I wanna know if there is a more elegant path in which the "must have at least 12 characters" invariant can be defined right in the variable name itself, forcing my professor to input at least 12 characters for the name like we all are forced to assign integers from -2,147,483,648 to 2,147,483,647 to a variable from type int/Int.
Now I thought about making my name a char[] array and allowing only char arrays longer or equal to 12 in the constructor, something like this in fake-Java:
public class Kingdom {
private char[] name;
public Kingdom(char[<=12] name) { //this line cannot exist in real Java
this.name = name;
}
}
But is there a way?
I also consider inventing a new type called KingdomName that is identical to a char[] array but must always have at least 12 elements, but again, how do I do that?