首页 > 解决方案 > 使用 Groovy 和 Java 改进代码的最佳方法、技巧和示例

问题描述

我正在使用 BDD 敏捷方法来设计和创建一个新系统,但是我是代码重构的新手,你能帮我吗?我能做些什么来改进这段代码,以及你们每次想要改进代码时都遵循哪些提示。

十分感谢。

在这里您可以找到用于测试某些功能的 Groovy 代码:

package client

import com.resiflex.client.domain.Client

class DeleteSpec extends Base {
    def "delete client"() {
        given: "I have the code of client created"
        def clientCreatedResponse = clientService.createClient(clientName, clientColor, currentDescription)
        def code = null
        if (clientCreatedResponse.getObject() != null) {
            def clientCreated = (Client) clientCreatedResponse.getObject()
            ids.add(clientCreated)
            code = clientCreated.getCode()
        }
        when: "delete client"
        def result
        if (code == null) {result=clientService.deleteClientByCode(code ,tenants).getError().code} else if (tenants != "0"){
            result=clientService.deleteClientByCode(code ,tenants).getError().code
        }
        then: "client is deleted"
        expect == result
        where:
        clientName | clientColor | currentDescription      | tenants | expect
        "PCI"      | "#121273"   | "Positive Care Ireland" | "0"     | null
        "POCI"     | "#FF5FF5"   | "Positive Care"         | "1"     | 4022
        "POCIN"    | "#FF555F"   | "Positive Care"         | "0"     | null
        null       | null        | null                    | "0"     | 4021
    }

}

在这里您可以找到主要的 Java 类:

package com.resiflex.client.service;

import com.resiflex.client.domain.Client;
import com.resiflex.client.dto.ClientResponse;
import com.resiflex.client.utils.cleaner.StringCleaner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.resiflex.client.repository.ClientRepository;
import com.resiflex.client.utils.BusinessException;
import com.resiflex.client.utils.validators.ClientValidator;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClientService {
    @Autowired
    ClientRepository clientRepository;
    ClientValidator validator = new ClientValidator();
    StringCleaner cleaner = new StringCleaner();

    public ClientService(ClientRepository clientRepository) {
        this.clientRepository = clientRepository;
    }

    public ClientResponse createClient(String name, String color, String description) {
        ClientResponse response = new ClientResponse();
        try {
            String cleanName = cleaner.removeWhiteSpace(name, (short) 4003, "name");
            String cleanColor = cleaner.removeWhiteSpace(color, (short) 4004, "color");
            if (validator.isValidName(cleanName) && validator.isValidColor(color)) {
                if (validator.isUniqueName(clientRepository.findByName(cleanName.toUpperCase())) &&
                        validator.isUniqueColor(clientRepository.findByColor(cleanColor))) {
                    Client client = new Client();
                    client.setName(cleanName.toUpperCase());
                    client.setColor(cleanColor);
                    client.setCode(client.generateCode(0, 0, getClientCodes()));
                    client.setDescription(description);
                    clientRepository.save(client);
                    response.setObject(client);
                }
            }
        } catch (BusinessException be) {
            response.setError(be);
        } catch (Exception e) {
            response.setError(new BusinessException((short) 4007, "client_form"));
            e.printStackTrace();
        }
        return response;
    }

    public ClientResponse getAllClients(String status) throws BusinessException {
        ClientResponse response = new ClientResponse();
        try {
            response.setObject(clientRepository.findAllByStatus(status));
        } catch (Exception e) {
            response.setError(new BusinessException((short) 4015, "client_list"));
        }
        return response;
    }

    private List<String> getClientCodes() {
        List<String> codes = new ArrayList<>();
        for (Client cli : clientRepository.findAll()) {
            codes.add(cli.getCode());
        }
        return codes;
    }

    @Transactional
    public ClientResponse updateClientDesc(String code, String desc){
        ClientResponse resp = new ClientResponse();
        Client client = clientRepository.findByCode(code);
        if (client==null){
            BusinessException businessException = new BusinessException((short) 4016, "client_form");
            resp.setError(businessException);
        }else{
            if (desc.length()<=30) {
                client.setDescription(desc);
                resp.setObject(clientRepository.save(client));
            }else{
                BusinessException businessException = new BusinessException((short) 4008, "description");
                resp.setError(businessException);
            }
        }
        return resp;
    }

    @Transactional
    public ClientResponse updateClientColor(String code, String color){
        ClientResponse resp = new ClientResponse();
        Client client = clientRepository.findByCode(code);
        if (client==null){
            BusinessException businessException = new BusinessException((short) 4016, "client_form");
            resp.setError(businessException);
        }else try {
            String cleanColor = cleaner.removeWhiteSpace(color, (short) 4004, "color");
            if (validator.isValidColor(color)) {
                if (validator.isUniqueColor(clientRepository.findByColor(cleanColor))) {
                    client.setColor(cleanColor);
                    clientRepository.save(client);
                    resp.setObject(client);
                }
            }
        } catch (BusinessException be) {
            resp.setError(be);
        }
        return resp;
    }

    public ClientResponse deleteClientByCode(String code, String tenants) {
        ClientResponse resp = new ClientResponse();
        Client client = clientRepository.findByCode(code);
        if (client==null){
            BusinessException businessException = new BusinessException((short) 4021, "user_blank");
            resp.setError(businessException);
        }else{
            if (tenants.equalsIgnoreCase("0")) {
                clientRepository.delete(client);
                resp.setObject(null);
            }else{
                BusinessException businessException = new BusinessException((short) 4022, "delete");
                resp.setError(businessException);
            }

        }
        return resp;
    }

    public Client findByCode(String code) throws Exception {
        return clientRepository.findByCode(code);
    }
}

标签: javamongodbgroovyrefactoring

解决方案


只需记住几件事:

  • 使用truthy - 例如,您不需要检查某些内容是否为空。if (clientCreatedResponse.getObject() != null) {可以if (clientCreatedResponse.getObject()) {if (code == null)可以成为if (code)等。
  • 不要担心声明某些内容为空。如果它没有实例化,它肯定是空的。

  • 不要内联条件。if (code == null) {result=clientService.deleteClientByCode(code ,tenants).getError().code} else if (tenants != "0"){ 读起来很疯狂,令人不快。如果你真的想要它内联,你可以将它重构为三元组。话虽如此,您正在根据输入测试客户端调用的结果 - 我不建议使用来自客户端的条件结果编写测试 - 您应该重新构建测试。向客户提供输入,测试结果。话虽如此..

  • def clientCreatedResponse = clientService.createClient(clientName, clientColor, currentDescription)应该是你的def result =线。如果一条数据会影响结果,请将其作为矩阵的一部分。您的测试应该只包含设置、结果(作为您调用的代码段)和期望。将影响这一点的所有内容输入数据表,并删除除此之外的所有垃圾

推荐阅读