Search code examples
javaoopinheritanceinstanceof

Is this a valid case to use instanceof operator?


I am a beginner in Java and OOP in general, and I have a question regarding inheritance in Java.

In my project, I have a class Order that represents a order placed for an asset. I intend to have several classes that extend Order including LimitBuyOrder and LimitSellOrder & the likewise for market orders.

I will also have a class Position, which consists of a pair of orders. In order to determine the kind of Position, I must know which type of Order was entered first. Although the instanceof operator would work in this situation, I feel it is not an appropriate solution. Below is a stripped-down snippet, which may help to illustrate my problem:

class Position {
    //Other fields and methods omitted for clarity
    public void open(Order o) {
        if(o instanceof LimitBuyOrder)
            //Set position type to LONG
        if(o instanceof LimitSellOrder)
            //Set position type to SHORT
    }
}

Or should I do something like define methods in Order such as isLimitBuy() & etc, which return false and override them to return true based on which subclass Order is extended by?

class Position {
    //Other fields and methods omitted for clarity
    public void open(Order o) {
        if(o.isLimitBuyOrder())
            //Set position type to LONG
        if(o.isLimitSellOrder())
            //Set position type to SHORT
    }
}

Basically, my question is how do I determine the type of a subclass properly? Thanks in advance!


Solution

  • You should aim to encapsulate the behaviour within the types of orders rather than simply using their types externally to switch behaviour.

    Add a method to your 'Order' class that does the work and then you do not have to know what type it is at all:

    order.openPosition(...);
    

    Let the 'Order' do whatever it needs to do according to its type.

    A significant benefit to encapsulation is that you end up having all the order-type-specific behaviour in one place. Abstract parent classes come naturally to provide any common order characteristics. With the code in one place (or at least in a small hierarchy of classes) you can change the behaviour without having to visit code all over your application.