Re: big function vs many small functions
- From: Christopher Corbell <chriscorbell@xxxxxxxxx>
- Date: Wed, 26 Sep 2007 17:43:19 -0000
On Sep 25, 5:30 am, teke...@xxxxxxxxxxx (t.j.) wrote:
Let's say that one has a function with a large switch statement with
many case statements.
One way of writing the function is to just place all of the code for
each case inside of the function containing the switch statement.
Another would be to have an individual function for each case statement.
Which way is better in terms of maintainability and frequency of bugs?
I recall reading something where someone actually studied this situation
and determined there was no meaningful difference between the two.
Anyone else come across the same thing?
It depends on how much logic is going into each case block. In some
cases switch statements are just used to convert e.g. from an
enumeration to a string representation; when each block is doing a
variant of the same thing and the logic is trivial the switch
statement is clearer. OTOH if there's significant code to each case -
certainly if there are any nested blocks of conditional code -
factoring into method calls is clearer. And if the switch is
essentially a dispatch table it should certainly call different
functions for each case and not try to implement cases in-place.
Also note that there may be object-oriented patterns that allow an
entire problem to be solved elegantly with something other than a
switch. Say for example you have a "type" class data member and
several methods which switch on type to select a certain behavior.
This may be better solved by creating an interface or abstract class
with the methods declared and defining the alternative implementations
in subclasses rather than using a switch statement in one concrete
class (assuming a given instance's "type" doesn't change).
Or, if you have a function that is parameterized and may behave
different ways based on some parameter, but that parameter represents
a relatively stable system state or configuration, you might be able
to use a strategy pattern or decorator pattern (creating a helper
object which provides the needed implementation) instead of a switch
statement in the function body.
- Chris
.
- References:
- [Q] big function vs many small functions
- From: t.j.
- [Q] big function vs many small functions
- Prev by Date: Re: Mathematical models for loop calculations
- Next by Date: Re: Mathematical models for loop calculations
- Previous by thread: Re: [Q] big function vs many small functions
- Next by thread: Where does programming begin?
- Index(es):
Relevant Pages
|