hwding hwding - 2 months ago 6
Android Question

How to make sure specific parameters are passed to the method?

For example, there is a method

public void set_gender(String gender) {}
, make sure only
"male"
or
"female"
is passed to this method without using enumeration.

Also, how to meet this demand when the method declaration is
public void set_gender(String... params) {}
?

If there's no such way to realize this, how could I give a warning in IDE when someone is passing a string that this method could not understand, just like how it works in Android Studio when I'm passing a value that is not a flag that defined inside a certain Class.

Answer

These are 4 ways I could think of:

  1. Use pre-defined method without parameter:

        public void setMale() { /* TODO: Implement */ }
    
        public void setFemale() { /* TODO: Implement */ }
    
  2. Keep setGender() but use boolean values as its parameter instead of plain String. true means it's male, false female (or the other way around):

        public void setGender(boolean male) { /* TODO: Implement */ }
    
  3. Keep setGender() while using String as its parameter, and throw an IllegalArgumentException if the supplied parameter does not comply with the scope:

        public void setGender(String gender) {
           if (!"male".equalsIgnoreCase(gender) && !"female".equalsIgnoreCase(gender)) {
               throw new IllegalArgumentException("Bad parameter");
           }
           /* TODO: Implement */ 
        }
    
  4. Just use enums which, frankly, was designed with this exact use cases in mind. Or IntDef if you're really that worried about performance.

Oh, and as an addition, this question you asked:

If there's no such way to realize this, how could I give a warning in IDE when someone is passing a string that this method could not understand, just like how it works in Android Studio when I'm passing a value that is not a flag that defined inside a certain Class.

They achieve this by using IntDef. ;)