Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, October 11, 2017

Clean Code, part 3

In this multipart series, I take some perfectly working code which is definitely not clean and refactor it into a much cleaner and more readable implementation. If you disagree with my approach at any point then I ask that you voice your concerns in the comment section. In part 1 of this series, I introduced what I see as the problem and the code that I will be refactoring in subsequent posts. In part 2 of the series, I made the code a little more readable by refactoring it a little. The code was still not object-oriented, however, so here is part 3, in which we split the functionality up into a few different classes.

One major issue with the existing code is that the target solution is passed along at every stage. This means that on every turn of the game, the application must pass in the target as well as the guess. It would be much better if we could just pass that value once. We'll do that by creating a HangmanSolution class. This class will keep track of the target value as well as the partial solution.

[pre class="brush:java" title="HangmanSolution.java"]package com.bitsnibblesandbytes.hangman;

class HangmanSolution {
 
    private String target;
 
    private String partialSolution;
 
    HangmanSolution(String target) {
        target = this.target;
        createPartialSolution();
    }
 
    String getTarget() {
        return target;
    }
 
    String getPartialSolution() {
        return partialSolution;
    }
 
    int checkCharacter(char guess) {
        int count = 0;
        for(int i = 0; i < target.length(); i++) {
            if (updatePartialSolution(guess)) {
                count++;
            }
        }
        return count;
    }
 
    boolean isSolutionFound() {
        return target.equalsIgnoreCase(partialSolution);
    }
 
    private boolean updatePartialSolution(char guess) {
        boolean guessMatches = target.toLowerCase().charAt(i) == Character.toLowerCase(guess);
        if (guessMatches) {
            partialSolution = partialSolution.substring(0, i) + Character.toLowerCase(guess) + partialSolution.substring(i + 1);
        }
        return guessMatches;
    }

    private void createPartialSolution() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < target.length(); i++) {
            builder.append('*');
        }
        partialSolution = builder.toString();
    }
}
[/pre]

Most of the above logic is simply copied from the GamePlayer class we created in part 2. The one exception is the isSolutionFound() method. We will see where this method gets used a little later in this post. Note that I did not make this class or any of its methods public. This is because this class is simply meant to be used within this package, so package-private works. There's no point in adding something to my public API that I don't intend the public to use.

Another problem we have is that the GamePlayer class does everything. It should really just direct traffic as other classes do all of the heavy lifting. The HangmanSolution class starts us down the road to removing functionality. Let's move it a little further by pulling the guess validation code out into its own class:

[pre class="brush:java" title="GuessValidator.java"]package com.bitsnibblesandbytes.hangman;

class GuessValidator {
 
    private String previousGuesses = "";
 
    boolean isLetter(char guess) {
        return Character.isAlphabetic(guess);
    }
 
    boolean isAvailableLetter(char guess) {
        if (guesses.indexOf(Character.toLowerCase(guess)) < 0) {
            guesses += Character.toLowerCase(guess);
            return true;
        }
        return false;
    }
}
[/pre]

Next, we'll pull out the logic for building the response string:

[pre class="brush:java" title="ResponseBuilder.java"]package com.bitsnibblesandbytes.hangman;

class ResponseBuilder {
 
    static buildResponse(int count, char guess, HangmanSolution solution, boolean gameLost) {
        String feedbackMessage = buildFeedbackMessage(guess, count);
        String winLoseOrContinueMessage = buildWinLoseOrContinueMessage(solution, gameLost);
        return feedbackMessage + "\n" + winLoseOrContinueMessage
    }

    private static String buildWinLoseOrContinueMessage(HangmanSolution solution, boolean gameLost) {
        String winLoseOrContinue = "";
        if (gameLost) {
            winLoseOrContinue += "The word is " + solution.getTarget() + "\nYou lose.";
        } else if (solution.isSolutionFound()) {
            winLoseOrContinue += "The word is " + solution.getPartialSolution() + "\nYou win!";
        } else {
            winLoseOrContinue += solution.getPartialSolution();
        }
        return winLoseOrContinue;
    }

