TIL more clean code principles
POSTED ON:
TAGS: cleancode principles
I grabbed a handful of tips from this post: The Must-Know Clean Code Principles
Functions should either answer something or do something, but not both.
// This function is problematic.
function checkElementIfExists(elementId, elementType) {
const element = document.getElementById(elementId);
if (element) {
return true;
} else {
const newElement = document.createElement(elementType);
newElement.id = elementId;
document.body.appendChild(newElement);
return false;
}
}
// better alternative
function checkElementIfExists(elementId) {
const element = document.getElementById(elementId);
if (!element) return false;
return true;
}
function createElement(elementId, elementType) {
const newElement = document.createElement(elementType);
newElement.id = elementId;
document.body.appendChild(newElement);
}
function wrapperFunction(elementId, elementType = null){
If (!checkElementIfExists(elementId)) {
// the element doesn't exist, so create it
if (typeof elementType === 'undefined') {
throw new Error('Required argument is missing');
}
createElement(elementId, elementType);
}
// element exists
}
If you use third-party libraries, wrap them, so if they change, only your wrapper implementation needs to change.
This is a 'maybe', because it can add a lot of overhead.
One example being fontawesome.
font-awesome 4: <i class="fa fa-address-book" aria-hidden="true"></i>
font-awesome 5: <i class="fas fa-address-book"></i>
font-awesome 6: <i class="fa-solid fa-address-book"></i>
Had you wrapped it into a web component, you could have a lot more flexibility.
/* flexible */
<font-awesome name="address-book"></font-awesome>
Throwing errors makes code cleaner than checking for status values throughout the code.
I like this a lot. You should fail hard and fail often.
Related TILs
Tagged: cleancode