如何消除空参数而不使用冗余代码
例如:
getBooks(author, title)
- 如果允许作者为空,将返回具有特定标题的所有书籍
- 如果允许标题为空,将返回特定作者的所有书籍
- 如果允许两者都为空,则将返回所有书籍,无论标题或作者
如何 消除this,具有以下功能:
getBooks(author)
getBooks(title)
getBooks(author, title)
getBooks()
在新函数中,可能存在冗余代码,或者如果我们将这些冗余代码分组到一个函数中,我们仍然会进入一个具有空参数的函数。有什么更好的方法来处理这个问题——没有冗余代码,也没有空参数?
For example:
getBooks(author, title)
- If allowing author to be null, would return all books with specific title
- If allowing title to be null, would return all books for the specific author
- If allowing both to be null, would return all books regardless of title or author
To eliminate this, have the following functions:
getBooks(author)
getBooks(title)
getBooks(author, title)
getBooks()
In the new functions, there might be redundant codes or if we group those redundant codes into a function, we will still get into a function having null parameters. What's a better way to handle this - no redundant code and no null parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要过载太多:
请注意,这不会减少代码重用:这些方法可以重用/共享它们在实现中需要的任何代码
Don't overload so much:
Note that this will not reduce code reuse: These methods could reuse/share whatever code they needed to in their implementations
您可以使用常量来表示要执行的搜索类型,并检查是否传递了参数(未经测试且已检查错误):
You could use a constant to denote what type of search to do, and check to see if a param was passed (very untested and error checked):
假设作者和标题是字符串,您可以执行以下操作:
因此您可以按如下方式使用此方法:
Assuming that author and title are Strings you can do the following:
So you can use this method as following:
尝试这种方法:
编辑:
更新以避免歧义。
Try this approach:
Edit:
Updated to circumvent ambiguity.