    private static String buildFeedbackMessage(char guess, int count) {
        String verb;
        String pluralModifier;
        String number;
        if (count == 0) {
            number = "no";
            verb = "are";
            pluralModifier = "s";
        } else if (count == 1) {
            number = "1";
            verb = "is";
            pluralModifier = "";
        } else {
            number = Integer.toString(count);
            verb = "are";
            pluralModifier = "s";
        }
        return String.format("There %s %s %s%s", verb, number, guess, pluralModifier);
    }
}
[/pre]

Note that the methods here are static since the ResponseBuilder does not depend on its own state at all. Some would find this a code smell, and I agree that this isn't the prettiest class, but at least it gets all of that string building out of the GamePlayer class, paring it down to a pretty short class:

[pre class="brush:java" title="GamePlayer.java"]package com.bitsnibblesandbytes.hangman;

public class GamePlayer {
 
    private static final int MAX_ERRORS = 5;

    private int errors = 0;

    private HangmanSolution solution;
 
    private GuessValidator validator;
 
    public GamePlayer(String solution) {
        this.solution = new HangmanSolution(solution);
        validator = new GuessValidator();
    }

    public String handleGuess(char guess) {
        if (!validator.isLetter(guess)) {
            return "Error: you can only guess letters.";
        }
        if (!validator.isAvailableLetter(guess)) {
            return "You already guessed that";
        }
        int count = solution.checkCharacter(guess);
        if (count == 0) {
            errors++;
        }
        return ResponseBuilder.buildResponse(count, guess, solution, errors > MAX_ERRORS);
    }
}
[/pre]

This concludes the refactoring I'm going to do. It's not the most elegant solution, but without starting over from scratch we have at least achieved cleaner code than we started with.

In part 4 of the series, we'll add a simple feature quickly and easily that would not have been so easy to implement with the code we started with in part 1.

Thursday, July 13, 2017

Clean Code, part 2

In this multipart series, I take some perfectly working code which is definitely not clean and refactor it into a much cleaner and more readable implementation. If you disagree with my approach at any point then I ask that you voice your concerns in the comment section. In part 1 of this series, I introduced what I see as the problem and the code that I will be refactoring in subsequent posts. In this post, part 2 of the series, we make the code a little more readable by refactoring it a little. A lot of work will still be left to be done, however.

After listing the code in part 1 (which I will not list again here in the interest of space), I asked several questions. Let's start by looking at the answers to these questions:

  • At a high level, what does this code do?
    • It simulates taking a turn in a hangman-like game.
  • How many errors can be made before losing?
    • 5
  • What are lines 36-52 doing?
    • Composing a response message to be sent back to the game driver.
  • What is the point of the instance variable partialSolution?
    • It keeps track of the letters that have been guessed (and not guessed) so far.

I'm skipping the final question about enhancing the functionality of the game since the basic answer to it is "it would be very difficult". The less basic answer would be quite lengthy and out of the scope of this post. We'll return to it later in the series.

How long did it take you to figure out the answers to these questions? My guess is that it took a while. At the very least, you had to go through most of the code to answer the first two questions (and possibly the last one as well). Well written code should not require you to read through most or all of it in order to figure out what it does at a high level. Breaking the code up into functions will help, so we will begin there.

All of the functionality of this code is contained in a single function. How many different things does this function do? Well, it starts out by building the partial solution if it is currently null. (This should happen only the first time through, but it counts as something the function does.) The second thing it does is validate the input. Third, it checks to see if the guess has already been tried and if not then it adds the guess to the list of attempted guesses. Fourth, it checks whether the guess matches any letters in the solution or not. Fifth, it updates the partial solution. Sixth, it figures out the return message stating how many letters were matched by the guess. Finally, it adds a message to the return value explaining whether the player gets to make another guess and, if not, whether the player won or lost.

That one function does SEVEN things (and this is a conservative count). This seems a rather extreme violation of the Single Responsibility Principle. The least we could do is break it into functions that perform each of these steps. Our new code block may look something like this:

[pre class="brush:java" title="GamePlayer.java"]package com.bitsnibblesandbytes.hangman;

public class GamePlayer {

    private static final int MAX_ERRORS = 5;

    private int errors = 0;

    private String guesses = "";

    private String partialSolution;

