Programmer this line of work for a long time, always infected with some bad habits, I will be infected with a let a person detest, but his habit with relish, also don’t want to change the kind of, it can be called obsessive-compulsive disorder, can also be called cleanliness. I will not allow my IDEA to have a little warning, yellow background, green wavy line, nothing is allowed, press F2 key must be like this

Of course, there’s no point in saying that, because there’s no how to do it, so today I’m going to start a new series on how to write Efficient and clean Java code, which means that all the cases in this series are going to be very rigorous and demanding. If someone says, “What does this little bit of performance matter?” Me: No, not a bit!

High efficiency: high efficiency in development and performance

Today’s first article uses static factory methods instead of constructors

The importance of Names

A thousand Hamlets for a thousand people, a thousand general response objects for a thousand items, like ApiResponse, ResponseResult, BaseResult, etc., and they’re all structured like this

public class BaseResult<T> implements Serializable {

    private static final long serialVersionUID = -9127050844792378533L;

    /** * Status code */
    private int code;

    /** * message */
    private String message;

    /** * The data object to return */
    private T data;

    public BaseResult(a) {}public BaseResult(int code, String message) {
        this(code, message, null);
    }

    public BaseResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
		// omit the get/set method
}
Copy the code

Usually we’ll define code as 0, or 200 or something to indicate a correct response, and anything else to indicate an error response.

The following is an example:

public BaseResult<Order> getOrder(a){
  Order order = new Order();
  return new BaseResult<>(0."Success", order);
}
Copy the code

At first glance, this may not seem like a problem, but if I tell you that code=0 is correct and then give you an example, you might be confused: what does 0 mean? Because zero is a magic value here. Or, the correct response code changes, and the project manager says, code=0 sucks, change it to 200! At this time… Die.

In this case, we can add a class to describe code, such as:

public interface ResultCode {
    /** * Correct response code */
    int SUCCESS = 0;
    /** * error response code */
    int FAILURE = -1;
}
Copy the code

The way of use has changed:

public BaseResult<Order> getOrder(a){
  Order order = new Order();
  return new BaseResult<>(ResultCode.SUCCESS, "Success", order);
}
Copy the code

Now, we have removed the magic value, and whatever the project manager says to change code to, we just change the value of resultcode.success.

Project Manager: Change code to character!

But! If you write the return value of each interface like this, you will find that the whole project is filled with new BaseResult<>(resultcode.success, “SUCCESS “, value), this line of code is identical except value, oh, this ugly code.

So we went ahead and added two static methods:

public static <T> BaseResult<T> success(T data){
  return new BaseResult<>(ResultCode.SUCCESS, ResultCode.SUCCESS_MESSAGE, data);
}

public static BaseResult<Void> failure(a){
  return new BaseResult<>(ResultCode.FAILURE, ResultCode.FAILURE_MESSAGE);
}
Copy the code

Add two constants to the ResultCode class:

String SUCCESS_MESSAGE = "Success";
String FAILURE_MESSAGE = "Failure";
Copy the code

If each new BaseResult<>(resultcode. SUCCESS, “SUCCESS “, order), the SUCCESS string will create a string object with each new BaseResult.

Improved use mode:

public BaseResult<Order> getOrder(a){
  Order order = new Order();
  return BaseResult.success(order);
}
Copy the code

Users no longer need to care what code is, cool~

Project manager: Change the code for me…. Development: Clap (applause)

You don’t have to create objects with every build

Sometimes the called interface does not need to return an argument, but only needs to respond with a true or failure. In this case, we need a success method with no arguments:

public static BaseResult<Void> success(a){
  return new BaseResult<>(ResultCode.SUCCESS, ResultCode.SUCCESS_MESSAGE);
}
Copy the code

Use:

public BaseResult<Void> createOrder(a){
  return BaseResult.success();
}
Copy the code

The success method returns the same object each time, but creates a new object each time. Ah, bad code!

Improvement:

public static final BaseResult<Void> SUCCESS = new BaseResult<>(ResultCode.SUCCESS, ResultCode.SUCCESS_MESSAGE);
public static final BaseResult<Void> FAILURE = new BaseResult<>(ResultCode.FAILURE, ResultCode.FAILURE_MESSAGE);

public static BaseResult<Void> success(a){
  return SUCCESS;
}
public static BaseResult<Void> failure(a){
  return FAILURE;
}
Copy the code

Here’s a quick fix for the Failure method

Now, a static object is used every time the success ‘method is called without arguments, and no repeat creation occurs! Cool!

Note that BaseResult that requires data should not do this, otherwise thread-safety issues will occur

The closed loop

Sometimes interfaces interact not only with pages, but also with services. What if we want to determine the response of other interfaces?

public void callOtherServer(a){
  BaseResult<Void> result = createOrder();
  if(result.getCode() == ResultCode.SUCCESS){
    / / right}}Copy the code

At this stage we can only do this, ah, this bad code again!

Improvement:

public boolean isSuccess(a){
  return this.code == ResultCode.SUCCESS;
}

public boolean isFailure(a){
  return this.code ! = ResultCode.SUCCESS; }Copy the code

Improved use mode:

public void callOtherServer(a){
  BaseResult<Void> result = createOrder();
  if(result.isSuccess()){
    / / right}}Copy the code

Elegant code!

summary

This article explains the nice thing about using static factory methods instead of constructors

First: encapsulate the construction logic with a good name

Second: sometimes you don’t need to create objects every time

Third: establish a logical closed loop

See if there is room for improvement in your project

The original address: zijiancode. Cn/archives/us…

If you want to know more exciting content, welcome to pay attention to the public account: programmer AH Jian, AH Jian in the public account welcome your arrival ~