Java处理的方法是null,然后是new [英] Java different approaches to handle if null then new

查看:123
本文介绍了Java处理的方法是null,然后是new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个关于处理空值的问题。这个问题可能在很大程度上基于意见,因此我将询问关于pro和cons的问题。



假设我有一个可以返回null的函数,或者一个JSONArray。我总是想要一个JSONArray,所以如果函数的结果为null,我希望它创建一个空的。



目前我有以下方法:

  jsonArray = jsonArray == null?new JSONArray():jsonArray; 

我喜欢这种方法,因为它是一行,并且非常清楚它的作用。这确实引出了我的问题,这是否有效?我已经知道现在它将执行 jsonArray = jsonArray 而不需要。虽然这似乎可以节省一次跳转,你可以使用 if(jsonArray == null)



什么是处理空值的不同方法的优点是什么?

解决方案

您是否看过Java 8的可选上课?这是一个对象包装器,它允许你以函数方式处理null。



例如,如果你有一个方法 public JSONArray getArray()你想要总是返回null以外的东西,你可以使用你的代码。使用Optional,它将更改为:

  public可选< JSONArray> getArray(){
// jsonArray来自某处
返回Optional.ofNullable(jsonArray);
}

如果jsonArray为null,则可选将为空;如果它不为null,它将包含jsonArray。



然后,您可以使用可选项指定的行为替换空检查。而不是

  JSONArray array = getArray(); 
if(array!= null){
//做点什么
}

你用

