Clean Code: Correctness

Clean Code: Correctness

Introduction

I got intentional about writing clean code some weeks ago.

I digged down into books and talks on clean code to shoot myself into a new stage of programming.

And sincerely, it's worth the time, am still learning and improving on what I have learnt, but I find it necessary and helpful to share what I have learnt.

Hopefully, I may help someone write better codes.

With all that said, let's move on to the main content:

What Is Clean Code

Basically, it is a code that is easy to understand and maintain.

However, I would like to give you more elaborate definition which I would use in discussing clean code henceforth.

A clean code is a code that is reliable, efficient, maintainable and usable.

What Is Code Correctness

Code correctness is one of the attribute of reliability.

Nothing would be reliable if it's not correct with respect to what is required.

A code is correct if it confirms to the requirements of the solutions to the problem about to be solved.

Task

Let's give a scenario where you are asked to feed the backend some user credentials given the following requirements:

  1. User must have a name.
  2. User should have a username which must be in lowercase.
  3. User must have a password.

Here are the three requirements for the task we are given.

Incorrect Solution

// "data" is the object from the form field

const feedBackend = (data) => {

const {name, username, password} = data

const url = "https://yourbackend.api/endpoint"

const userCred = {
        name: name, 
        username: username,
        password: password
} 

axios.post(url, userCred)
}

Correct Solution

// "data" is the object from the form field

const feedBackend = (data) => {

const {name, username, password} = data

const url = "https://yourbackend.api/endpoint"

//this ensures that no field is empty when submitting to the backend.
//thus fulfilling the "must" condition
if ( !name || !username || !password) {
 return
}

const userCred = {
        name: name, 
//this ensures that no matter the case the user used in filling the form, it is always converted to lower case before submitting 
        username: username.toLowerCase(),
        password: password
} 

axios.post(url, userCred)
}

Conclusion

What determines the correctness of a code is its conformity to requirements specified by the solution to the problem being solved. You should always work in line with the requirements given from your analysis of the problem.