Конвертировать multi if-else в простой код лямбда-выражения в java - PullRequest
0 голосов
/ 04 января 2019

Я новичок в Lambda и хочу преобразовать свой простой код, который имеет множество if-else, в Lambda-код.Может кто-нибудь объяснить мне, как это сделать?Я не очень понимаю, как его построить

public void registerModule(HttpServletRequest req, ModuleType moduleType) {
    LOGGER.debug("Register New Module - " + moduleType.name());
    ModuleEntityGenerator moduleEntityGenerator = new ModuleEntityGenerator();
    try {
        if (!req.getParts().isEmpty() && !req.getParameterMap().isEmpty()) {
            ModuleEntityDao moduleEntityDao = moduleEntityGenerator.get(req, moduleType);
            if (moduleEntityDao != null) {
                if (processRegistryDal.getModule(moduleType, moduleEntityDao.getId()) == null) { // Check BA is not already exist
                    processRegistryDal.addNewModule(moduleEntityDao);
                } else { // If already exists just update the current row
                    processRegistryDal.updateModule(moduleEntityDao);
                }
            } else {
                LOGGER.error("The BA object is null. There is nothing to register");
            }
        } else {
            LOGGER.error("The rest request is empty.No info to register");
        }
    } catch (IOException e) {
        LOGGER.error("IO Error\n" + e.getMessage());
    } catch (ServletException e) {
        LOGGER.error("Servlet Error\n" + e.getMessage());
    }
}

Ответы [ 3 ]

0 голосов
/ 04 января 2019

Если вы просто реорганизуете свой код, вы не получите столько вложенных if операторов.

Например, отмените условия.Вместо:

if (a) {
    if (b) {
        // code here
    } else {
        // ERROR
    }
} else {
    // ERROR
}

Переверните его и используйте конструкции else-if:

if (! a) {
    // ERROR
} else if (! b) {
    // ERROR
} else {
    // code here
}

Дополнительным преимуществом является то, что короткая логика «ОШИБКА» обрабатывается прямо рядом сif условие, вместо того, чтобы появляться где-то намного ниже, где условие и действие были разделены слишком далеко друг от друга.

С вашим кодом это можно упростить следующим образом:

public void registerModule(HttpServletRequest req, ModuleType moduleType) {
    LOGGER.debug("Register New Module - " + moduleType.name());
    try {
        ModuleEntityDao moduleEntityDao;
        if (req.getParts().isEmpty() || req.getParameterMap().isEmpty()) {
            LOGGER.error("The rest request is empty.No info to register");
        } else if ((moduleEntityDao = new ModuleEntityGenerator().get(req, moduleType)) == null) {
            LOGGER.error("The BA object is null. There is nothing to register");
        } else if (processRegistryDal.getModule(moduleType, moduleEntityDao.getId()) == null) { // Check BA is not already exist
            processRegistryDal.addNewModule(moduleEntityDao);
        } else { // If already exists just update the current row
            processRegistryDal.updateModule(moduleEntityDao);
        }
    } catch (IOException e) {
        LOGGER.error("IO Error\n" + e.getMessage());
    } catch (ServletException e) {
        LOGGER.error("Servlet Error\n" + e.getMessage());
    }
}
0 голосов
/ 04 января 2019

Как насчет разделения каждого if на отдельный метод с низкой областью действия.

Основной метод выглядит очень просто.

public void registerModule(HttpServletRequest req, ModuleType moduleType) {
    LOGGER.debug("Register New Module - " + moduleType.name());

    try {
        if (!isRequestEmpty(req))
            addOrUpdateModule(createModule(req, moduleType));
    } catch (IOException e) {
        LOGGER.error("IO Error\n" + e.getMessage());
    } catch (ServletException e) {
        LOGGER.error("Servlet Error\n" + e.getMessage());
    }
}

Вспомогательные методы.Если разработчик нуждается в деталях, посмотрите на него.

private static boolean isRequestEmpty(HttpServletRequest req) {
    if (req.getParts().isEmpty() || req.getParameterMap().isEmpty()) {
        LOGGER.error("The rest request is empty.No info to register");
        return true;
    }

    return false;
}

private static ModuleEntityDao createModule(HttpServletRequest req, ModuleType moduleType) {
    ModuleEntityDao module = new ModuleEntityGenerator().get(req, moduleType);

    if (module != null)
        return module;

    LOGGER.error("The BA object is null. There is nothing to register");
    return module;
}

private void addOrUpdateModule(ModuleEntityDao module) {
    if(module == null)
        return;

    if(processRegistryDal.getModule(module.getModuleType(), module.getId()) == null)
        processRegistryDal.addNewModule(moduleEntityDao);
    else
        processRegistryDal.updateModule(moduleEntityDao);
}
0 голосов
/ 04 января 2019

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

public void registerModule(HttpServletRequest req, ModuleType moduleType) {
    LOGGER.debug("Register New Module - " + moduleType.name());
    try {
        if (req.getParts().isEmpty() || req.getParameterMap().isEmpty()) {
            LOGGER.error("The rest request is empty.No info to register");
            return;
        }

        ModuleEntityGenerator moduleEntityGenerator = new ModuleEntityGenerator();
        ModuleEntityDao moduleEntityDao = moduleEntityGenerator.get(req, moduleType);
        if (moduleEntityDao == null) {
          LOGGER.error("The BA object is null. There is nothing to register");
          return;
        }

        if (processRegistryDal.getModule(moduleType, moduleEntityDao.getId()) == null) { // Check BA is not already exist
            processRegistryDal.addNewModule(moduleEntityDao);
        } else { // If already exists just update the current row
            processRegistryDal.updateModule(moduleEntityDao);
        }
    } catch (IOException e) {
        LOGGER.error("IO Error\n" + e.getMessage());
    } catch (ServletException e) {
        LOGGER.error("Servlet Error\n" + e.getMessage());
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...