DEV Community

Wagner Negrão 👨‍🔧
Wagner Negrão 👨‍🔧

Posted on

Improving the way to use if in your code

The way we use 'ifs' is usually about validating a positive case, and if it is not that case then we should go to an Else, this form technically is not wrong, but we should pay attention to better ways to implement these validations.


if (user.isPresent()) {
    User.toDto(user.get())
    // More actions for success
} else {
    // Do something for error case
}

// continues the code

Enter fullscreen mode Exit fullscreen mode

Currently, languages of programming like Golang have a different way when using the 'if', which would be to validate the case of error if not exist, then should continue the normal flow of the code.

user, err := receiveUser()

if err != nil {
    return err
}

userDto := convertUser(user)

// continues the code flow
Enter fullscreen mode Exit fullscreen mode

We can see that this way of implementation is cleaner, this enables making code clean for whoever is reading.

Now we can see that code remains with the same complexity although cleaner, the way of validating the error case for the first seeks ensures the integrity of information as soon as it is received, bringing defensive programming to the code.


if (!user.isPresent()) {
    // Do something for error case
}

User.toDto(user.get())

// More actions for success
// continues the code flow

Enter fullscreen mode Exit fullscreen mode

A good way to practice this methodology is using the type 'Optional' that fits perfectly to what we need or creating ways to evaluate a possible error, such as, if you are receiving a list you must validate if it is empty and after making some interaction, another way, validate strings if are empty before the use. These are simple examples, but the idea here is to understand how to start this practice.

I always indicate to seek the type 'Optional', but when it is not possible, we can use this technique to try to help us build a more defensive and clean code.

It is worth remembering that this post is not saying what way to write 'if' it is better but to present a way cleaner to declare an 'if'.

Top comments (0)