4

I have read a lot of topics about code refactoring and avoiding of if else statements. Actually, I have a class where I am using a lot of if - else conditions.

private static String getXSIType(String fieldType) {
    if ("_freeFormText".equals(fieldType) || "_eMailAddress".equals(fieldType) || "_help".equals(fieldType)
            || "_hyperlink".equals(fieldType) || "_inlineText".equals(fieldType) || "_longText".equals(fieldType)
            || "_password".equals(fieldType) || "_phoneNumber".equals(fieldType) || "_richText".equals(fieldType)
            || "_textArea".equals(fieldType)) {

        return "platformCore:StringCustomFieldRef";

    } else if ("_integerNumber".equals(fieldType)) {
        return "platformCore:LongCustomFieldRef";

    } else if ("_multipleSelect".equals(fieldType)) {
        return "platformCore:MultiSelectCustomFieldRef";

    } else if ("_document".equals(fieldType) || "_listRecord".equals(fieldType) || "_image".equals(fieldType)) {
        return "platformCore:SelectCustomFieldRef";

    } else if ("_currency".equals(fieldType) || "_decimalNumber".equals(fieldType)
            || "_percent".equals(fieldType)) {
        return "platformCore:DoubleCustomFieldRef";

    } else if ("_checkBox".equals(fieldType)) {
        return "platformCore:BooleanCustomFieldRef";

    } else if ("_date".equals(fieldType) || "_datetime".equals(fieldType) || "_timeOfDay".equals(fieldType)) {
        return "platformCore:DateCustomFieldRef";

    }
    return "platformCore:StringCustomFieldRef";
}

Now, I would like to use something else, instead of those if else conditions, but I don't know what.

Can you please give me an example or a good tutorial page?

Thank you

Vladas Maier
  • 2,054
  • 2
  • 22
  • 34

4 Answers4

7

Here is what you need:

private static String getXSIType(String fieldType) {
    String result=new String();
    switch (fieldType)
    {
        case "_checkBox":
            result="platformCore:BooleanCustomFieldRef";
            break;
        case "_integerNumber":
            result="platformCore:LongCustomFieldRef";
            break;
        case "_multipleSelect":  
            result="platformCore:MultiSelectCustomFieldRef";
            break;

        case "_currency":
        case "_decimalNumber":
        case "_percent":
            result="platformCore:DoubleCustomFieldRef";
            break;

        case "_document":
        case "_listRecord":
        case "_image": 
            result="platformCore:SelectCustomFieldRef";
            break;
        case "_date":
        case "_datetime":
        case "_timeOfDay":
            result="platformCore:DateCustomFieldRef";
            break;

        case "_freeFormText":
        case "_eMailAddress":
        case "_help":
        case "_hyperlink":
        case "_inlineText":
        case "_longText":
        case "_password":
        case "_phoneNumber":
        case "_richText":
        case "_textArea":
            result="platformCore:StringCustomFieldRef";
            break;      
        default:
            result="platformCore:StringCustomFieldRef";
            break;
    }
    return result;
}
Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
The KNVB
  • 3,588
  • 3
  • 29
  • 54
2

Combination of enum and switch statement comes handy for your example:

private static String getXSIType(String fieldType) {

    FieldType foundFieldType = FieldType.findByValue(fieldType);
    if(foundFieldType == null) {
        return CustomFieldRef.STRING.getValue();
    }
    switch(foundFieldType) {
    case FREE_FORM_TEXT:
    case EMAIL_ADRESS:
    case HELP:
    case HYPERLINK:
    case INLINE_TEXT:
    case LONG_TEXT:
    case PASSWORD:
    case PHONE_NUMBER:
    case RICH_TEXT:
    case TEXT_AREA:
        return CustomFieldRef.STRING.getValue();
    case INTEGER_NUMBER:
        return CustomFieldRef.LONG.getValue();
    case MULTIPLE_SELECT:
        return CustomFieldRef.MULTI_SELECT.getValue();
    case DOCUMENT:
    case LIST_RECORD:
    case IMAGE:
        return CustomFieldRef.SELECT.getValue();
    case CURRENCY:
    case DECIMAL_NUMBER:
    case PERCENT:
        return CustomFieldRef.DOUBLE.getValue();
    case CHECK_BOX:
        return CustomFieldRef.BOOLEAN.getValue();
    case DATE:
    case DATETIME:
    case TIME_OF_DAY:
        return CustomFieldRef.DATE.getValue();
    default:
        return CustomFieldRef.STRING.getValue();
    }
}

enum FieldType {

