Search code examples
javaabstraction

When should I declare abstract methods?


I'm currently working on an application that communicates with other applications in the system over different networks. At present, it communicates through DIS as well as RabbitMQ. Internally, however, the application doesn't care who sent the message or in what format.

With this in mind, I've made an abstract class which contains information called InternalMessage, and an Abstract class for sending and receiving these messages, OrchestrationMessenger. The application polls Messengers for incoming messages and sends responses back. However, the process of sending out messages to the network happens internally to the class and is dependent on the Concrete class that extends InternalMessage.

Should the functions that I know each Concrete class will need, but that will only be used internally, be declared in the Abstract class? I understand how to declare the methods, I just don't know if I should.

For example: functions that converts incoming messages to my internal format and visa-versa, read incoming messages from the networks, and send the outgoing messages.

The abstract Messenger:

//Package omitted
import java.util.Queue;

//Comments omitted
public abstract class OrchestrationMessenger <M extends InternalMessage> implements Runnable
{
    protected Queue<M> incoming, outgoing;

    //Send out a Message, such as responses or commands
    public void publish(M message)
    {
        outgoing.add(message);
    }

    //Receive next incoming Message Object
    public M process()
    {
        return incoming.poll();
    }

    //Check if there are any Messages to process
    public boolean hasNext()
    {
        return !incoming.isEmpty();
    }
}

Thanks!


Solution

  • Should the functions that I know each Concrete class will need, but that will only be used internally, be declared in the Abstract class ?

    To answer this you must think whether only the concrete child classes will need this method.

    For instance, you have class Person and every child class of Person need one common method which is say calculateWeight which returns the weight of the Person. You must say that every Person will have same method to do this. However, what about other Object say Animal which also need the same method to calculate weight of Animals. Note that the requirement of the method is not limited to the sub classes only. Then it should not be in abstact class. It should be utility method, otherwise having the common implementation in abstract parent is fine.