Check the class of objects

janderson askme at me.com
Fri Jun 6 08:46:34 PDT 2008


janderson wrote:
> 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


Oh the other piece of the puzzle in your case since your doing the same 
thing for each case is a template.

void DoStuffTemplate(T)(T obj)
{
    //Do nasty stuff to obj (no cast required since is the given type)
}


class ByteImage : Image
{
   override void DoSomething1()
   {
     DoStuffTemplate(this); //Note, can't be in base class
   }

}

class ByteImage : Image
{
   override void DoSomething1()
   {
     DoStuffTemplate(this); //Note, can't be in base class
   }
}

Also if you need to special case something you have 2 options, template 
spealization or changing the contents of DoSomething1().

-Joel


More information about the Digitalmars-d-learn mailing list