java - Is this a valid case to use instanceof operator? -
i beginner in java , oop in general, , have question regarding inheritance in java.
in project, have class order
represents order placed asset. intend have several classes extend order
including limitbuyorder
, limitsellorder
& likewise market orders.
i have class position
, consists of pair of orders. in order determine kind of position
, must know type of order
entered first. although instanceof
operator work in situation, feel not appropriate solution. below stripped-down snippet, may illustrate problem:
class position { //other fields , methods omitted clarity public void open(order o) { if(o instanceof limitbuyorder) //set position type long if(o instanceof limitsellorder) //set position type short } }
or should define methods in order
such islimitbuy()
& etc, return false
, override them return true
based on subclass order
extended by?
class position { //other fields , methods omitted clarity public void open(order o) { if(o.islimitbuyorder()) //set position type long if(o.islimitsellorder()) //set position type short } }
basically, question how determine type of subclass properly? in advance!
you should aim encapsulate behaviour within types of orders rather using types externally switch behaviour.
add method 'order' class work , not have know type @ all:
order.openposition(...);
let 'order' whatever needs according type.
a significant benefit encapsulation end having order-type-specific behaviour in 1 place. abstract parent classes come naturally provide common order characteristics. code in 1 place (or @ least in small hierarchy of classes) can change behaviour without having visit code on application.
Comments
Post a Comment