Coding Style: Return expected last
Example: Person object
Given: A function that will return a user's full name, but only if first name and last name are present:
function getFullName() {
if (this.first_name && this.last_name) {
return this.first_name + ' ' + this.last_name;
}
/* More checks/validation
* ...
*/
return '';
}
Return the expected result as last statement.
More checks might follow after validating first name and last name not being empty.
function getFullName() {
if (!this.first_name || !this.last_name) {
return '';
}
return this.first_name + ' ' + this.last_name;
}
Example: Database connect function
The approach can also help to reduce code complexity:
function connect() {
if (db.connect()) {
if (db.selectdb()) {
return db.getConnection();
}
else {
return undefined;
}
}
else {
return undefined;
}
}
After refactoring:
function connect() {
if (!db.connect()) {
return undefined;
}
if (!db.selectdb()) {
return undefined;
}
return db.getConnection();
}
Cascading assignments
There might be cases when you need to get some result, using different methods in a cascading manner. To avoid overwriting an already set result, you might check it before:
let store = getCacheStore();
if (!store) {
store = getRemoteStore();
}
if (!store) {
store = getLocalStore();
}
Refactoring – I
A cleaner approach could be to use the do...while construct:
let store;
do {
store = getCacheStore();
if (store) break;
store = getRemoteStore();
if (store) break;
store = getLocalStore();
if (store) break;
} while (false);
Refactoring – II
It can be shorten like this (although it can be confusing or misleading; a code style checker might warn):
let store;
do {
if (store = getCacheStore()) break;
if (store = getRemoteStore()) break;
if (store = getLocalStore()) break;
} while (false);
Refactoring – III
For really simple cases like the ones shown (where the code has already been moved to separate functions), it can be reduced to the following code:
const store = getCacheStore() || getRemoteStore() || getLocalStore();
Comments
There are no comments yet.
Thanks for your contribution!
Your comment will be visible once it has been approved.
An error occured—please try again.
Add Comment