extract method for better readability

G

Guest

hey all,
i have about a 40 or more lines in my switch statement and was just
wondering if it was worth extracting out the individual case statement which
would involve passing a Table object, 2 ints and a string?

What's the rule of thumb?

thanks,
rodchar
 
N

Nicholas Paldino [.NET/C# MVP]

You are going to have to provide more information than that. In what
way do you want to extract out that case statement?
 
B

Ben Voigt [C++ MVP]

rodchar said:
hey all,
i have about a 40 or more lines in my switch statement and was just
wondering if it was worth extracting out the individual case statement
which
would involve passing a Table object, 2 ints and a string?


I think I would in that case.
What's the rule of thumb?

If naming the block is more helpful than seeing the code, then make it a
helper function.
 
L

Larry Smith

hey all,
i have about a 40 or more lines in my switch statement and was just
wondering if it was worth extracting out the individual case statement
which
would involve passing a Table object, 2 ints and a string?

What's the rule of thumb?

Your question isn't very clear. Presumably you mean invoking a function for
each case statement or some particularly long case statement (or some
variation of this). If so then you should normally do that anyway IMHO
unless (perhaps) there's one (trivial) line per case. Note BTW that a case
statement (or equivalent "if" statements) often indicates a design problem
in OOP. I have no idea if that applies in your own case but testing
multiples values in a switch statement is often better replaced with objects
that have virtual functions (all derivatives of some common base class). It
depends on the situation of course since there's always a judgment call to
make and not everyone will always agree. It's typically better however to
invoke a virtual function on some object in a collection then to test a type
in a switch statement. You should always consider this whenever writing a
switch statement. For instance, switching on employee type such as
"manager", "architect", "developer", etc., and then calling a
"SalaryRange()" function for each employe type is poor design. It's better
to provide an abstract "Employee" class and an abstract "SalaryRange()"
function. You then create one derivative for each employee type and override
this function accordingly.
 
R

Rene

What's the rule of thumb?

I would say that the rule of thumb is: "If it makes your code easier to
understand and more maintainable do it".
 
G

Guest

sorry for the brevity of the OP but the feedback was helpful nonetheless.
thanks,
rod.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top