As SOLID principles say, it's better to remove switch conditions by converting them to classes and interfaces. I want to do it with this code:
Note: This code is not real code and I just put my idea into it.
MessageModel message = getMessageFromAnAPI();
manageMessage(message);
...
void manageMessage(MessageModel message){
switch(message.typeId) {
case 1: justSave(message); break;
case 2: notifyAll(message); break;
case 3: notify(message); break;
}
}
Now I want to remove switch statement. So I create some classes for it and I try to implement a polymorphism here:
interface Message{
void manageMessage(MessageModel message);
}
class StorableMessage implements Message{
@Override
public void manageMessage(MessageModel message) {
justSave(message);
}
}
class PublicMessage implements Message{
@Override
public void manageMessage(MessageModel message) {
notifyAll(message);
}
}
class PrivateMessage implements Message{
@Override
public void manageMessage(MessageModel message) {
notify(message);
}
}
and then I call my API to get my MessageModel
:
MessageModel message = getMessageFromAnAPI();
Now my problem is here. I have my model and I want manage it using my classes. As SOLID examples, I should do something like this:
PublicMessage message = new Message();
message.manageMessage(message);
But how can I know which type is related to this message to make an instance from it(PublicMessage
or StorableMessage
or PrivateMessage
)?! Should I put switch block here again to do it or what?
justSave/notify/notifyAll
. If you want to savePublicMessage
andPrivateMessage
too, they will need to access the functionality forjustSave
, which is either moved to a separate class,StorableMessage
and became tricky to access, or they still reside in a commonManager
class, which makes the existence ofStorableMessage
a bit questionable. The same fornotifyAll
, which likely does the very same thing asnotify
, in a loop. These classes exist just to exist – Scopula