    public String takeTurn(char guess, String target) {
        createPartialSolution(target);
        if (isInvalidInput(guess)) {
            return "Error: you can only guess letters.";
        }
        if (isAlreadyGuessed(guess)) {
            return "You already guessed that";
        }
        int count = 0;
        if (isCorrectGuess(target, guess)) {
            count = updatePartialSolution(target, guess);
        } else {
            errors++;
        }
        return buildOutputMessage(target, guess, count);
    }

    private String buildOutputMessage(String target, char guess, int count) {
        String feedbackMessage = buildFeedbackMessage(guess, count);
        String winLoseOrContinueMessage = buildWinLoseOrContinueMessage(target);
        return feedbackMessage + "\n" + winLoseOrContinueMessage
    }

    private String buildWinLoseOrContinueMessage(String target) {
        String winLoseOrContinue = "";
        if (errors > MAX_ERRORS) {
            winLoseOrContinue += "The word is " + target + "\nYou lose.";
        } else if (partialSolution.indexOf('*') < 0) {
            winLoseOrContinue += "The word is " + partialSolution + "\nYou win!";
        } else {
            winLoseOrContinue += partialSolution;
        }
        return winLoseOrContinue;
    }

    private String buildFeedbackMessage(char guess, int count) {
        String verb;
        String pluralModifier;
        String number;
        if (count == 0) {
            number = "no";
            verb = "are";
            pluralModifier = "s";
        } else if (count == 1) {
            number = "1";
            verb = "is";
            pluralModifier = "";
        } else {
            number = Integer.toString(count);
            verb = "are";
            pluralModifier = "s";
        }
        return String.format("There %s %s %s%s", verb, number, guess, pluralModifier);
    }

    private int updatePartialSolution(String target, char guess) {
        int count = 0;
        for(int i = 0; i < target.length(); i++) {
            if (target.toLowerCase().charAt(i) == Character.toLowerCase(guess)) {
                count++;
                partialSolution = partialSolution.substring(0, i) + Character.toLowerCase(guess) + partialSolution.substring(i + 1);
            }
        }
        return count;
    }

    private boolean isCorrectGuess(String target, char guess) {
        return target.toLowerCase().indexOf(Character.toLowerCase(guess)) > -1;
    }

    private boolean isAlreadyGuessed(char guess) {
        if (guesses.indexOf(Character.toLowerCase(guess)) >= 0) {
            return true;
        }
        guesses += Character.toLowerCase(guess);
        return false;
    }

    private boolean isInvalidInput(char guess) {
        return !Character.isAlphabetic(guess);
    }

    private void createPartialSolution(String target) {
        if (partialSolution == null) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < target.length(); i++) {
                builder.append('*');
            }
            partialSolution = builder.toString();
        }
    }
}
[/pre]
(Side note: The above code adds a package statement and removes the unused import that was in the previous code in addition to the discussed changes.)

The above code is still far from perfect. For one thing, it is still not particularly object-oriented (since the logic has not been altered at all, just pulled out into private methods), but at least the original method is more readable. The names of the new methods explain what they're doing, which helps with the high-level interpretation of the code. The mystery of the maximum number of errors is also dispelled through the use of the MAX_ERRORS constant, eliminating the use of a magic number in buildWinLoseOrContinueMessage(). The mystery of lines 36-52 in the original code is solved by the name of the buildFeedbackMessage() method. The purpose of partialSolution is still not particularly clear, though the updatePartialSolution() method implementation and the placement of the call to it in the code provide strong clues.

We have begun the process of making this code more readable and more maintainable, but we still have a ways to go. In part 3 of this series, we will explore a more object-oriented approach to the problem and again refactor this code to follow object-oriented principles more closely.

Friday, June 9, 2017

Clean Code, part 1

In this multipart series, I will take some perfectly working code which is definitely not clean and refactor it into a much cleaner and more readable implementation. If you disagree with my approach at any point then I ask that you voice your concerns in the comment section. In this post, part 1 of the series, I introduce what I see as the problem and the code that I will be refactoring in subsequent posts.

