Home > Software design >  String attribute in class that can only assign to specific values
String attribute in class that can only assign to specific values

Time:11-20

I remember that there is a data structure that guarantees that a certain string can only receive specific values, it works like an interface or something. I don't remember exactly the name of this data structure and couldn't find it easily.

Let me try to explain the context.

Let's say I've got a class called Foo with the parameter position.

Class Foo {
   public static final String TOP = "TOP";
   public static final String BOTTOM = "BOTTOM";
   public static final String MIDDLE = "MIDDLE";

   private String position;

   Foo(String position){
        this.position = position;
   }
}

If I assign to position the values TOP, BOTTOM or Middle, position is going to accept. If I assign another value it will throw an exception.

new Foo(Foo.TOP)         // OK
new Foo(Foo.MIDDLE)      // OK
new Foo(Foo.BOTTOM)      // OK
new Foo("anystring")     // Throws Exception.

I know I could do a simple if else or switch and throw an exception, but I'd like to find this specific data structure.

CodePudding user response:

You should use enum for this to solve at that way.

Class Foo {
   public static enum Position {TOP, BOTTOM, MIDDLE};

   private Position position;

   Foo(String position){
        this.position = Position.valueOf(position);
   }
}

But keep in mind: enum is not a String. But on enum you can call toString(), and also can parse a String to enum, like I did.

  • Related