On how to write code-smells-free code. Few tips, part I.

Read Time:2 Minute, 55 Second

You are here because you want to be better at software craftmanship. You’re at the right place. I will show you some examples of good and bad practices. What to do and what should be avoided. The series will be divided into parts.

Frankly speaking this is a sneak peak of the vast topic I’m going to raise. Firstly go and buy Robert C. Marint’s book “Clean code” – this book is considered a must when it comes to learning good coding practices. But firstly you can familiarize with those ideas by reading my articles. Let’s go.

1. String comparison

First of all we need to understand what comparing two objects means. In Java we use either “==” operator or .equals method. The first one checks whether two object are the same – or two references point to the same object. In this case when we compare two string we need to use .equals method.

string1.equals(string2);

The other important thing is to invoke .equals on the constant, not on the variable. It could throw NullPointerException otherwise.

public class Main {
    public static void main(String[] args) {
        final String THE_CONSTANT = "Love Java";
        String text = "";

        System.out.println(THE_CONSTANT.equals(text));
        System.out.println("sometext".equals(text));
    }
}

2. Null first!

When designing a method remember about returning the simpliest case at first. If your design allows returning null value from your method you should return it at first. Why? Program returns the value instantly instead of going through the whole method body.

   public String addTwo(Integer theNumber){
        if(theNumber == null){
            return "No value has been passed!";
        }
        return  "The result: " + (theNumber + 2);
    }

3. Return empty collection instead of a null.

It’s a good practice to return an empty collection instead of a null value. Returning null is going to create more work for us in the future. All methods which will invoke such a method will have to do a null check first which results in more boiler plate code to write.

    public List<String> stringify(List<Integer> numbers){
        if(numbers == null || numbers.isEmpty()){
            return Collections.emptyList();
        }
        return numbers.stream().map(number -> {
            if(number % 2 == 0){
                return "number: " + number + " is even";
            }else{
                return "number: " + number + " is odd.";
            }
        }).collect(Collectors.toList());
    }

4. Write small methods

The method should be doing one and only one thing. When you have written a method and you’d have to use a word “and” for describing its behaviour it’s bad. It has to be divided to smaller ones, each performing one action only. Look at the example:

    public User addUser(String userName){
        if(userName == null || "".equals(userName)){
            return;
        }
        emailSender.sendEmail("user " + userName + " has been added");
        logger.log("User" + userName + " hass been added");

        User user =  userCreator.createUser(userName);        
        user.setPass("some pass");

        return db.addUser(user);
    }

What does this method do? It check’s whether correct username was passed. It’s ok. Then it sends some email AND logs the event AND creates user AND sets password AND saves user to the db. All those actions should be performed one level higher or in separate methods. the .addUser method should be only adding user instead of doing all the other stuff showed here.

We can introduce some other layer of abstraction – a servie which will handle the process.

    public User addUser(String userName){
        if(userName == null || "".equals(userName)){
            return;
        } 

        return userService.addUser(userName);
    }

That’s it when it comes to part I of my series. See you round!.

Should you have any questions, don’t hesitate to reach me via linkedin, facebook, email or via comments.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x