switch()
QAston
qaston at gmail.com
Wed Feb 19 06:02:00 PST 2014
On Tuesday, 18 February 2014 at 02:55:10 UTC, Manu wrote:
> Me too, but you don't feel this is basically a hack?
> About half of that text is repeated cruft, and there's no
> precedent for
> formatting well-structured code like that anywhere else in the
> language.
There are other ways in D to deal with repetition. For people
coming from C/C++ some of these tricks are unnatural because
programmers writing in those prefer to just write everything
"inline" for performance reasons.
So, possible sollutions:
- go make a function:
getDifficulty(int note) {
switch(note)
{
case 60: .. case 71: return 0;
case 72: .. case 83: return 1;
case 84: .. case 95: return 2;
case 96: .. case 107: return 3;
default: return -1;
}
}
and then
difficulty = getDifficulty(e.note.note);
- you can make this function local if it's not needed anywhere,
local functions are awesome - they reduce a lot of code
duplication. Any code that repeats inside a local scope can be
put inside a local function
- you can also make e.note a real type with a method instead of
inlining the logic in place and call e.note.getDifficulty or
whatever
If your code is full of switch-cases you should probably use
polymorphism instead (virtual dispatch, omg).
More information about the Digitalmars-d
mailing list