Подтвердить что ты не робот

Является ли утверждение SWITCH и CASE в APEX в Salesforce?

Вместо этой базовой структуры с IF/THEN/ELSEIF/ELSE

int month = 8;
String monthString;
if (month == 1) {
    monthString = "January";
} else if (month == 2) {
    monthString = "February";
}
...  // and so on

было бы неплохо иметь

    int month = 8;
    String monthString;
    switch (month) {
        case 1:  monthString = "January";
                 break;
        case 2:  monthString = "February";
                 break;

        ..... // and so on

        case 12: monthString = "December";
                 break;
        default: monthString = "Invalid month";
                 break;
    }

Это повысит читаемость и облегчит отладку из-за ясности намерения.

4b9b3361

Ответ 2

    monthMap = new Map<Integer,String>();
    monthMap.put(1,'JAN');
    monthMap.put(2,'FEB');
    monthMap.put(3,'MAR');
    monthMap.put(4,'APR');
    monthMap.put(5,'MAY');
    monthMap.put(6,'JUN');
    monthMap.put(7,'JUL');
    monthMap.put(8,'AUG');
    monthMap.put(9,'SEP');
    monthMap.put(10,'OCT');
    monthMap.put(11,'NOV');
    monthMap.put(12,'DEC');

Затем сделайте get в соответствии со значением вашего целого месяца.

Не нужно писать большой if-else.

Ответ 3

Я добавил свои комментарии к другим ответам.

Пока этот вопрос действительно не отвечает на вопрос, я все еще думаю, что это хорошая идея бросить его здесь. Ненавижу видеть такие "самодельные библиотеки дат"...

DateTime someDate = System.now();
System.debug(someDate.format('MMM'));  // Jan, Feb etc.
System.debug(someDate.format('MMMM')); // January, February etc.

Это всегда будет на английском языке, даже если предпочтение текущего пользовательского языка отличается. Строка форматирования передается во внутренний метод Java, поэтому просто взгляните на http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Ответ 4

В то же время SFDC предоставляет собственный движок, поскольку для работы вы можете использовать небольшую утилиту 'framework' в качестве объектно-ориентированного оператора switch-case:

утилита Switch-Case

Пример использования:

public with sharing class SwitchCaseExample {

    public String result {get; set;}

    public static final String MSG_FROM_ACTION_1 = 'invoke action 1';
    public static final String MSG_FROM_ACTION_2 = 'invoke action 2';
    public static final String MSG_FROM_ACTION_3 = 'invoke action 3';
    public static final String MSG_FROM_ACTION_4 = 'invoke action 4';

    public void testSwitchCase(String value) {

        SwitchCaseHelper sch = new SwitchCaseHelper();  

        sch.switch(value)
            .case('value1', new Action1(this), SwitchCaseHelper.PUT_BREAK)
            .case('value2', new Action2(this), SwitchCaseHelper.PUT_CONTINUE)
            .case('value3', new Action3(this), SwitchCaseHelper.PUT_BREAK)
            .default(new Action4(this));
    }


    private class Action1 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action1(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_1;
            return null; 
        }
    }

    private class Action2 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action2(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_2;
            return null; 
        }
    }

    private class Action3 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action3(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_3;
            return null; 
        }
    }

    private class Action4 implements ActionContainer {

        private SwitchCaseExample outerCtx;

        public Action4(SwitchCaseExample outerCtx) {

            this.outerCtx = outerCtx;
        }

        public String doAction() {

            outerCtx.result = MSG_FROM_ACTION_4;
            return null; 
        }
    }

}

Интерфейс:

public interface ActionContainer {

    String doAction();

}

И реализация логики коммутационного блока

public with sharing class SwitchCaseHelper {

    public static final Boolean PUT_BREAK = true;
    public static final Boolean PUT_CONTINUE = false;

    public class SwitchCaseException extends Exception {}

    public static final String EXCEPTION_MESSAGE = 'Switch-Case construction must have one (and only one) "switch" statement';

    @TestVisible
    private Object switchOperand;

    @TestVisible
    private Boolean isCaseAfterBreakStatement;

    @TestVisible
    private Boolean isPreviousSwitch;

    public SwitchCaseHelper() {

        isCaseAfterBreakStatement = false;
    }

    public SwitchCaseHelper switch(Object switchOperand) {

        if (isPreviousSwitch != null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }
        isPreviousSwitch = true;
        this.switchOperand = switchOperand;
        return this;
    }

    public SwitchCaseHelper case(Object caseOperand, ActionContainer container, Boolean hasBreak) {

        if (isPreviousSwitch == null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }

        if (isPreviousSwitch) {
            isPreviousSwitch = false;
        }

        if (isCaseAfterBreakStatement) {
            return this;
        }

        if (switchOperand.equals(caseOperand)) {
            container.doAction();
            isCaseAfterBreakStatement = hasBreak;
        }

        return this;
    }

    public SwitchCaseHelper default(ActionContainer container) {

        if (isPreviousSwitch == null) {
            throw new SwitchCaseException(EXCEPTION_MESSAGE);
        }

        if (!isCaseAfterBreakStatement) {
            container.doAction();
        }
        return this;
    }
}