Many amateur and professional software developers take on the attitude "if it ain't broke, don't fix it". In other words, they will write their code until it works and then they are done with it. After all, isn't the point to have working software? Tight company deadlines encourage this approach as well, as the perception is that there isn't time to refactor and clean the code. It is my position that even with tight deadlines, you don't have time not to clean your code. In the long run, just getting the code working and then moving on is going to come back to bite you.

Think about it. You work long and hard to get a new feature working. Once it's working, you deliver it and move on to the next feature. A few weeks later, the initial feature needs to be enhanced. Will you be the one to work on it? Maybe. If not, then pity the poor soul who has to untangle what took you days to tangle up in the first place. If so, then just hope that you can remember what it was that you were doing, because it's unlikely to be clear from the code.

Let's take a look at a simple example.
[pre class="brush:java" title="GamePlayer.java"]import java.util.Scanner;

public class GamePlayer {

    private int errors = 0;

    private String guesses = "";

    private String partialSolution;

    public String takeTurn(char guess, String target) {
        if (partialSolution == null) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < target.length(); i++) {
                builder.append('*');
            }
            partialSolution = builder.toString();
        }
        if (!Character.isAlphabetic(guess)) {
            return "Error: you can only guess letters.";
        }
        if (guesses.indexOf(Character.toLowerCase(guess)) >= 0) {
            return "You already guessed that";
        }
        guesses += Character.toLowerCase(guess);
        if (target.toLowerCase().indexOf(Character.toLowerCase(guess)) == -1) {
            errors++;
        }
        int count = 0;
        for(int i = 0; i < target.length(); i++) {
            if (target.toLowerCase().charAt(i) == Character.toLowerCase(guess)) {
                count++;
                partialSolution = partialSolution.substring(0, i) + Character.toLowerCase(guess) + partialSolution.substring(i + 1);
            }
        }
        String verb;
        String pluralModifier;
        String number;
        if (count == 0) {
            number = "no";
            verb = "are";
            pluralModifier = "s";
        } else if (count == 1) {
            number = "1";
            verb = "is";
            pluralModifier = "";
        } else {
            number = Integer.toString(count);
            verb = "are";
            pluralModifier = "s";
        }
        String output = String.format("There %s %s %s%s", verb, number, guess, pluralModifier);
        if (errors > 5) {
            output += "\nThe word is " + target + "\nYou lose.";
        } else if (partialSolution.indexOf('*') < 0) {
            output += "\nThe word is " + partialSolution + "\nYou win!";
        } else {
            output += "\n" + partialSolution;
        }
        return output;
    }
}[/pre]
If, at this point, you find yourself saying, "He said a simple example. This doesn't look simple," then I have made my point. This really is a simple example. It is functionally and syntactically correct. Please answer the following questions for yourself and pay attention to how long it takes to be able to do so.
  • At a high level, what does this code do?
  • How many errors can be made before losing?
  • What are lines 36-52 doing?
  • What is the point of the instance variable partialSolution?
  • Suppose that the rules of the game are to be changed so that if the solution contains multiple copies of the same letter then they are filled in one at a time when that letter is guessed. For example, if the word was 'feelers' then the first guess of the letter 'e' would reveal the first 'e', but not the others (*e*****), the second guess of the letter 'e' would reveal the second 'e' (*ee****), and so on. 
    • Where would you start? 
    • How many points in the code would need to be touched? 
    • What if the new rule was to be optional, chosen by the player before starting the game?
The point I am making here is that the above questions are not easy to answer quickly. The code works, but it is not obvious what it does or what all its parts are for. This is for a fairly simple game written by one person in an hour or so. The problem gets exponentially worse for complex business domains written and maintained by multiple people on multiple teams over the course of years. This, my friends, is where spaghetti code comes from.

The code above is not only dirty, but it is also not object oriented. (Just because it's Java doesn't mean it's object oriented.) It is structured in that it doesn't have goto statements of any type (goto, continue, break), but it is very procedural. In part 2 of this series, I will start with this code and discuss how to make it cleaner and more object oriented.

Tuesday, March 28, 2017

Spring Configuration -- Do You Use a Component Scan?

If you use Spring beans for dependency injection in any of your applications then you know that you frequently have to define quite a lot of them. Whether you use xml configuration, Java annotation-based configuration, or a mix of the two, you still wind up creating a bean for each component of your application. With even a moderately complex system, this number of beans adds up very quickly. Thus, we have the component scan.

For those of you who aren't familiar with it, a component scan makes it very easy to create a new component. All you need to do is place an @Component tag on the class itself and then indicate in one of your configuration files that Spring should scan for components in the directory that your class is in.

A brief example:
First, define the component using the @Component tag.
[pre class="brush:java" title="MyComponent.java"]package my.component.pkg;

import  org.springframework.stereotype.Component;

@Component
public class MyComponent {
...
}[/pre]

Next, tell Spring  to scan for components. I'll give both the Java and xml configurations, but really only one is necessary.

[pre class="brush:java" title="MyConfiguration.java"]package my.configuration.pkg;

import my.component.pkg.MyComponent;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("my.component.pkg")
public class MyConfiguration {
}[/pre]

[pre class="brush:xml" title="component-configuration.xml"]<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.7.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.7.xsd">

    <context:component-scan base-package="my.component.pkg" />
</beans>[/pre]

Pretty nifty, huh? Well, maybe. Until you try to run a bunch of integration tests. You see, I might have hundreds (or even thousands) of components defined this way (within the same package or in multiple base packages). Now suppose I want to run an integration test on MyComponent. When Spring starts up, it loads not just MyComponent, but every component in your application. This is not only unnecessary, but for a very large application, it can take up to a minute, possibly more,  before your test can even begin running.

The above issue has led my team recently to abandoning using the component scan. We have begun defining beans using the @Bean tag in a Java configuration file in the same package as the component. The above example would then look like this:

[pre class="brush:java" title="MyComponent.java"]package my.component.pkg;

class MyComponent {
...
}[/pre]

[pre class="brush:java" title="ComponentConfig.java"]package my.component.pkg;

import org.springframework.context.annotation.*;
@Configuration
public class ComponentConfig {

    @Bean
    MyComponent myComponent() {
        return new MyComponent();
    }
..
}[/pre]

We would define all components in the my.component.pkg package in this configuration file. Then, when running a test on MyComponent, I only need to load this configuration and can skip loading the components that are not needed for the test.

This finally brings me to my question: do you/would you use component scan to simplify the creation of component beans or do you/would you avoid it in order to be able to more easily control how much of the application context must be loaded when running a test? Please leave a response in the comments.

Friday, March 10, 2017

The final keyword in Java

Most experienced Java developers are familiar with the final keyword. It can be used at three different levels: class, method, and variable (or field).

Probably the most common use of final is in the definition of constants, such as

public static final Integer MY_CONSTANT = 475;


Another common use is for local variables (or method parameters) whose value never changes:

String getNameAndAge() {
    final String name = determineName();
    final Integer age = determineAge();
    return name + " " + age;
}

That the values of name and age in the above example cannot be changed leads some to believe that the final keyword makes an object immutable. In a code review I was doing recently, I came across a snippet of code similar to the following:

// make the context immutable
final Context context = contextFactory.build(contextParameters);

The author had been told in a previous comment to make Context immutable, and this was their attempt to do so. To understand why this fails to make context immutable, it helps to recall how Java stores data.

Briefly, for primitive values, the value is stored directly in the stack. For the sake of visualization, we can say that the variable stores the value itself. For objects, however, the variable stores not the object, but a reference to the object. In other words, adding the final keyword only limits you from reassigning the reference that is stored by the variable.

This means that the final keyword in the above case means that you cannot assign a different Context instance to context, but you can use the setter methods in the Context class to modify the instance that you do have, so you do not have an immutable instance of Context. The way to make Context immutable is not in the use of final, but instead in removing the setter methods from the Context class itself. You cannot make an immutable instance of a class that is itself mutable.

As mentioned above, final can be used at the class level and at the method level as well. When used at the class level, it means that the class cannot be extended (see java.lang.String). When used at the method level, it means that the method cannot be overridden.

There are style issues around final as well, such as whether or not to label method parameters as final or whether final should be used on local variables at all. Style is a bit outside the scope of this article, but I urge you (and your team) to have a consistently used policy.