help me refactor iteration over a generic collection

Posted by Biswanath on Stack Overflow See other posts from Stack Overflow or by Biswanath
Published on 2008-12-19T11:18:21Z Indexed on 2011/02/15 23:25 UTC
Read the original article Hit count: 202

Filed under:
|
|

Hi,

I am working with a generic data structure, say MyGeneric<Type>. There is a case where I have to iterate over all the values it holds

The code I am trying to do.

for ( all the keys in myGeneric ) {
    // do lot of stuff here 
}

Now the generic can hold base type as double and string and it can hold some user-defined type also. There is a particular situation where I have to some specific work depending upon the type of the generic.

so the final code block looks something like this

for( all the keys in myGeneric ) {
    if key is type foo then 
    	//do foo foo 
    else if key is of type bar 
    	//do bar bar 
}

Now, as complexity sensitive as I am I do not like to have an if condition in the for loop. So the next solution I did was

if myGeneric is of type foo 
    call fooIterator(myGeneric) 
if myGenric is of type bar 
    call barItetrator(myGeneric)


function FooIterator() {
    // .....
    // foo work 
    //......
}

function BarItetrator() {
    // .....
    // bar work 
    //......
}

Then again when somebody sees my code then I am quite sure that they will shout where is the "refactoring".

What is the ideal thing to do in this situation ?

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about refactoring