-2

我有一种从数据库中检索记录的搜索方法,我想限制用户只能按名称搜索。我有一个SearchBy带有搜索参数列表的枚举,对于特定SearchBy方法,用户只能按某些值进行搜索。

public List<Book> getBooks(SearchBy identifierName,List<String> identifierList) throws UnsupportedOperationException{

    List<Book> resultList = new ArrayList<Book>();

    if (identifierName.equals(SearchBy.TITLE)) {
        //returns list of BookObjects
    } else if (identifierName.equals(SearchBy.AUTHOR)) {
        //returns list of BookObjects
    } else {
        throw new UnsupportedOperationException("Books can be retrieved only using book titles or author names");
    }
}

除了验证和抛出异常之外,我们如何才能清楚地表明只有值TITLEAUTHOR才允许作为标识符名称的输入?

4

2 回答 2

1

我没有使用它,但这个框架对您的要求很有意义:

Java 参数验证

检查(公共)方法和构造函数的前提条件的简单方法。在抛出 IllegalArgumentException 之前,可以检查所有参数。为参数值中的不便创建一致的消息。

于 2013-11-07T16:33:09.450 回答
1

It's hard to tell what you mean, but if you are trying to validate input to a method it's common to throw an IllegalArgumentException for bad inputs and the client code can then handle this as they desire.

You would typically do something like this to validate input to a method:

public void method(String name) throws InvalidArgumentException {

    if (isInvalid(name)) { 
        throw new IllegalArgumentException("The name is invalid");
    }
    else {
        // rest of method ...
    }
}

It's up to you to decide how to validate the actual name depending on the rules you want to enforce. You can then give a suitable message in the exception to explain why it might not have been valid. Perhaps a regex could be used for the validation code, but without knowing the validation requirements it's impossible to suggest one here.

于 2013-11-07T16:33:58.273 回答