library api design: extra parameter for multiple methods

I am writing a Java API library for an existing REST API.

The REST API has a few postOperations (getPosts, getUserPosts, getGlobalPosts etc.) So I have a class for postOperations that exposes that. Now I need to add to all the operations the option to add a group of parameters (generalParameters).

What do you think is the better solution?

  1. Add a parameter to the current functions, which means that sometimes the user will have to pass null (it's actually 80% of the time).
  2. Add an overloading function to every operation that gets 2 parameters (this means adding 6-7 overloading methods to the class)

I know both ways work. And it's not a major issue in most applications, but when writing a library other would use it seems a bit more important to me.

What's your opinion? what is a better api to expose?

Answers


I would do something like this:

public void handle(some parameters) {
    //handle params
}
public void handle() {
    handle(null, null, -1, w/e);
}

Per your edit:

This code here uses option 2; they will never have to pass a null value if you add another overloaded method which doesn't take in anything, but passes null for them


Between those two choices, I prefer #1, unless backward compatibility is an issue. I think it's good to make the library users aware of the parameters and force them to make an intelligent decision as to whether to submit one.

Another way to do it is to have a context object for finer-grained control. Rather than treating generalParameters as a data structure, treat them as properties of the context:

class PostOperations {
  public void getPosts() {
    return getPostContext().getPosts();
  }

  public void getPostContext() {
    return new PostContext();
  }
}

class PostContext {
  public void setGeneralProperty1() {...}
  public void setGeneralProperty2() {...}
  public void getPosts() {...}
}

You can decide how to model your various get*Post methods. Depending on what they mean in your system, you can have PostContext have all of those methods, or you could have a state on PostContext that affects its getPosts() behavior (e.g. PostContext.setUserOnly(true)), or you could model it with a class hierarchy (e.g. class UserPostContext extends PostContext)


Need Your Help

Worklight - How to pass parameters in an adapter procedure invocation in Objective-C?

ios objective-c parameters worklight worklight-adapters

I've been searching and haven't found any answers. I would like to invoke an adapter procedure from my native iOS code. Based on research, this is the code to do that...

Ado multiple range select

excel excel-vba ado

I need get data from excel sheet from multiple range