ID生成器代码重构问题(下)

本文详细介绍了如何通过接口设计、模块拆分、测试驱动和添加注释,优化Main.java和RandomIdGenerator类,使代码更易读、易于测试和维护。涉及到了提升代码结构、单元测试和注释规范。

在这里插入图片描述

第一轮:提升代码可读性
Main.java

  • IdGenerator修改为接口而非实现类
  • LogTraceIdGenerator继承IdGenerator
  • RandomIdGenerator作为 LogTraceIdGenerator的实现类
  • 将原来的generate函数细分几个子函数
  • 将魔法数替换为ASCII
  • generate() 函数中的三个 if 逻辑重复了,且实现过于复杂,我们要对其进行简化
package org.example;

public class Main {
    public static void main(String[] args) {
        LogTraceIdGenerator logTraceIdGenerator = new RandomIdGenerator();
        System.out.println(logTraceIdGenerator.generate());
    }

}

IdGenerator.java

package org.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public interface IdGenerator{
    String generate();
}
interface LogTraceIdGenerator extends IdGenerator {
}

class RandomIdGenerator implements LogTraceIdGenerator{
    private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);

    public String generate(){
        String substrOfHostName = getLastfieldOfHostName();
        long currentTimeMillis = System.currentTimeMillis();
        String randomString = generateRandomAlphameric(8);
        String id = String.format("%s-%d-%s",substrOfHostName,currentTimeMillis,randomString);
        return id;
    }

    private String getLastfieldOfHostName(){
        String substrOfHostName = null;
        try{
            String hostName = InetAddress.getLocalHost().getHostName();
            String[] tokens = hostName.split("\\.");
            substrOfHostName = tokens[tokens.length - 1];
            return substrOfHostName;
        }catch(UnknownHostException e){
            logger.warn("Failed to get the host name",e);
        }
        return substrOfHostName;
    }

    private String generateRandomAlphameric(int length){
        char[] randomChars = new char[length];
        int count = 0;
        Random random = new Random();
        while(count < length){
            int maxAscii = 'z';
            int randomAscii = random.nextInt(maxAscii);
            boolean isDigit = randomAscii >='0'&& randomAscii<='9';
            boolean isUppercase = randomAscii >='A'&&randomAscii<='Z';
            boolean isLowercase = randomAscii >='a' &&randomAscii <='z';
            if(isDigit || isUppercase || isLowercase){
                randomChars[count] = (char)(randomAscii);
                ++count;
            }
        }
        return new String(randomChars);
    }
}

第二轮:提升代码可测试性

  • generate函数定义为普通函数而非静态函数
  • 对于getLastfieldOfHostName()划分重要部分到子子函数getLastSubstrSplittedByDot中方便测试
  • logger不会影响代码逻辑的正确性,所以,我们没有必要 mock Logger 对象。
  • 添加 Google Guava 的 annotation @VisibleForTesting示意,仅仅用于测试
  • 将 generateRandomAlphameric() 和getLastSubstrSplittedByDot() 这两个函数的访问权限设置为 protected。目的:可以直接在单元测试中通过对象来调用两个函数进行测试。
package org.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public interface IdGenerator{
    String generate();
}
interface LogTraceIdGenerator extends IdGenerator {
}

class RandomIdGenerator implements LogTraceIdGenerator{
    private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);

    public String generate(){
        String substrOfHostName = getLastfieldOfHostName();
        long currentTimeMillis = System.currentTimeMillis();
        String randomString = generateRandomAlphameric(8);
        String id = String.format("%s-%d-%s",substrOfHostName,currentTimeMillis,randomString);
        return id;
    }


    private String getLastfieldOfHostName(){
        String substrOfHostName = null;
        try{
            String hostName = InetAddress.getLocalHost().getHostName();
            substrOfHostName = getLastSubstrSplittedByDot(hostName);
        }catch(UnknownHostException e){
            logger.warn("Failed to get the host name",e);
        }
        return substrOfHostName;
    }
    @VisibleForTesting
    protected String getLastSubstrSplittedByDot(String hostName){
        String[] tokens = hostName.split("\\.");
        String substrOfHostName = tokens[tokens.length-1];
        return substrOfHostName;
    }
    @VisibleForTesting
    private String generateRandomAlphameric(int length){
        char[] randomChars = new char[length];
        int count = 0;
        Random random = new Random();
        while(count < length){
            int maxAscii = 'z';
            int randomAscii = random.nextInt(maxAscii);
            boolean isDigit = randomAscii >='0'&& randomAscii<='9';
            boolean isUppercase = randomAscii >='A'&&randomAscii<='Z';
            boolean isLowercase = randomAscii >='a' &&randomAscii <='z';
            if(isDigit || isUppercase || isLowercase){
                randomChars[count] = (char)(randomAscii);
                ++count;
            }
        }
        return new String(randomChars);
    }
}

第三轮:添加单元测试

  • 使用了 JUnit 测试框架
package org.example;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;


