Search code examples
javapolymorphismsubtyping

How should I implement subtypes of a Message class in Java?


I'm sure this is a basic OOP question -- I'm designing a message-passing system where there are several entirely distinct message formats, but I want them all to be able to be placed on a PriorityBlockingQueue. My first thought was to define an abstract class Message and then define subclasses extending Message for each of the message types. But this means that, at the receiving end, the message processor needs to identify the subclass in order to know how to process the contents of the message. And the only way I know of doing this is with .instanceof() or Class. and it somehow doesn't seem right.

As Scott Meyers writes,

Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.

(He goes on to make the point that, in polymorphism, you should have the same method names having different implementations for each subclass. I don't see how I can make that idea work in my case - the message types themselves are utterly unrelated.)

For the sake of discussion, here are my message types:

  • ConsoleMessage, identifying a ConsoleObject and an ObjectState.
  • CardReaderRequestMessage, not containing anything but simply requesting "next card"
  • CardReaderMessage, containing a byte[80] card image and a Last Card indicator
  • CardPunchMessage, containing a byte[80] card image
  • CardPunchResponseMessage, not containing anything but signifying that the card image was copied to the punch buffer

I believe I have to know what kind of message I'm dealing with, so I suspect I should not be using polymorphic Messages. How should I design this properly?

===== EDIT to raise a follow-up question =====

I was trying to find a way to use a polymorphic Message without having, at some point, to identify its subclass. The suggested approach was to override a process() method in each subclass. Here's my (simplified) abstract Message and two subclasses:

public abstract class Message {

    public abstract void process() {
        // subclasses of Message implement this
    }

    public static class ConsoleMessage extends Message {
        private int obj;
        private int state;
        public ConsoleMessage(int x, int y) {
            obj = x;
            state = y;
        }
        @Override
        public void process() {
            // do something with obj and state?
        }

    public static class CardReaderMessage extends Message {
        private byte[] card;
        private boolean lastCardIndicator;
        public CardReaderMessage(byte[] c, boolean lc) {
            card = c;
            lastCardIndicator = lc;
        }
        @Override
        public void process() {
            // do something with card and lastCardIndicator
        }
}

There is one queue per thread for all "inbound" Messages. Suppose my thread needs to wait for a message from the console to "resume", but meanwhile should receive and process other message types:

waitForResumeMessage() {
    while (true) { // the following will block until a msg arrives
        Message msg = inboundMessageQueue.receiveMessage();
        msg.process();    

But now what? Some implementation of process() has moved some data somewhere, but ultimately I need to be able to write:

        if // msg was ConsoleMessage "resume" command
            return;  // .. from waitForResumeMessage()
    } // else iterate until another message
}

Which basically means finding out what class 'msg' belongs to.

Am I approaching this all wrong? I realize that "waiting" is not really appropriate in an "event-driven" model, but this is a long-running background worker. Perhaps the idea of using process() is more useful for changing the state of an FSM that's guiding an event-driven thread?


Solution

  • Your idea is good, you should indeed start with either an abstract class or an interface called Message, and this interface should be something like this:

         public interface Message {
         void process();
         //some other methods
    }
    
    public class MessageType1  implements Message {
        @Override
        public void process() {
          //My special way to process this message
    }
    }
    

    This way the receiving end only has to receive something that IS A Message i.e. implements your Message interface, and it doesn't really care what type of particular message all it cares is that it responds to process, so you can just implement how each particular message should be processed there.