Passing parameters cleanly
I'm writing an API wrapper for a web service and have methods that look like this:
public void login(String username, String password) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("username", username);
params.put("password", password);
makeRequest("/user/login", "POST", params);
}
This works, but is there a neater/cleaner way of writing this in Java? For example a different collection that doesn开发者_C百科't need <String, Object>
specified each time or a way to do it inline (in Javascript I'd be writing makeRequest("/user/login", "POST", {"username": username, "password": password});
). I have a feeling that Java needs you to be a bit more verbose like this but I'd like to find out earlier rather than later.
Your approach is good enough. I can't think of anything less verbose. Certainly you can't create dynamic objects like in JS.
Surely you can implement first your own method makeRequest() that accepts parameters in other format. Really makeRequest() is not a part of JDK. It is some other custom library (yours or third party). Somebody decided to implement it this way. You can either use other library or implement your own wrapper:
makeRequest(String url, String method, String[] paramNames, String[] paramValues);
You could try implementing a fluent API that could be used like this:
HTTP.request("/user/login").method(Method.POST).param("username", username).param("password", password).execute();
Depending on who you interpret "verbosity", it may or may not be more verbose, but at least you can easily chain the methods and they can be read.
You can implement this by making the request()
method return an object of a type that has a method()
method, a param()
method and an execute()
method and have all of those (except the last one) return an object of the same type:
public class HTTP {
public static HTTP request(final String URL) { // ... }
public HTTP method(final Method method) { // ... }
public HTTP param(final String name, final String value) { // ... }
public HTTPResult exec() { // ... }
}
I don't recommend this approach, but it's less "verbose"
public void login(final String username, final String password) {
makeRequest("/user/login", "POST", new HashMap(){
{
put("username", username);
put("password", password);
}
});
}
As for me, I always use wrapper object for key-value pairs:
public class Param {
private String key;
private String value
// Getters & Setters below
}
public void makeRequest(String uri, String method, Param... params) {
// your code here
}
public void login(String username, String password) {
makeRequest("/user/login", "POST", new Param("username", username), new Param("password", password));
}
精彩评论