This question is in respects to Boolean not boolean (but I would be curious to know if its the same case for both). Let's say you have a function that is performing multiple checks on data, and in each case it has a specific response. You want the function to show case all the invalid inputs (and why they are invalid) so you want to check all the inputs (not just one and stop and return). Would it be a better approach to use a single Boolean value (like Boolean x = isValidEmail(String email)) and then deal with it if its invalid and reuse x in future checks so that you don't allocate additional memory, or should you do (Boolean x = isValidEmail(String email), Boolean y = isValidPassword(String password)). I hope this question isn't too confusing in the way I've formulated it. I've placed an example of the code Im trying to implement to give you an idea.
//Checking if email is valid
Boolean isValidEmail = registrationService.emailIsValid(user.getEmail());
if(!isValidEmail) {
model.addAttribute("invalidEmail", true);
}
//Checking if email length is valid
Boolean emailIsValidLength = registrationService.emailIsValidLength(user.getEmail());
if(!emailIsValidLength) {
model.addAttribute("invalidEmailLength", true);
}
As you see here, I create separate Boolean values. Is it better to reuse the first Boolean one and do
IsValidEmail = registrationService.emailIsValidLength(user.getEmail());
Instead of creating two separate instances of Boolean?
CodePudding user response:
It costs the same amount either way, after javac and the JIT have had the chance to optimize.
Write the clearest thing -- which means using a new variable.
(Note that this is related to how you're not "creating new instances," almost certainly only creating references to existing objects.)
CodePudding user response:
it depends on your case, are you going to use the boolean later on, or validation is a one time thing, this doesn't concern only the Object Boolean,
for one single use, I usually do this:
if(!registrationService.emailIsValidLength(user.getEmail());) {
model.addAttribute("invalidEmail", true);
}
//Checking if email length is valid
if(!registrationService.emailIsValidLength(user.getEmail());) {
model.addAttribute("invalidEmailLength", true);
}
if I need the boolean later on, I store the result in a variable, since why would you call the function again?
Storing the result in one single variable is also valid if you want to return a global error message.
Using seperate Boolean, doesn't hinder java performance at all, If I were you I would pay attention to data structures and time complexity.