C++ best practices for current ToME2 code?
Posted: Wed Mar 02, 2016 2:42 pm
The below is an example of type of structure common in T2 code, in areas ported directly from the original C. This one's from traps.cc:
That's the beginning of the function. It continues for about a thousand lines, with the switch() cases getting progressively longer and more complex as it goes on. High cognitive overhead, much repeated code, etc.
The obvious answer in C is, split this up into smaller functions. And eventually, try to pass as much stuff as possible by function parameters, and get rid of those big switch() statements. Or so I'd think, anyway. But at the very least, the giant switch() could be split up into a bunch of smaller switch()ing functions with the trap type as a parameter.
(That'd be hackish, but would be better than the original for now.)
The problem is, this is supposed to be C++, not C. I have no idea what the standard answer to this is in typical C++98 paradigms, let alone functional-style C++11.
How should I be refactoring the code for stuff like this?
Code: Select all
/*
* this function activates one trap type, and returns
* a bool_ indicating if this trap is now identified
*/
bool_ player_activate_trap_type(s16b y, s16b x, object_type *i_ptr, s16b item)
{
bool_ ident = FALSE;
s16b trap;
s16b k, l;
trap = cave[y][x].t_idx;
if (i_ptr != NULL)
{
trap = i_ptr->pval;
}
switch (trap)
{
/* stat traps */
case TRAP_OF_WEAKNESS_I:
ident = do_dec_stat(A_STR, STAT_DEC_TEMPORARY);
break;
case TRAP_OF_WEAKNESS_II:
ident = do_dec_stat(A_STR, STAT_DEC_NORMAL);
break;
case TRAP_OF_WEAKNESS_III:
ident = do_dec_stat(A_STR, STAT_DEC_PERMANENT);
break;
case TRAP_OF_INTELLIGENCE_I:
ident = do_dec_stat(A_INT, STAT_DEC_TEMPORARY);
break;
/*** Continues this way for a long while ***/
The obvious answer in C is, split this up into smaller functions. And eventually, try to pass as much stuff as possible by function parameters, and get rid of those big switch() statements. Or so I'd think, anyway. But at the very least, the giant switch() could be split up into a bunch of smaller switch()ing functions with the trap type as a parameter.
(That'd be hackish, but would be better than the original for now.)
The problem is, this is supposed to be C++, not C. I have no idea what the standard answer to this is in typical C++98 paradigms, let alone functional-style C++11.
How should I be refactoring the code for stuff like this?