'is instanceof' Interface bad design

Posted by peterRit on Stack Overflow See other posts from Stack Overflow or by peterRit
Published on 2012-10-17T22:43:29Z Indexed on 2012/10/17 23:00 UTC
Read the original article Hit count: 200

Filed under:
|
|

Say I have a class A

class A
{
   Z source;
}

Now, the context tells me that 'Z' can be an instance of different classes (say, B and C) which doesn't share any common class in their inheritance tree.

I guess the naive approach is to make 'Z' an Interface class, and make classes B and C implement it.

But something still doesn't convince me because every time an instance of class A is used, I need to know the type of 'source'. So all finishes in multiple 'ifs' making 'is instanceof' which doesn't sound quite nice. Maybe in the future some other class implements Z, and having hardcoded 'ifs' of this type definitely could break something.

The escence of the problem is that I cannot resolve the issue by adding functions to Z, because the work done in each instance type of Z is different.

I hope someone can give me and advice, maybe about some useful design pattern.

Thanks

© Stack Overflow or respective owner

Related posts about oop

Related posts about design-patterns