8000 关于工具类 · Issue #71 · techiall/Blog · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

关于工具类 #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
techiall opened this issue May 6, 2020 · 0 comments
Open

关于工具类 #71

techiall opened this issue May 6, 2020 · 0 comments
Labels

Comments

@techiall
Copy link
Owner
techiall commented May 6, 2020

在写项目过程中,自己写了一些工具类,在此把自己的想法和做法记录一下。

Q: 关于工具类的命名 / 存放?

A: 工具类统一放在 util 包内,工具类统一以 xxxUtils 命名,Utils 结尾。如 TimeUtils

Q: 关于工具类的定义?

A: 以 TimeUtils 定义为例。

方式一,将构造方法私有化,再严格一点,在私有方法里面加个抛异常(防止通过反射调用,调用后会抛异常);final 修饰类说明不能被继承。

/**
 * @author techial
 */
public final class TimeUtils {
    private TimeUtils() {
        // throw new IllegalStateException("Utility class");
    }
}

方式二,巧用 abstract 关键字,抽象类不能被实例化,如果用反射去调用,会抛出异常。

你也可以继承这个抽象类,扩展这个工具类;不像方式一,不能继承扩展。

/**
 * @author techial
 */
public abstract class TimeUtils {

}

Q: 工具类方法怎么写?

A: public static 修饰方法,如果有传入的参数,尽量使用 @Nullable / @NonNull 注解,提醒调用者关于 null 情况检查。(加了注解 IDE 也会提醒)

这两个注解是 Spring 里面的,IDEA 也有提供对应的注解。

@nullable 对象可能为 null

@nonnull 对象不为 null

    /**
     * 返回今天零点 Instant
     */
    public static Instant todayZeroTimeInstant() {
        return Instant.now().truncatedTo(ChronoUnit.DAYS);
    }

import org.springframework.lang.Nullable;
import org.springframework.lang.NonNull;

    public static boolean between(@Nullable Long start, @Nullable Long end, @Nullable Long target) {
        if (start == null || end == null || target == null) {
            return false;
        }
        return target > start && target < end;
    }

other

关于工具类,个人还是偏向于使用 abstract 关键字来定义类,思路来源于 Spring 的工具类。

final 加私有构造方法根据有点麻烦,毕竟你还要多手写一个私有构造方法。

其实在项目中还有一类用的比较多,也就是常量类,定义和工具类类似。

public abstract class ProfileConst {
    public static final String DEV = "dev";
    public static final String PROD = "prod";
    public static final String TEST = "test";
}
@techiall techiall added the Java label May 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant
0