DEV Community

Claire Lipskey
Claire Lipskey

Posted on

Developing with Empathy: Reusability

"Reusability", "Reusable Components"... we've all heard it before.

In my last post, I spoke about the Single Responsibility Principle. Now, if we take this idea and apply it to "reusable components" or "reusability" it makes total sense. But aside from reusable components, what other ways can we make our code more modular and reusable?

Let's put it in the context of the code below:

index.html

<script src="date.js" type="text/javascript"></script>
<form>
    <input type="date" id="date1" name="date1">
    <input type='date" id="date2" name="date2">
    <button>Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

date.js

document.addEventListener('submit', () => {
    let date1 = document.getElementById('date1').valueAsDate
    let date2 = document.getElementById('date2').valueAsDate

    console.log(Math.abs(parseInt(date1 / 60 * 60 * 1000 * 24) - parseInt(date2 / 60 * 60 * 1000 * 24)))
})
Enter fullscreen mode Exit fullscreen mode

This is a very rudimentary example, but I have found a lot in my experience as a front-end engineer that when writing code, sometimes there is not a thought to abstract something that could be calculated / used somewhere else.

How might we make the above code a bit more abstract? Or how might we break out some functionality to be able to be used elsewhere?

Take this modified code sample for example:

date.js

document.addEventListener('submit', () => {
    let date1 = document.getElementById('date1').valueAsDate
    let date2 = document.getElementById('date2').valueAsDate

    console.log(calculateDaysBetween(date1, date2))
});

function calculateDaysBetween(date1: Date, date2: Date): number {
    const toDays = 60 * 60 * 1000 * 24;
    return Math.abs(parseInt(date1 / toDays) - parseInt(date2 / toDays));
}
Enter fullscreen mode Exit fullscreen mode

The above takes the hard-to-read bit in the console.log() from the first script block and makes it easier to read and makes it so we can call it anywhere.

Writing code in a way that is very easy to read is caring for your fellow developer, and it makes it easier for you to come back to in a few months and not want to pull your hair out!

Happy abstracting!

Top comments (0)