When to use Long vs long in java?

前端 未结 7 1275
爱一瞬间的悲伤
爱一瞬间的悲伤 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:33

    1 Long is the object orientated counter part of long. The difference is as follows, and it applies to Float to float, Integer to integer etc.

    • long is a primitive type, while Long is a Java class (and so it will inherit Object).
    • long must be assigned with a valid number, while Long can be null
    • long instances can't use the benefits of OO, while instances of Long are real Java objects
    • Long is a serializable so it will be very useful when doing file, database or network IO
    • long is more efficient than Long considering memory space and processing speed

    If you are doing heavy calculations, use primitive types. Otherwise if you're concerning more about design, the object counter parts will be very useful.

    2 Since you are not using any frameworks if I'm observing correctly, I suggest you make an interface like Validated with a method bool validate(). And every time you try to put a input into the database call validate in advance.

    0 讨论(0)
  • 2020-12-24 13:37

    I don't think there's a single correct answer. A few suggestions:

    • The biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values, the Long object will be helpful as null can indicate missing values. If you're using primitives, you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing.

    • My preference for validation logic is to throw some sort of custom ValidationException at the point at which the thing could fail. If you're just creating these things with a constructor, the simplest thing would be just to validate there, e.g.

       public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) throws ValidationException {          
      
            if (userid == null) throw new ValidationException("UserId is required"); 
                  ...etc, etc...
      }
      

    Ultimately, the ValidationException is only useful if you can catch it at a point where you can do something useful with it - echo it back to a user or whatever.

    0 讨论(0)
  • 2020-12-24 13:38

    1) Use Long if you need to treat the value as an object. Use long otherwise; it's more efficient.

    2) Judgement call, really. Putting it deeper means you're going to check even when the value is coming from a source you trust, but that may catch errors in other code. Putting it closer to the user input means you lose that deep sanity-check (and may need to check in more than one place) but avoids spending time checking things you've already checked. What's best depends on how you plan on using/enhancing this code in the future.

    0 讨论(0)
  • 2020-12-24 13:39

    long is a primitive, which must have a value. Simple.

    Long is an object, so:

    • it can be null (meaning whatever you like, but "unknown" is a common interpretation)
    • it can be passed to a method that accepts an Object, Number, Long or long parameter (the last one thanks to auto-unboxing)
    • it can be used an a generic parameter type, ie List<Long> is OK, but List<long> is not OK
    • it can be serialized/deserialized via the java serialization mechanism

    Always use the simplest thing that works, so if you need any of the features of Long, use Long otherwise use long. The overhead of a Long is surprisingly small, but it is there.

    0 讨论(0)
  • 2020-12-24 13:43

    I try to keep Bean objects as simple as possible, which would mean handling validation elsewhere - either in a separate Validator class or in a validate() method. The general algorithm is the same:

    • validateInputParametres()
    • readDb()

    I would do something like:

    final ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);
    validate(input); // throw/handle exceptions here
    
    final Map<String, String> paramMap = new HashMap<String, String>();
    paramMap.put("attribute", "segmentation");
    
    final IDBClient client = DatabaseClientFactory.getInstance();
    client.read(input);
    
    0 讨论(0)
  • 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<String, String> 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<String, String> 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.

    0 讨论(0)
提交回复
热议问题