Today I Learned - Rocky Kev

TIL more clean code principles

POSTED ON:

TAGS:

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:

TIL not obsessively trying to be DRY

Quite often, DRY is applied to any duplication, rather than specifically to the duplication of business rules and knowledge. This is often made worse by automated code analysis tools, which will often highlight any duplication as a code smell.

TIL ways to organize eventListeners

Some code spaghetti I made recently was creating a lot of eventListeners for multiple buttons, and then forgot what they all connected to.

TIL Very Efficient Code

This is a great solution. Easy to understand. Executes really fast. No real-time string concatenation. No over-engineering. String appearance is easily customized.