2012-12-15 28 views
4

我的例子是這樣的我希望我的用戶呼叫在java中我如何設計一個API既普通,簡單,可讀

findCustomers(...) 

現在我的問題是關於參數此方法。 我有一個

Customer.java 

對象,我希望用戶能夠使用圖書館的客戶名稱和客戶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,但我不我不喜歡這種方式,我把零件傳給了一個物體,我不喜歡零點。

任何人都有這樣一個API的明確最佳做法?

感謝

回答

8

怎麼有點像流體API進行查詢:

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

+1使用新類型的CustomerQuery而不是客戶 –

+0

現在我看到這一點,你甚至可以建立一個查詢工廠,以避免這個尷尬的構造函數調用: QueryFactory.customer()。withName(「john(。*) 「).olderThan(10) QueryFactory.customer()將是靜態工廠方法,返回CustomerQueries。那麼您可以重複使用相同的查詢工廠進行任何其他您可能擁有的實體查詢 – radai

1

不是傳遞了一個Customer對象,我認爲有許多其他方法,你可以有

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

或可以有這些或可能多個ID和名稱的CustomerSearch對象。

+0

我投票支持最具擴展性的CustomerSearch想法。 –

+0

這是API!如果我添加一個新字段Customer.java喜歡無論新的領域,我將需要改變這種方法的簽名!這是api!萬一我會發現自己也需要在這個新領域找到一個方法! – Jas

+0

如果您開發的API最好不要添加您可能希望稍後移除的功能,那麼添加它比移除它更容易。 –

3

你正在嘗試建立被稱爲Query By Example。它是可以的,但它有一定的侷限性:你的類被重新定義爲查詢參數,它的一些代碼無用或者適得其反。例如,如果添加要求名稱僅包含字母的驗證,則無法使用通配符查詢名稱。

解決此問題的一種方法是提供專門設計用於處理查詢參數的查詢構建器類。查詢對象本身可以包裝用戶傳遞的參數綁定的Map<String,Object>,讓您的查詢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); 
相關問題