This needs a different approach
Steven Schveighoffer
schveiguy at yahoo.com
Mon Apr 28 11:54:03 PDT 2008
"Saaa" wrote
>
>>>
>>> I have this piece of code:
>>>
>>> enum { APPLE, PEAR .. PLUM}
>>>
>>> switch (data.type)
>>> {
>>> case APPLE:
>>> groupModule.appleModule.eat();
>>> break;
>>> case PEAR:
>>> groupModule.pearModule.eat();
>>> break;
>>> ..
>>> ..
>>> case PLUM:
>>> groupModule.plumModule.eat();
>>> break;
>>> default:
>>> break;
>>> }
>>>
>>> As the function is always the same I'd rather see a lookup iso an
>>> iteration over all options.. but how?
>>>
>>> groupModule.(data.type).eat();
>>>
>>> Something like this is both faster and a lot less to code :)
>>>
>>
>> Not sure if this works, but what you probably want is a function table:
>>
>> auto functionArray = [APPLE:&groupModule.appleModule.eat,
>> PEAR:&groupModule.pearModule.eat, .., PLUM:&groupModule.plumModule.eat];
>>
>> functionArray[data.type]();
>
> Ok, that works; I think :) although the array would become very large.
Not any larger than the code that is generated from your switch statement :)
In fact, compilers sometimes optimize code like yours into a function array.
>
>>
>> Another option is to store your modules in the groupModule in an array
>> and just get a common interface returned via a function get:
>
> Erm, how does one do this?
I was assuming your groupModule was a class, but now I think it might be a
module (duh!).
You should seriously consider putting these things into classes instead of
modules, and looking up the right interface based on the data type from a
function. For example:
interface Edible
{
void eat();
}
class Pear : Edible
{
void eat() {...}
}
static Edible[] fruits;
static this()
{
fruits = [APPLE:new Apple(), PEAR:new Pear()...].dup;
}
Edible get(uint type)
{
if(type > fruits.length)
return null;
return fruits[type];
}
Robert is right, this is precisely the thing that OO programming was created
for :)
-Steve
More information about the Digitalmars-d-learn
mailing list