Reputation: 36746
I have a class called Document
that can be extended by Page
or Image
. For each one I have an insert method in database. The insert for Page
and Image
includes the insert for Document
.
My doubt is if the way to determine what method will be called is verifying the class first, like this:
if (doc instanceof Document){
insertDoc(doc);
}
if (doc instanceof Page){
insertPage(doc);
}
if (doc instanceof Image){
insertImage(doc);
}
Or there is another way, because I always heard that using instanceof
is not a good thing.
Edit: Polymorphism doesn't works in this case, right? Something like insert(Document doc)
, insert(Page doc)
and insert(Image doc)
.
Upvotes: 0
Views: 191
Reputation: 8278
In case that in future you plan to add more types that extend Document and add more operations than just insert(), I would suggest implementing a Visitor design pattern . Otherwise, follow Bynyamin Sharet's suggestion.
Upvotes: 4
Reputation: 137442
I think it would be better to implement the insert method in the Document
class and override it with an appropriate methods in the classes that extend it. Then, just call doc.insert();
.
Upvotes: 8