我必须完成的任务已经完成,但是我仍然想着一个问题。
我定义了以下接口:
package dao;
import java.sql.SQLException;
/**
* Get / save / delete a single instance from the db in RESTful fashion on the object
* @author kimg
*
* @param <T>
*/
public interface IDao<T> {
public void fetch(int id);
public void save() throws SQLException;
public void delete() throws SQLException;
}
Run Code Online (Sandbox Code Playgroud)
Purpose is to have all pojo's that are represented as database table entities implement these methods, so the user of the pojo's knows how to handle instances according to a pattern. I've taken this approach from Backbone (Javascript).
However, there are other methods that I liked to impose as class methods (static) on the Pojo class itself. The most obvious methods are things like:
List<Person> list = Person.fetchAll();
List<Person> list = Person.fetchAll(offset, limit);
int i = Person.countAll();
...
Run Code Online (Sandbox Code Playgroud)
I've found that having these methods defined by default offers great benefit, yet nothing forces a developer to implement them, as static methods can't be imposed by default. Also, users of the classes can't know for sure that they'll be able to use the static methods that they would otherwise expect by contract (in case of an interface); any typo in the method name, omitting any method can cause the smooth app workflow to break.
抓住这个陷阱的最优雅的解决方案是什么?
我发现默认定义这些方法会带来很大的好处,但没有什么强制开发人员实现它们,因为默认情况下不能强加静态方法。
如果这些方法如此有益,那么开发人员难道不想实施它们吗?至少他们是否了解所需的模式以及实现这些模式的用处?
此外,类的用户无法确定他们是否能够使用合同中预期的静态方法(在接口的情况下)
这是无关紧要的,因为静态方法不是虚拟的。用户确实知道他们想要调用其静态方法的类型实际上是否具有该方法。如果他们忘记了,编译器会很乐意告诉他们。
方法名称中的任何拼写错误、省略任何方法都可能导致流畅的应用程序工作流程中断。
我不确定我是否关注你。如果您谈论的是开发人员未能实现这些静态方法或错误地实现了这些方法,那么这就是代码审查的目的。您还可以编写自动化测试来反思性地验证方法的存在。我真的不明白这是一个比使用所需签名但不正确实现的方法更大的问题。
再次强调,静态方法不是虚拟的。每个静态方法调用的用户在编译时确切地知道正在调用哪个方法,因此知道这样的方法是否可用。如果他们想要某种特定的方法但没有,那么他们可以选择请求添加、自己添加或不添加。
捕捉这个陷阱的最优雅的解决方案是什么?
记录任何此类期望。让项目管理强制执行它们(如果他们拒绝这样做,那么也许它根本就不那么重要)。采用代码审查。编写自动化测试,也许是反思性测试。
| 归档时间: |
|
| 查看次数: |
397 次 |
| 最近记录: |