Skip to content

StaticFactoryMethods test

Mikhail Pravilov edited this page Jul 3, 2018 · 1 revision

Checks that the algorithms don't try to move static factory methods.

Expected refactorings
Member Move to
- -
package staticFactoryMethods;

import java.util.ArrayList;

class Cat {
    private final Color color;
    private int weight;

    public Cat(Color color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public ArrayList<Cat> bearChildren() {
        ArrayList<Cat> children = new ArrayList<>();
        children.add(new Cat(Color.makeFromHex(0), 10));
        children.add(new Cat(Color.makeFromRGB("101010"), 20));
        children.add(new Cat(Color.makeFromPalette(20, 20, 20), 30));
        children.forEach(this::feedChild);
        return children;
    }

    public void feedChild(Cat cat) {
        cat.weight++;
    }
}
package staticFactoryMethods;

class Color {
    private final int hex;

    static Color makeFromRGB(String rgb) {
        return new Color(Integer.parseInt(rgb, 16));
    }

    static Color makeFromPalette(int red, int green, int blue) {
        return new Color(red << 16 + green << 8 + blue);
    }

    static Color makeFromHex(int h) {
        return new Color(h);
    }

    private Color(int h) {
        hex = h;
    }
}
package staticFactoryMethods;

import java.util.ArrayList;

class Dog {
    private final Color color;
    private int weight;

    public Dog(Color color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public ArrayList<Dog> bearChildren() {
        ArrayList<Dog> children = new ArrayList<>();
        children.add(new Dog(Color.makeFromHex(0), 10));
        children.add(new Dog(Color.makeFromRGB("101010"), 20));
        children.add(new Dog(Color.makeFromPalette(20, 20, 20), 30));
        children.forEach(this::feedChild);
        return children;
    }

    public void feedChild(Dog dog) {
        dog.weight++;
    }
}
Clone this wiki locally