繁体   English   中英

如何减少多个采用不同类型1个参数的方法?

[英]How can I reduce multiple methods that take 1 parameter of different type?

我有以下代码:

public final boolean doesExistById(Long id) {
    return dataAccessObject.findById(id) != null;
}

public final boolean doesExistByName(String name) {
    return dataAccessObject.findByName(name) != null;
}

public final boolean doesExistByDisplayName(String displayName) {
    return dataAccessObject.findByDisplayName(displayName) != null;
}

public final boolean doesExistByWebId(String webId) {
    return dataAccessObject.findByWebId(webId) != null;
}

我的Product类具有属性id, name, displayName, wedId
dataAccessObject.findBy____()返回Product类型的对象(如果可以在数据存储中找到),如果不能,则返回null

如果可能的话,我想减少这段代码,因为我有很多对象需要上面的doesExist()模式。 客户端代码只会知道其中一个属性。


我想到的一个可能的解决方案是:

public final boolean doesExist(Long id, String name, String displayName, String webId) {..}

然后在使用if语句确定哪个字段具有值时使用null为未知字段调用它。 但还有另一种更优雅的方式吗?

您认识到所有这些方法中“确实存在”的部分完全相同,这使您希望避免重复它,但这些方法的“ByXxx”部分完全不同。

你得到的东西比你想做的要好得多。 不要更改方法签名,以要求调用者为除一个参数之外的所有参数提供空值。 这非常容易出错,因为它不会为人们可能错误地使用方法签名的各种不同方式提供编译时错误。

您可能想要考虑做的一件事是将“确实存在”的部分分成它自己的机制:

public final Optional<MyObj> byId(Long id) {
    return Optional.ofNullable(dataAccessObject.findById(id));
}

因此,不是说service.doesExistById(123) ,而是说service.byId(123).isPresent() 这在语义上表示相同的含义,但它被分解为单独的部分,这意味着您可以重用byId()byName()等,以用于需要实际对象的其他目的,而不仅仅是知道它是否存在。

您可以编写一个采用对象类型的方法我建议您查看此页面。 什么是反思,为什么它有用?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM