Heart containing Coding Chica Java 101

Hands Off My Property! Getters and Setters

Table of Contents

TIP: References Quick List
  1. Table of Contents
  2. Introduction
  3. Add Failing Tests
  4. Making the Tests Succeed
  5. Run The Build – Checkstyle Failure
  6. Fix the Style Issues
  7. Run The Build – Success
  8. Commit

Introduction

Generally speaking, it is a good practice to make your Plain Old Java Object (POJO) instance fields (AKA properties) private (inaccessible outside of the class) and use methods to set / get them. Even if you don’t plan to have any validation now, using the getter/setter approach would reduce the work of any calling code if you need to add validation logic or additional updates to the class when modifying that field in the future, etc.

Field TypeGetter Name FormatGetter Example SignatureSetter Name FormatSetter Example Signature
booleanis<FieldName>public boolean isDefault()set<FieldName>public void setDefault(final boolean newDefaultValue)
otherget<FieldName>public String getName()set<FieldName>public void setName(final String newNameValue)

This convention also helps your calling code know how to retrieve / modify the state of the object. If everyone uses the same approach, we all know what to expect in the various code bases.

We already have a private field in our App class, called name. Let’s add a getter/setter pair to allow it to be changed and retrieved after the object is created.

Add Failing Tests

First, let’s add a new set of tests that relay the expectations of the new methods, whether the name is populated by the constructor or the setter, we expect it to be stored and returned by the getter method.

In src/test/java/codingchica.java101.AppTest, let’s add a new, nested class with the new tests:

/**
 * Unit tests for the name field's getters and setter logic.
 * @see App#App(String) 
 * @see App#getName() 
 * @see App#setName(String) 
 */
@Nested
class NameTest {

    @ParameterizedTest
    @ValueSource(strings = {"Sally", "Suzie", "Billy"})
    void getName_whenPopulatedFromConstructor_thenReturnsExpectedValue(String name) {
        // Setup
        App app = new App(name);

        // Execution
        String actualGreeting = app.getName();

        // Validation
        assertEquals(name, actualGreeting);
    }

    @ParameterizedTest
    @ValueSource(strings = {"Rachel", "Jeannine", "Andrew"})
    void getName_whenPopulatedFromSetter_thenReturnsExpectedValue(String name) {
        // Setup
        App app = new App("Pattie");
        app.setName(name);

        // Execution
        String actualGreeting = app.getName();

        // Validation
        assertEquals(name, actualGreeting);
    }
}

Even though the logic we are adding is going to be pretty simple, having a parameterized test with a couple of different values each helps ensure that we cannot simply pass a test with hard-coding.

Making the Tests Succeed

Let’s add the new methods to the src/main/java/codingchica.java101.App class:

/**
 * Getter for the name field.
 * @return The current value of the name field.
 */
public String getName() {
    return name;
}

/**
 * Setter for the name field.
 * @param name The new value for the name field.
 */
public void setName(String name) {
    this.name = name;
}

Run The Build – Checkstyle Failure

Running mvn clean install at this point shows the following errors:

[INFO] — checkstyle:3.3.0:check (validate) @ java101 —
[INFO] Starting audit…
[ERROR] …\java101\src\main\java\codingchica\java101\App.java:76:21: Parameter name should be final. [FinalParameters]
[ERROR] …\java101\src\main\java\codingchica\java101\App.java:76:28: ‘name’ hides a field. [HiddenField]
Audit done.
[INFO] ————————————————————————
[INFO] BUILD FAILURE
[INFO] ————————————————————————

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:3.3.0:check (validate) on project java101: Failed during checkstyle execution: There are 2 errors reported by Checkstyle 9.3 with sun_checks.xml ruleset. -> [Help 1]

Fix the Style Issues

Let’s update the new setter method to address these issues. Remember, we saw both of these before, when we first added the Maven Checkstyle Plugin.

/**
 * Setter for the name field.
 * @param newName The new value for the name field.
 */
public void setName(final String newName) {
    this.name = newName;
}

Run The Build – Success

This time, when we run the build, we should not see any failures, whether from the checkstyle plugin or the unit tests:

...
[INFO] --- checkstyle:3.3.0:check (validate) @ java101 ---
[INFO] Starting audit...
Audit done.
[INFO] You have 0 Checkstyle violations.
...
[INFO] --- surefire:3.1.2:test (default-test) @ java101 ---
...
[INFO] Tests run: 44, Failures: 0, Errors: 0, Skipped: 0
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
...

Commit

Remember, commit in small batches. Now is a good time to do so.

Hands Off My Property! Getters and Setters

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.