How should I refactor switch statements like this (Switching on type) to be more OO?

I’m seeing some code like this in our code base, and want to refactor it:

(Typescript psuedocode follows):

class EntityManager{

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    var existingEntity:IEntity = null;

    switch(entityType) {
      case Types.UserSetting:
            existingEntity = this.getUserSettingByUserIdAndSettingName(serverObject.user_id, serverObject.setting_name);
                break;

        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(serverObject.user_id, serverObject.id);
            break;

        //Lots more case statements here...
    }
    return existingEntity;
 }

 }

The downsides of switching on type are self-explanatory. Normally, when switching behavior based on type, I try to push the behavior into subclasses so that I can reduce this to a single method call, and let polymorphism take care of the rest.

However, the following two things are giving me pause:

1) I don’t want to couple the serverObject with the class that is storing all of these objects. It doesn’t know where to look for entities of a certain type. And unfortunately, the identity of a type of ServerObject varies with the type of ServerObject. (So sometimes it’s just an ID, other times it’s a combination of an id and a uniquely identifying string, etc). And this behavior doesn’t belong down there on those subclasses. It is the responsibility of the EntityManager and its delegates.

2) In this case, I can’t modify the ServerObject classes since they’re plain old data objects. It should be mentioned that I’ve got other instances of the above method that take a parameter like “IEntity” and proceed to do almost the same thing (but slightly modify the name of the methods they’re calling to get the identity of the entity). So, we might have:

        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(entity.getUserId(), entity.getId());
            break;

So in that case, I can change the entity interface and subclasses, but this isn’t behavior that belongs in that class.

So, I think that points me to some sort of map. So eventually I will call:

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    return aMapOfSomeSort[entityType].findByServerObject(serverObject);

}

private findEntityForEntity(someEntity:IEntity):IEntity {
    return aMapOfSomeSort[someEntity.entityType].findByEntity(someEntity);
}

Which means I need to register some sort of strategy classes/functions at runtime with this map. And again, I darn well better remember to register one for each my my types, or I’ll get a runtime exception.

Is there a better way to refactor this? I feel like I’m missing something really obvious here.

7

Whenever you start switching by type (or providing if’s based on type), then you’re going against the OO model. In a good OO design, the implementation class should be hidden from the calling code.

(That said, there are times when it’s easier to do a quick instanceof, but I try to make it rare).

Polymorphism is the answer here.

Really, what you’re doing is calling some common action on some classes. So spin off an interface that defines that common call, and then reference the objects through that interface.

In other words, whenever I see myself writing “if xxx.class” or “xxx instanceof” or “switch (xxx.class)”, I ask myself is there’s a common interface I can pull out.

Now, it can be tricky. If the different classes require different parameters, you might need to use some sort of Builder pattern. It can get complicated.

But the short answer, anyway, is: if you’re switching or iffing based on class type, you should really be using polymorphism instead.

13

I would map between entityTypes and an object that knows what to do with that entity type. So you might have something like

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {
    EntityFinder entityFinder = EntityFinder.getForEntity(entityType);
    return entityFinder.find(serverObject);
}

You will then be pushing the switch into EntityFinder which will have a static method along the following lines

class EntityFinder {
    public static EntityFinder getForEntity(String entityType) {
        switch (entityType) {
            case Types.UserSetting:
               return new UserSettingsFinder();
            case Types.Bar:
               return new BarSettingsFinder();
            default:
               // Possibly better than a null pointer
               return new UnknownSettingsFinder(); 
        }
    }
}

If you introduce a new type, you will have to remember to include it in the switch but hopefully, you will only have one place to do this.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật