开发者

Single class with multiple constructor parameter values or many classes?

I have a class Response which contains a HTTP response with a HTTP status code like 200 or 404 and few other things like a view name and a domain object. But lets focus on the status code. I could use a single class and pass the status as a parameter:

public class Response {
  private int status;
  public Response(int status) {
    this.status = status;
  }
}

// in a handler method:

return new Response(HttpStatus.OK);

The other way would be to create a new class for every status code (41 status codes in HTTP 1.1). Like this:

public class Ok exten开发者_如何学运维ds Response {
  public Ok() {
    super(HttpStatus.OK);
  }
}

// in a handler method:
return new Ok();


public class Created extends Response {
  public Created() {
    super(HttpStatus.CREATED);
  }
}

// in a handler method:
return new Created();

In reality there will be usually more parameters like the view name and the domain object, like this new Response(HttpStatus.OK, "customer", customer) respective new Ok("customer", customer).


my recommendation 1) if there is no behavior associated with each status code then there is no need for new abstractions. 2) use enums for constants instead of int


The "pure" way would be to have a type for each distinct value, but in practice this may be overkill.

Generally speaking, consider whether:

  • There is any unique processing (which would lend itself to classes)

  • Whether there could be a hierarchy between the entities (e.g., statuses representing success and statuses representing errors).

In my experience, if there are hierarchies in the domain, they often end up in the code. You could save future refactoring by planning around that. For instance, error statuses may later also have things like error details tacked on.

My rule of thumb is to look at the specification in which the magic numbers appear. If they are each associated with a lot of details, that could indicate future problems if I merely keep them as ints, since I am essentially using a key to a more complex entity.

Also, when taking details from a fixed domain, an enum might be better than direct int.


Ask yourself - do you need different "types" for each status code? It could be useful if for example you want to use a specific type say OK as the parameter to some method. If not, I don't see any benefits of the second approach. Go for the first one.


I would keep the constructor simple. Something like:

public Response(int status)
public Response(int status, String reasonPhrase)
public Response(int status, Map<String,String> headers)
public Response(int status, String reasonPhrase, Map<String,String> headers)

Or, possibly, omit the last 2 and provide a setHeader(String, String)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