patternjavascriptMinor
Null checks in user validation
Viewed 0 times
nulluservalidationchecks
Problem
I would like to know an alternative, more elegant way to write the following method. I am especially not enthusiastic of the nested
if statement.hasUserSavedCredentials: function () {
var userName = Storage.get(CONFIG.app.storageUserName),
password = Storage.get(CONFIG.app.storagePassword),
result = false;
if (userName !== null && password !== null) {
if (userName.length > 0 && password.length > 0) {
result = true;
// save in state for faster retrivial
State.xx.isSaved = result;
State.xx.userName = userName;
State.xx.password = password;
} else {
result = false;
State.xx.isSaved = false;
}
}
return result;
},Solution
You can remove
And to get rid of the nested statements, you could use early returns:
Is it correct that when
result = false;, as result is already false.And to get rid of the nested statements, you could use early returns:
if (userName == null && password == null) {
return false;
}
if (userName.length <= 0 && password.length <= 0) {
State.xx.isSaved = false;
return false;
}
State.xx.isSaved = true;
State.xx.userName = userName;
State.xx.password = password;
return true;Is it correct that when
username is null, isSaved = false should not be set? Because if not, then you could just combine the two if statements, either in my example, or in yours.Code Snippets
if (userName == null && password == null) {
return false;
}
if (userName.length <= 0 && password.length <= 0) {
State.xx.isSaved = false;
return false;
}
State.xx.isSaved = true;
State.xx.userName = userName;
State.xx.password = password;
return true;Context
StackExchange Code Review Q#63237, answer score: 3
Revisions (0)
No revisions yet.