替换它

  getArray()。ifPresent(array  - > //做某事); 

这意味着您不需要创建空的JSONArrays,列表,集合或字符串,管他呢。如果包装对象实际为null,则从 Optional.ofNullable 返回singleton Optional,进一步减少开销。



<如果你仍想采用经典方法,那也是可能的。由于 if(option == null)应始终评估为 false (如果返回null而不是Optional,则为有点想念!),你要使用 if(option.isPresent())



如果你如果不使用Java 8,您可以编写自己的Optional或使用第三方库,例如Guava。



编辑:非Java 8解决方案



解决方案1 ​​



使用类似Guava的东西 - 看看 http://docs.guava-libraries.googlecode.com/git/javadoc/com/google /common/base/Optional.html



解决方案2



自己编写!在此实现中,供应商消费者谓词是接口返回,接受或测试对象。<​​/ p>

 公共抽象类选项< T>实现Iterable< T> {

private static final Option NONE = new None();

private Option(){
// no-op
}

public static< T>选项< T> of(T t){
return t == null? NONE:new Some< T>(t);
}

public static< T>选项< T> empty(){
返回NONE;
}

public abstract T get();

公共抽象T orElse(T fallback);

公共抽象T orElse(供应商< T>供应商);

public abstract< E extends Exception> T orThrow(供应商< E> exceptionSupplier)抛出E​​;

public abstract boolean isPresent();

公共摘要选项< T> filter(谓词< T>谓词);

public abstract void ifPresent(Consumer< T> consumer);

公共摘要< O>选项< O> ifPresent(函数< T,O>函数);

private static final class Some< T>扩展选项< T> {

私人最终T值;

private一些(最终T值){
this.value = value;
}

@Override
public T get(){
返回值;
}

@Override
public T orElse(最终T回退){
返回值;
}

@Override
public T orElse(最终供应商< T>供应商){
返回值;
}

@Override
public< E extends Exception> T orThrow(最终供应商< E> exceptionSupplier)抛出E​​ {
返回值;
}

@Override
public boolean isPresent(){
return true;
}

@Override
public Option< T> filter(final Predicate< T>谓词){
return predicate.test(value)?这个
:无;
}

@Override
public void ifPresent(final Consumer< T> consumer){
consumer.consume(value);
}

@Override
public< O>选项< O> ifPresent(最终函数< T,O>函数){
返回Option.of(function.apply(value));
}

@Override
public Iterator< T> iterator(){
返回Collections.singletonList(value).iterator();
}
}

私有静态最终类无< T>扩展选项< T> {
@Override
public T get(){
抛出新的IllegalStateException(value not defined);
}

@Override
public T orElse(final T fallback){
return fallback;
}

@Override
public T orElse(最终供应商< T>供应商){
return supplier.get();
}

@Override
public< E extends Exception> T orThrow(最终供应商< E> exceptionSupplier)抛出E​​ {
throw exceptionSupplier.get();
}

@Override
public boolean isPresent(){
return false;
}

@Override
public Option< T> filter(final Predicate< T>谓词){
返回此;
}

@Override
public void ifPresent(final Consumer< T> consumer){
// no-op
}

@Override
public< O>选项< O> ifPresent(最终函数< T,O>函数){
返回NONE;
}

@Override
public Iterator< T> iterator(){
return Collections。< T> emptyList()。iterator();
}
}
}


Okay, I've got a question about handling nulls. This question can be heavily based upon opinion, therefore I'm going to ask about pro's and cons.

Let's say I've got a function that can return null, or a JSONArray. I always want a JSONArray, so I want it to create an empty one if the function's result is null.

Currently I've got the following approach:

jsonArray = jsonArray==null?new JSONArray():jsonArray;

I like this approach as it's one line, and pretty clear what it does. This does lead me to the question though, is this efficient? I've got the idea that now it'll execute jsonArray = jsonArray while not needed. Though this does seem to save one jump you would have with an if (jsonArray == null)

What are the advantages of different ways of handling nulls?

解决方案

Have you taken a look at Java 8's Optional class? This is an object wrapper that lets you handle null in a functional way.

For example, if you have a method public JSONArray getArray() that you want to always return something other than null, you can use your code. Using Optional, it would change to this:

public Optional<JSONArray> getArray() {
    // jsonArray comes from somewhere
    return Optional.ofNullable(jsonArray);
}

In cases where jsonArray is null, the optional will be empty; in cases where it's not null, it will contain jsonArray.

You can then replace null checks with behaviour dictated by the optional. Instead of

JSONArray array = getArray();
if (array != null) {
    // do something
}

you replace it with

getArray().ifPresent(array -> // do something);

This means you don't need to create empty JSONArrays, or Lists, or Sets, or Strings, or whatever. In cases where the wrapped object is actually null, a singleton Optional is returned from Optional.ofNullable, further reducing overhead.

If you still want to take a classic approach, that's possible too. Since if (option == null) should always evaluate to false (if you return null instead of an Optional, you kind of miss the point!), you woud use if (option.isPresent()).

If you're not using Java 8, you can either write your own Optional or use a third-party library such as Guava.

EDIT: Non-Java 8 solutions

Solution 1

Use something like Guava - take a look at http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html

Solution 2

Write your own! In this implementation, Supplier, Consumer and Predicate are interfaces that return, accept or test an object.

public abstract class Option<T> implements Iterable<T> {

    private static final Option NONE = new None();

    private Option() {
        // no-op
    }

    public static <T> Option<T> of(T t) {
        return t == null ? NONE : new Some<T>(t);
    }

    public static <T> Option<T> empty() {
        return NONE;
    }

    public abstract T get();

    public abstract T orElse(T fallback);

    public abstract T orElse(Supplier<T> supplier);

    public abstract <E extends Exception> T orThrow(Supplier<E> exceptionSupplier) throws E;

    public abstract boolean isPresent();

    public abstract Option<T> filter(Predicate<T> predicate);

    public abstract void ifPresent(Consumer<T> consumer);

    public abstract <O> Option<O> ifPresent(Function<T, O> function);

    private static final class Some<T> extends Option<T> {

        private final T value;

        private Some(final T value) {
            this.value = value;
        }

        @Override
        public T get() {
            return value;
        }

        @Override
        public T orElse(final T fallback) {
            return value;
        }

        @Override
        public T orElse(final Supplier<T> supplier) {
            return value;
        }

        @Override
        public <E extends Exception> T orThrow(final Supplier<E> exceptionSupplier) throws E {
            return value;
        }

        @Override
        public boolean isPresent() {
            return true;
        }

        @Override
        public Option<T> filter(final Predicate<T> predicate) {
            return predicate.test(value) ? this
                                         : NONE;
        }

        @Override
        public void ifPresent(final Consumer<T> consumer) {
            consumer.consume(value);
        }

        @Override
        public <O> Option<O> ifPresent(final Function<T, O> function) {
            return Option.of(function.apply(value));
        }

        @Override
        public Iterator<T> iterator() {
            return Collections.singletonList(value).iterator();
        }
    }

    private static final class None<T> extends Option<T> {
        @Override
        public T get() {
            throw new IllegalStateException("value not defined");
        }

        @Override
        public T orElse(final T fallback) {
            return fallback;
        }

        @Override
        public T orElse(final Supplier<T> supplier) {
            return supplier.get();
        }

        @Override
        public <E extends Exception> T orThrow(final Supplier<E> exceptionSupplier) throws E {
            throw exceptionSupplier.get();
        }

        @Override
        public boolean isPresent() {
            return false;
        }

        @Override
        public Option<T> filter(final Predicate<T> predicate) {
            return this;
        }

        @Override
        public void ifPresent(final Consumer<T> consumer) {
            // no-op
        }

        @Override
        public <O> Option<O> ifPresent(final Function<T, O> function) {
            return NONE;
        }

        @Override
        public Iterator<T> iterator() {
            return Collections.<T>emptyList().iterator();
        }
    }
}

这篇关于Java处理的方法是null,然后是new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