Clean Code – Part 04

Hello, how are you? To make our code cleaner, let’s keep the study about Clean Code? The others articles you will find here: Part OnePart TwoPart Three.

Today the subject will be Constants and Exceptions.

  • Constants name pattern – The Constant name has its name written with high caps “COLOR”; and will receive “_” when is a composite name “OWN_GOAL”. You don’t have to start a Constant name with “_” because there is no need for it; this was a name pattern created, in another development language, to make distinct the methods of the attributes.
  • Constants name should explain its use – A Constant gets clear thanks to its name which must be objective. Constants name must be understandable wherever it’s placed. Imagine you got a Constant used to log messages, if we just name it as LOG it would not be a clear name as LOGGER. There is a difference in the meaning of the words, LOG is “something” created and LOGGER is the creator. Wherever the LOGGER name is, we always will understand its usability.
  • When Constants are needed – We always should be looking for repetitions in our code. Always that we repeat an action or value there is something wrong happening. Image we have a method that modifies soccer game score:
    public void changeScore(Team team, int goal){
        this.fullScore(team, gol);
    }

    And this method is invoked by other method to register an own goal:

    public void recordOwnGoal(Team team){
        match.changeScore(team, -1);
    }

    Imagine if every time we have to inform an own goal to any method, if we have to write the “-1”, by example: “registerToPlayerAGoal (player, “-1”)”; Why we don’t create a Constant? In this soccer sample, creating a Constant we will be able to eliminate a method. Let’s see our final code:

    //Our declared Constant in the Match class.
    public static final int OWN_GOAL = -1;
    
    public void changeScore(Team team, int goal){
        this.fullScore(team, goal);
    }

    Notice that we don’t have the need of a method to register only the own goal (recordOwnGoal), this method was created only to pass the value of an own goal as negative. When we invoke the method that will change the game score (changeScore) we just have to put the “OWN_GOAL” as parameter instead creating a method just to do that (  changeScore(team, OWN_GOAL);  ). By example, Constants are welcome in templates building: “ADD_SIMPLE_INDENT”, “ADD_DOUBLE_INDENT”, and others. Just notice: “Do you have to pass the same value? It’s time to use Constants”.

  • There is a reason. Why does this exception exist? – When we create a catcher for an exception we must pay attention to the reason of that exception it’s been thrown. We must keep in mind that if a method throws an exception we must handle it. We must be prepared to give the best treatment to the exception. Some ways of doing a good handling it would be: show to the user (exception that were handled), handle unfinished actions (files, databases transactions, log, etc).
    When we ignore an exception, by do not working with the Exception object, we are disrespecting the method contract that may result in problems to the user and to the application.
  • Exception that it’s declared, but it’s impossible to happen? Once I was working in a software by refactoring a method, to adapt it to a new customer request, and when I was testing my code it did not worked but it did not failed either. Even after review my code I didn’t find any error, it was ok.
    What did I do to find what was happening? Debug!
    When I was checking the code in runtime, I found the following code:

    //...
    validateCreditCard(creditCard);
    //...
    }catch(CreditCardInUseException){
        //Impossible to get here
    }

    When the validate credit card was created it was impossible of it been in use, that’s why there was a comment saying that it was impossible to get there. We can see two possible aspects that we could change:

    1. Non cohesion method – notice that sometimes the method to validate the credit card throws an exception and sometimes it doesn’t; there is inside its method a business rule that make its behavior to change, this behavior changing will define how the method signature will be handled (future talk about OO). A good solution to this issue it would be splitting this method instead keeping all this rules in one method; this method it’s too complicated and has too much decisions in it.
      If an exception it’s declared, this exception must be handled and in our case – when the code was created – it was impossible of that exception to be thrown. If there is a method that declares an exception that will never happen, there is something wrong!
    2. If an exception it’s been thrown, there is a reason for this exception to exist. Notice that if the exception were handled, at least, with “System.out.println ();” it would have a message to notify that error. When I say “at least”, it’s because we can handle an exception by a lot of different ways like send an email, record a log, etc. Something was happening, an exception was thrown, but there wasn’t anything to take care of it. Remember: “If a method declares an exception, there is a reason for it and it should be handled”.
  • Straight error message – when you write an error message avoid thinking like: “I will put the message like this, it’s clear that we are talking about this subject”. Are you sure about this? The user does not think as a developer, he does not need to know that a value X come from screen Y and it is needed to Z screen.
    When you do not know the best message for that situation, try looking at the screen and forgetting everything you know about it and think: “If I were someone that didn’t know anything about development, how I would understand this error message?” Make changes to this question and adapt it to what you are developing, change your way of thinking, and keep your focus on the user. Another good thing to do is ask some coworker to give an opinion.
  • Avoid some exception error messages when developing – When you write an exception message, even in a test environment, avoid some messages like: “Can’t you see that it’s by your fault that this error happened!” or “Hey loser, type something here!” Sometimes it is fun to see those types of messages; or it can give us some relieve to see that our code reached there, but doing this is very dangerous. Imagine if this message stays in the code and goes to the client? Even if those messages bring us some kind of happiness, it’s better to avoid it.
  • Log4J – It’s a good tool that can be useful if you want to log your exception. With this library it is possible to log messages in different event levels and more. I will write a tutorial about it very soon, until there here it goes a link that might help you to study it: http://www.developer.com/open/article.php/10930_3097221_3/Logging-with-log4jmdashAn-Efficient-Way-to-Log-Java-Applications.htm.

I hope these tips might help you.
See you guys later.

Leave a Comment