Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,如何设计一个既通用、简单又可读的api_Java_Api_Oop - Fatal编程技术网

在java中,如何设计一个既通用、简单又可读的api

在java中,如何设计一个既通用、简单又可读的api,java,api,oop,Java,Api,Oop,我的例子是,我希望我的用户调用 findCustomers(...) 现在我的问题是关于这个方法的论点。 我有一个 对象,我希望用户能够使用库按客户名称和客户id进行搜索 现在我不想创建多个方法 findCustomerById(String id) findCustomerByName(String name) findAllCustomers() 相反,我想做的是这是一个通用的findCustomer /** if you pass only custoer.name and rest

我的例子是,我希望我的用户调用

findCustomers(...)
现在我的问题是关于这个方法的论点。 我有一个

对象,我希望用户能够使用库按客户名称和客户id进行搜索

现在我不想创建多个方法

findCustomerById(String id)
findCustomerByName(String name)
findAllCustomers()
相反,我想做的是这是一个通用的findCustomer

/** if you pass only custoer.name and rest of fields are null will search by name,
if you pass a null custoer object will return all customers, if you pass both custoer id and his name will search by both fields). **/
findCustomer(Customer customer)
现在我有一个通用的单一api方法,但我不喜欢在对象中传递null,我不喜欢null

有人对这种api有明确的最佳实践吗


谢谢你,而不是传递一个Customer对象,我想你还有很多其他的方法

findCustomer(String id, String name); // id or name can be null.

或者一个CustomerSearch对象,它可以有这些ID和名称,也可以有多个ID和名称。

类似于用于查询的流体api的东西怎么样:

List<Customer> matches = find(new CustomerQuery().withName("john(.*)").withId(42));
List matches=find(new CustomerQuery().withName(“john(.*)).withId(42));

您试图构建的内容被调用。这是可以的,但它有局限性:您的
Customer
类被重新设计为一个查询参数,使得它的一些代码无效或适得其反。例如,如果添加的验证要求名称仅包含字母,则无法使用通配符查询名称

解决这个问题的一种方法是提供一个专门设计用于处理查询参数的查询生成器类。查询对象本身可以包装用户传递的参数绑定的
映射
,让您的查询API将其分解,并将相应的数据传递给底层数据存储的查询

QueryObject<Customer> qObj = new QueryObject(Customer.class);
qObj.setParameter("FirstName", "Joe");
qObj.setParameter("LastName", "S*");
qObj.setParameter("ID", 123);
List<Customer> cust = findCustomers(qObj);
QueryObject qObj=新的QueryObject(Customer.class);
setParameter(“名字”、“乔”);
setParameter(“LastName”,“S*”);
qObj.setParameter(“ID”,123);
列表客户=findCustomers(qObj);

我投票支持CustomerSearch这是一个最具扩展性的想法。这就是API!如果我向Customer.java添加一个新字段,比如whatevernew字段,我需要更改此方法的签名!!这是api!万一我发现自己也需要在这个新领域做一个发现!如果开发API时最好不要添加以后可能要删除的功能,那么添加它要比删除它容易得多。+1对于使用新类型CustomerQuery而不是Customernow,我再看一下,您甚至可以构建一个查询工厂来避免这种笨拙的构造函数调用:QueryFactory.customer().withName(“john(.*)).olderThan(10)QueryFactory.customer()将是一个静态工厂方法,用于返回CustomerQueries。然后,您可以将同一查询工厂重新用于可能有的任何其他实体查询
QueryObject<Customer> qObj = new QueryObject(Customer.class);
qObj.setParameter("FirstName", "Joe");
qObj.setParameter("LastName", "S*");
qObj.setParameter("ID", 123);
List<Customer> cust = findCustomers(qObj);