Skip to main content Link Menu Expand (external link) Document Search Copy Copied

refactoring-journey

Table of contents
  1. Replace Magic Stuff with Constants
  2. Encapsulate fields

Replace Magic Stuff with Constants

Code Smells

  • Code uses numbers that have a certain meaning to it
  • Code uses strings that have a certain meaning to it

Make it harder to understand the program and refactor the code

Technique

  • Extract the magic stuff by using your IDE feature
    • Makes its name self-evident

Practice

  • Open Utils in organizing.data package
  • Extract magic stuff
public class Utils {
    public static void validatePassword(String password) {
        if (password.length() < 12) {
            throw new IllegalArgumentException("minimum password length is not respected");
        }
    }

    public static double calculatePotentialEnergy(double mass, double height) {
        return mass * height * 9.81;
    }
}

Shortcuts

Extract Constant :

IntelliJ
Ctrl+Alt+C
⌘+⌥+C

Benefits

  • Symbolic constant can serve as live documentation of the meaning of its value
  • Reduce duplicate use of a number in the code

Drawbacks

  • N/A

Encapsulate fields

Code Smells

  • From public to private fields
  • Ideally expose just behaviors (methods / functions)

One of the pillars of object-oriented programming is Encapsulation : the ability to conceal object data.

Technique

  • Make the field private and create access methods for it

Practice

  • Open Wizard in organizing.data package
  • Encapsulate fields
public class Wizard {
    public String weapon;
    public String magicStick;
    public String name;
    public int life;

    public Wizard(String name) {
        this.name = name;
    }
}

Shortcuts

  • Right Click in the file
  • Refactor | Encapsulate Fields

extract class

  • Then configure the encapsulation
  • More info here

Benefits

  • Preserve the state of your object
    • No side effect from the outside
  • Much easier for you to maintain and develop this component

Drawbacks

  • N/A

Journey proposed by Yoan Thirion #sharingiscaring