When to use Long vs long in java?

柔情痞子 提交于 2019-12-18 12:12:21

问题


Below is my Interface -

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

This is my Implementation of the Interface -

public class DatabaseClient implements IDBClient {

    @Override
    public String read(ClientInput input) {

    }
}

Now I have a factory which gets the instance of DatabaseClient like this -

IDBClient client = DatabaseClientFactory.getInstance();
....

Now I need to make a call to read method of my DatabaseClient which accepts the ClientInput parameter and below is the class for the same. This class was not written by me so that is the reason I am having a question on this and I am pretty much sure this is the wrong way of doing it.

public final class ClientInput {

    private Long userid;
    private Long clientid;
    private Long timeout_ms = 20L;
    private boolean debug;
    private Map<String, String> parameterMap;

    public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
        this.userid = userid;
        this.clientid = clientid;
        this.parameterMap = parameterMap;
        this.timeout_ms = timeout_ms;
        this.debug = debug;
    }
}    

So when customer make a call to read method of DatabaseClient, they will create the ClientInput parameter like this and then use the factory to get the Instance of DatabaseClient and then call the read method accordingly.

Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");

ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);

IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);

Problem Statement:-

  1. So my first question is does the userid, clientid, timeout_ms should be Long object or just simply long in ClientInput class?
  2. Second question I have is, it might be possible that customer can pass wrong information such as negative user ids, negative client id, negative timeout value etc etc.. Then where I should do this validation? Should I do this validation check in the constructor of ClientInput class or at some other place? What's the better way of doing this and how should I do the validation?

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


  1. As Long is wrapper class privimitive type long and Long is a class, which indicate its instance could be null. In my perspective use wrapper class is better than primitive type because there could have null state in it, which could tells us more information.
    In addition, wrapper class will automatically initialized with 0, it is good for lazy using.

  2. For data validation, I think you'd better do it in controller rather than DAO, then have a good method to handle this or alert user to modify them!




回答6:


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.




回答7:


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);


来源:https://stackoverflow.com/questions/21034955/when-to-use-long-vs-long-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!