    FREE_FORM_TEXT("_freeFormText"),
    EMAIL_ADRESS("_eMailAddress"),
    HELP("_help"),
    HYPERLINK("_hyperlink"),
    INLINE_TEXT("_inlineText"),
    LONG_TEXT("_longText"),
    PASSWORD("_password"),
    PHONE_NUMBER("_phoneNumber"),
    RICH_TEXT("_richText"),
    TEXT_AREA("_textArea"),
    INTEGER_NUMBER("_integerNumber"),
    MULTIPLE_SELECT("_multipleSelect"),
    DOCUMENT("_document"),
    LIST_RECORD("_listRecord"),
    IMAGE("_image"),
    CURRENCY("_currency"),
    DECIMAL_NUMBER("_decimalNumber"),
    PERCENT("_percent"),
    CHECK_BOX("_checkBox"),
    DATE("_date"),
    DATETIME("_datetime"),
    TIME_OF_DAY("_timeOfDay");

    private final String value;

    FieldType(String fieldType) {
        this.value = fieldType;
    }

    public static FieldType findByValue(final String value) {
        return Arrays.stream(FieldType.values())
                .filter(o -> StringUtils.equals(o.value, value))
                .findFirst()
                .orElse(null);
    }
}

enum CustomFieldRef {

    STRING("String"),
    LONG("Long"),
    DOUBLE("Double"),
    BOOLEAN("Boolean"),
    DATE("Date"),
    SELECT("Select"),
    MULTI_SELECT("MultiSelect");

    private final String value;

    CustomFieldRef(String customFieldRef) {
        this.value = customFieldRef;
    }

    public String getValue() {
        String prefix = "platformCore";
        String suffix = "CustomFieldRef";
        return String.format("%s:%s%s", prefix, value, suffix);
    }
}

There is no need for a break in this case because the return stops the execution of the getXSIType() function.

In a switch statement you can not use the || operator but instead, you can define fall through statements:

...
case PHONE_NUMBER:
case RICH_TEXT:
case TEXT_AREA:
    return CustomFieldRef.STRING.getValue();

This is equivalent to:

if(FieldType.findByValue(fieldType).equals(FieldType.PHONE_NUMBER)
|| FieldType.findByValue(fieldType).equals(FieldType.RICH_TEXT)
|| FieldType.findByValue(fieldType).equals(FieldType.TEXT_AREA)) {
    return CustomFieldRef.STRING.getValue();
}

A switch statement can have an optional default case, which must appear at the end of the switch statement. It can be used for performing an action when none of the cases above is true.

Vladas Maier
  • 2,054
  • 2
  • 22
  • 34
1

You can try stream() and it's functions: map and filter. Also You can try doing ArrayList of strings and then check in loop (or preferably loop in other function) if they equals fieldtype. If one of them does, you return true, else, you return false.

A little help for now might be adding function checking if it equals fieldtype (it'll be just a tiny bit shorter).

  • Hi, welcome to stack overflow, with a little work, this can become a great answer, if you include some code. As you have given multiple solutions, I'd recommend picking which one you think is the best to elaborate, and leave the others as suggestions to try. – Ryan Leach Oct 23 '18 at 10:13
0

Here is the example of doing it using Enum and matches expression which makes the code more readable.

import java.io.IOException;

public class Test {
    public enum Types{
        INTEGER_NUM("_integerNumber"), MULTI_SELECT("_multipleSelect"), DOC("_document"), CURRENCY("_currency"), CHK_BOX("_checkBox"), DATE("_date"),
        DEC_NUM("_decimalNumber"), LIST_RCRD("_listRecord"), IMG("_image"), DTTM("_datetime"), TIMESTAMP("_timeOfDay");

        private String type ;
        private Types(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }   
        public static Types getEnum(String str){
            for (Types type : Types.values()) {
                if(type.getType().equalsIgnoreCase(str)){
                    return type;
                }
            }
            return null;
        }   
    }   
    private static String getXSIType(String fieldType) {

        if(fieldType.matches("_freeFormText|_eMailAddress|_help|_hyperlink|_inlineText|_longText|_password|_phoneNumber|_richText|_textArea")){
            return "platformCore:StringCustomFieldRef"; 
        }   
        switch (Types.getEnum(fieldType)) {
        case INTEGER_NUM:   return "platformCore:LongCustomFieldRef";
        case MULTI_SELECT:  return "platformCore:MultiSelectCustomFieldRef";
        case DOC:           
        case LIST_RCRD:     
        case IMG:           return "platformCore:SelectCustomFieldRef";
        case CURRENCY:     
        case DEC_NUM:       return "platformCore:DoubleCustomFieldRef";
        case CHK_BOX:       return "platformCore:BooleanCustomFieldRef";
        case DATE:          
        case DTTM:          
        case TIMESTAMP:     return "platformCore:DateCustomFieldRef";       
        default:            return "platformCore:StringCustomFieldRef";
        }
    }
    public static void main(String[] args) throws IOException { 
        System.out.println(getXSIType("_integerNumber"));
    }
}
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37