Return first non-null value

前端 未结 8 1989
情歌与酒
情歌与酒 2020-12-14 07:17

I have a number of functions:

String first(){}
String second(){}
...
String default(){}

Each can return a null value, except the default. <

8条回答
  •  清歌不尽
    2020-12-14 07:55

    It isn't readable because you are dealing with a bunch of separate functions that don't express any kind of connection with each other. When you attempt to put them together, the lack of direction is apparent.

    Instead try

     public String getFirstValue() {
          String value;
          value = first();
          if (value != null) return value;
          value = second();
          if (value != null) return value;
          value = third();
          if (value != null) return value;
          ...
          return value;
     }
    

    Will it be long? Probably. But you are applying code on top of a interface that's not friendly toward your approach.

    Now, if you could change the interface, you might make the interface more friendly. A possible example would be to have the steps be "ValueProvider" objects.

    public interface ValueProvider {
        public String getValue();
    }
    

    And then you could use it like

    public String getFirstValue(List providers) {
        String value;
        for (ValueProvider provider : providers) {
           value = provider.getValue();
           if (value != null) return value;
        }
        return null;
    }
    

    And there are various other approaches, but they require restructuring the code to be more object-oriented. Remember, just because Java is an Object-Oriented programming language, that doesn't mean it will always be used in an Object-Oriented manner. The first()...last() method listing is very not-object oriented, because it doesn't model a List. Even though the method names are expressive, a List has methods on it which permit easy integration with tools like for loops and Iterators.

提交回复
热议问题