异常判null工具类

118 阅读1分钟

工具类

为了避免空指针调用,我们经常会看到这样的语句

scss
复制代码
...if (someobject != null) {    someobject.doCalc();}...

最终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢?

精华回答

这是初、中级程序猿经常会遇到的问题。他们总喜欢在方法中返回null,因此,在调用这些方法时,也不得不去判空。另外,也许受此习惯影响,他们总潜意识地认为,所有的返回都是不可信任的,为了保护自己程序,就加了大量的判空。

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;

/**
 * @program: wym-parent
 * @description: 异常情况工具类
 * @author: 尉一民
 * @create: 2022-01-28 17:21
 **/
public class SafesUtil {
    public static <K, V> Map<K, V> of(Map<K, V> source) {

        return Optional.ofNullable(source).orElse(Maps.newHashMapWithExpectedSize(0));
    }

    public static <T> Iterator<T> of(Iterator<T> source) {

        return Optional.ofNullable(source).orElse(Collections.emptyIterator());
    }

    public static <T> Collection<T> of(Collection<T> source) {

        return Optional.ofNullable(source).orElse(Lists.newArrayListWithCapacity(0));
    }

    public static <T> Iterable<T> of(Iterable<T> source) {

        return Optional.ofNullable(source).orElse(Lists.newArrayListWithCapacity(0));
    }

    public static <T> List<T> of(List<T> source) {

        return Optional.ofNullable(source).orElse(Lists.newArrayListWithCapacity(0));
    }

    public static <T> Set<T> of(Set<T> source) {

        return Optional.ofNullable(source).orElse(Sets.newHashSetWithExpectedSize(0));
    }

    public static BigDecimal of(BigDecimal source) {

        return Optional.ofNullable(source).orElse(BigDecimal.ZERO);
    }

    public static Double of(Double source) {

        return Optional.ofNullable(source).orElse(0d);
    }

    public static String of(String source) {

        return Optional.ofNullable(source).orElse(StringUtils.EMPTY);
    }

    public static String of(String source, String defaultStr) {

        return Optional.ofNullable(source).orElse(defaultStr);
    }

    /**
     * 对象为空, 返回默认值
     *
     * @param source
     * @param defaultValue
     * @param <T>
     * @return
     */
    public static <T> T of(T source, T defaultValue) {

        return Optional.ofNullable(source).orElse(defaultValue);
    }

    public static <T> T first(Collection<T> source) {

        if (org.springframework.util.CollectionUtils.isEmpty(source)) {
            return null;
        }
        T t = null;
        Iterator<T> iterator = source.iterator();
        if (iterator.hasNext()) {
            t = iterator.next();
        }
        return t;
    }

    public static void run(Runnable runnable, Consumer<Throwable> error) {

        try {
            runnable.run();
        } catch (Throwable t) {
            error.accept(t);
        }
    }

}