public class RandomIdGeneratorTest {
    @Test
    public void testGetLastSubstrSplittedByDot(){
        RandomIdGenerator idGenerator = new RandomIdGenerator();
        String actualSubstr = idGenerator.getLastSubstrSplittedByDot("field1.field2.field3");
        assertEquals("field3",actualSubstr);

        actualSubstr = idGenerator.getLastSubstrSplittedByDot("field1");
        assertEquals("field1",actualSubstr);

        actualSubstr = idGenerator.getLastSubstrSplittedByDot("field1#field2#field3");
        assertEquals("field1#field2#field3",actualSubstr);
    }

    @Test
    public void testGetLastSubstrSplittedByDot_null0rEmpty(){
        RandomIdGenerator idGenerator = new RandomIdGenerator();
        String actualSubstr = idGenerator.getLastSubstrSplittedByDot(null);
        assertNull(actualSubstr);

        actualSubstr = idGenerator.getLastSubstrSplittedByDot("");
        assertEquals("",actualSubstr);
    }

    @Test
    public void testGenerateRandomAlphameric(){
        RandomIdGenerator idGenerator = new RandomIdGenerator();
        String actualRandomString = idGenerator.generateRandomAlphameric(6);
        assertNotNull(actualRandomString);
        assertEquals(6,actualRandomString.length());
        for(char c: actualRandomString.toCharArray()){
            assertTrue(('0'<=c && c<='9') || ('a' <= c &&c<='z')||'A'<=c && c<='Z');
        }
    }

    @Test
    public void testGenerateRandomAlphameric_lengthEqualsOrLessThanZero(){
        RandomIdGenerator idGenerator = new RandomIdGenerator();
        String actualRandomString = idGenerator.generateRandomAlphameric(0);
        assertEquals("",actualRandomString);

        actualRandomString = idGenerator.generateRandomAlphameric(-1);
        assertNull(actualRandomString);
    }
}

第四轮:添加注释

  • 做什么、为什么、怎么做、怎么用,对一些边界条件、特殊情况进行说明,以及对函数输入、输出、异常进行说明。
  • 在类或接口前添加注释补充
package org.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public interface IdGenerator{
    String generate();
}
interface LogTraceIdGenerator extends IdGenerator {
}


/**
 * Id Generator that is used to generate random IDs.
 *
 * <p>
 * The IDs generated by this class are not absolutely unique,
 * but the probalility of duplication is very low.
 */
class RandomIdGenerator implements LogTraceIdGenerator{
    private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);


    /**
     * Generate the random ID.The IDs may be duplicated only in extreme situation.
     *
     * @return an random ID
     */
    @Override
    public String generate(){
        String substrOfHostName = getLastfieldOfHostName();
        long currentTimeMillis = System.currentTimeMillis();
        String randomString = generateRandomAlphameric(8);
        String id = String.format("%s-%d-%s",substrOfHostName,currentTimeMillis,randomString);
        return id;
    }

    /**
     * Get the local hostname and
     * extract the last field of the name string splitted by delimiter '.'.
     *
     * @return the last field of hostname.Retruns nul if hostname is not obtained.
     */
    private String getLastfieldOfHostName(){
        String substrOfHostName = null;
        try{
            String hostName = InetAddress.getLocalHost().getHostName();
            substrOfHostName = getLastSubstrSplittedByDot(hostName);
        }catch(UnknownHostException e){
            logger.warn("Failed to get the host name",e);
        }
        return substrOfHostName;
    }
    /**
     * Get the last field of {@hostname} splitted by delemiter '.'.
     *
     * @param hostName should not be null
     * @return the last field of {@hostname}.Returns empty string if {@hostName} is empty string.
     */
    @VisibleForTesting
    protected String getLastSubstrSplittedByDot(String hostName){
        String[] tokens = hostName.split("\\.");
        String substrOfHostName = tokens[tokens.length-1];
        return substrOfHostName;
    }
    /**
     * Generate random string which
     * only contains digits,uppercase letters and lowercase letters.
     *
     * @param length should not be less than 0
     * @return the random string.Returns empty string if{@length} is 0
     */
    @VisibleForTesting
    protected String generateRandomAlphameric(int length){
        char[] randomChars = new char[length];
        int count = 0;
        Random random = new Random();
        while(count < length){
            int maxAscii = 'z';
            int randomAscii = random.nextInt(maxAscii);
            boolean isDigit = randomAscii >='0'&& randomAscii<='9';
            boolean isUppercase = randomAscii >='A'&&randomAscii<='Z';
            boolean isLowercase = randomAscii >='a' &&randomAscii <='z';
            if(isDigit || isUppercase || isLowercase){
                randomChars[count] = (char)(randomAscii);
                ++count;
            }
        }
        return new String(randomChars);
    }
}

以上,学完啦~
在这里插入图片描述

原链接:35 | 实战一(下):手把手带你将ID生成器代码从“能用”重构为“好用”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂java杰尼龟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值