Check the class of objects

janderson askme at me.com
Fri Jun 6 08:35:19 PDT 2008


Mael wrote:
>> What's wrong with:
>>
>> if(isByteImage(u))
>> { do something; }
>> ...
>>
>> Either way, you still need the if-else block to determine what the image is 
>> at runtime.
> 
> Well, actually the point is that the action "do something" is consistent accross images except when trying to access data (compare bytes/floats/value/triples), and using a run time if inside the loops would be unefficient, that's why I want to only use static if in the loop, but still share most of the code since it's truly redundant 
> 
>  


I still think you should do this instead:

interface Image
{
   void DoSomething1();
}

class ByteImage : Image
{
   override void DoSomething1()
   {
     //do something;
   }

}


class ByteImage : Image
{
   override void DoSomething1()
   {
     //do something else;
   }

}


... Use case

Image image = new ByteImage();

...

image.DoSomething();


Using a switch statement like you have is very poor design in my book. 
The great thing about doing it this way is you have no coupling to a 
switch statement.  Someone wants to create a new type of Image they can 
  just by inheriting from your interface.  They don't need to update a 
whole heap of switch statements (which they may not even have access to 
if you used a lib.)  Its becomes more like a plug-in architecture.

Sorry to come across as harsh here but if your going to show this to 
students you should show them the right way to do such stuff.

This is called the adapter pattern BTW.

Wiiiiiiiiiiiiiiiiiii,
-Joel


More information about the Digitalmars-d-learn mailing list