java 番石榴前提条件检查,空列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12475532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:03:37  来源:igfitidea点击:

Guava precondition checks, empty List

javaguava

提问by Robottinosino

I would like to know what is the best pattern for precondition checks on a list from which I will need to pick the first item.

我想知道在我需要从中选择第一项的列表上进行前提条件检查的最佳模式是什么。

In words, I suppose the list should not be nulland its size should be > 1.

换句话说,我认为列表不应该是null它的大小应该 > 1。

I find Guava's checkPositionIndex not helpful in this respect. On the contrary, I find it counter-intuitive, see the example below which bombs on an empty list because I use checkPositionIndex rather than checkArgument, as outlined afterthe guard which does not trigger.

我发现 Guava 的 checkPositionIndex 在这方面没有帮助。相反,我觉得它违反直觉,请参阅下面的示例,因为我使用 checkPositionIndex 而不是 checkArgument,如未触发的守卫概述的那样,在空列表上进行轰炸。

It seems like checking position 0 is not sufficient to validate the argument even if I .get(0) from it?

即使我从它 .get(0) 中检查位置 0 似乎也不足以验证参数?

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import java.util.List;
import com.google.common.collect.Lists;
public class HowShouldIUseCheckPositionIndex {
  private static class ThingAMajig {
    private String description;
    private ThingAMajig(String description) {
      this.description = description;
    }
    @Override
    public String toString() {
      return description;
    }
  }
  private static void goByFirstItemOfTheseAMajigs(List<ThingAMajig> things) {
    checkNotNull(things);
    // Check whether getting the first item is fine
    checkPositionIndex(0, things.size()); // Looks intuitive but...
    System.out.println(things.get(0)); // Finally, help the economy!
    checkArgument(things.size() > 0); // This would have worked :(
  }
  public static void main(String[] args) {
    List<ThingAMajig> fullList =
        Lists.newArrayList(new ThingAMajig(
            "that thingy for the furnace I have been holding off buying"));
    List<ThingAMajig> emptyList = Lists.newLinkedList();
    goByFirstItemOfTheseAMajigs(fullList);
    // goByFirstItemOfTheseAMajigs(emptyList); // This *bombs*
  }
}

回答by axtavt

You should use checkElementIndex()instead.

你应该checkElementIndex()改用。

checkPositionIndex()ensures that the given position is a valid position to insert new element to (i.e. you can do add(0, obj)on empty list), not a valid index to get an element from.

checkPositionIndex()确保给定的位置是插入新元素的有效位置(即您可以add(0, obj)在空列表上执行),而不是从中获取元素的有效索引。

回答by Louis Wasserman

You don't need to do the check at all, in point of fact.

事实上,您根本不需要进行检查。

The list.get(0)call itselfwill already throw basically exactly the same error message.

list.get(0)调用本身就已经抛出基本上完全相同的错误消息。

But if you didwant to do the check explicitly, yes, use checkElementIndexor checkArgument(!list.isEmpty()).

但是,如果您确实想明确进行检查,是的,请使用checkElementIndexcheckArgument(!list.isEmpty())

回答by keyoxy

You can use valid4j with hamcrest-matchers instead (found on Maven Central as org.valid4j:valid4j)

您可以将 valid4j 与 hamcrest-matchers 一起使用(在 Maven Central 中作为 org.valid4j:valid4j 找到)

For preconditions and postconditions (basically assertions -> throwing AssertionError):

对于前置条件和后置条件(基本上是断言 -> 抛出 AssertionError):

import static org.valid4j.Assertive.*;

require(list, hasSize(greaterThan(0)));

Or for input validation (throwing your custom recoverable exception):

或用于输入验证(抛出您的自定义可恢复异常):

import static org.valid4j.Validation.*;

validate(list, hasSize(greaterThan(0)), otherwiseThrowing(EmptyListException.class));

Links:

链接:

回答by John B

Use checkElementIndex

使用checkElementIndex

It states:

它指出:

Ensures that index specifies a valid element in an array, list or string of size size. An element index may range from zero, inclusive, to size, exclusive

Ensures that index specifies a valid element in an array, list or string of size size. An element index may range from zero, inclusive, to size, exclusive

回答by Asaf

You can use the twitter-commonsimplementation of the checkNotBlankmethod. it validates that an Iterable is not null and not empty. here is the implementation:

您可以使用checkNotBlank方法的twitter-commons实现。它验证 Iterable 不为 null 且不为空。这是实现:

/**
* Checks that an Iterable is both non-null and non-empty. This method does not check individual
* elements in the Iterable, it just checks that the Iterable has at least one element.
*
* @param argument the argument to validate
* @param message the message template for validation exception messages where %s serves as the
* sole argument placeholder
* @param args any arguments needed by the message template
* @return the argument if it is valid
* @throws NullPointerException if the argument is null
* @throws IllegalArgumentException if the argument has no iterable elements
*/
public static <S, T extends Iterable<S>> T checkNotBlank(T argument, String message,
      Object... args) {
  Preconditions.checkNotNull(argument, message, args);
  Preconditions.checkArgument(!Iterables.isEmpty(argument), message, args);
  return argument;
}

Very simple and works on all iterables.

非常简单,适用于所有可迭代对象。