When to use Long vs long in java?

前端 未结 7 1274
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 13:03

Below is my Interface -

public interface IDBClient {
    public String read(ClientInput input);
}

This is my Implementation of the Interfa

7条回答
  •  生来不讨喜
    2020-12-24 13:45

    The advantage of the Long class is that the value can be null. In your case, if no Long ID is supplied, if you quickly detect this with something like..

    public ClientInput(Long userid, Long clientid, Map parameterMap, Long timeout_ms, boolean debug) {
        if (userid == null) {
              throw new IllegalArgumentException("userid is null");
        }
    

    To your second question, you could place your ID validation in the constructor as well. This ensures that if the ID is null or invalid, a ClientInput can never be created. But there is no "best" answer for where you put this validation, it depends on the structure of the rest of your code, but ideally you want to catch such things as early as possible.

    public ClientInput(Long userid, Long clientid, Map parameterMap, Long timeout_ms, boolean debug) {
        if (userid == null || userid < USER_ID_MIN || userid > USER_ID_MAX ) {
              throw new IllegalArgumentException("userid is invalid");
        }
    

    Another option is to accept the userid parameter as a Long, testing it for null, but then store it as a private, primitive long, once you know its valid.

提交回复
热议问题