0

I have this 4 classes, almost the same with only difference the type of building parameter.

Is there some way to refactor/merge class Building and class NewBuilding to one. I tried creating a generic class but sBuilding.getSomething() then is not valid.

public class Building {

static void doSomething(SearchBuilding sBuilding) {
        if (sBuilding.getSomething()) {
            useBuilding(sBuilding);
        }
    }

}

public class NewBuilding {

static void doSomething(SearchNewBuilding sBuilding) {
        if (sBuilding.getSomething() ){
            useBuilding(sBuilding);
        }
    }
}


public class SomeBuilding {

    private final SearchBuilding building;

    protected SearchBuilding getBuilding() {
        return building;
    }

    protected void applyBuilding() {
        Building.doSomething(getBuilding());
    }
}

public class SomeNewBuilding {

    private final SearchNewBuilding building;

    protected SearchNewBuilding getBuilding() {
        return building;
    }

    protected void applyBuilding() {
        NewBuilding.doSomething( getBuilding());
    }

}
Spyros_av
  • 854
  • 2
  • 8
  • 24
  • It's hard to say if this is viable, because you're using a contrived example here, but the typical solution would be to have a base class `BaseBuilding`, then refer to the base class type everywhere, and have any other Building directly inherit from the base class. Do all building types have the same set of methods? – Carcigenicate Jul 26 '19 at 16:03
  • why are those methods static? – Andrew Tobilko Jul 26 '19 at 16:07
  • Really not complicated at all. Implement a common interface... `SomeBuilding implements FooBuilding` and `doSomething(FooBuilding building)` – Michael Jul 26 '19 at 16:12
  • By the way, that example is absolutely awful. You have abstracted away all of the details, which is good, but the result is completely incoherent. – Michael Jul 26 '19 at 16:16
  • @Michael if I do `doSomething(FooBuilding building)` then Im loosing the functionality of `SearchBuilding ` – Spyros_av Jul 29 '19 at 08:17
  • @Carcigenicate yes the same, but with difference `SearchBuilding` and `SearchNewBuilding` data classes . – Spyros_av Jul 29 '19 at 11:52

0 Answers0