TankGameOrg / engine

1 stars 2 forks source link

Create TankBuilder class for unit testing #41

Closed BryanFriestad closed 4 months ago

BryanFriestad commented 5 months ago
          The only way to implement something like default arguments in Java is to overload a member function of a class, i.e., 
class Foo {
    void bar(int i) { ... }
    void bar()
    { 
        bar(0);
    }
}

This is why I suggested the idea of a builder class.

_Originally posted by @TrevorBrunette in https://github.com/TankGameOrg/engine/pull/39#discussion_r1590440200_

TrevorBrunette commented 5 months ago

Suggested implementation:

    public static class TankBuilder<T extends GenericTank<E>, E extends Enum<E> & IAttribute> {
        private final T tank;
        public TankBuilder(T tank) {
            this.tank = tank;
        }

        public TankBuilder<T, E> with(E attribute, Object value) {
            tank.set(attribute, value);
            return this;
        }

        public T build() {
            return tank;
        }
    }

    public static TankBuilder<Tank, TankAttribute> getTankBuilder() {
        JSONObject json = new JSONObject();
        json.put("name", "test");
        json.put("position", "A1");
        json.put("type", "tank");
        return new TankBuilder<>(new Tank(json));
    }