Cags
Contributor
I have read in many places how having multiple exit points in a program is not a good idea and can cause trouble during testing aswell as disrupt the general readability of code. Having said this I often find myself writting code like this.
Essentially what this does is check the keyvalue, then if it was the key you pressed it is handled and there is no reason to continue checking through each key value. I format my code like this as I find it nicer to read than the equivalent example with a singular exit point (also this method also prevents checking all other key values after the event has been handled)...
Now I'll freely admit that in this example I've give the code is perfectly understandable, but once you start adding alot of if / else, switch statements or loops in place of the comments I put above things soon start getting extremely complicated to follow. I guess Methods could be used for each key, but in some system that would be creating an awefull lot of methods, some of which wouldn't have more than a line or two of code. I just wondered what anyone else had to say about the matter.
C#:
// multiple exit points
if(e.Control)
{
// ctrl s, save
if(e.KeyValue == 83)
{
// save file
return;
}
// ctrl o, open
if(e.KeyValue == 83)
{
// open file
return;
}
// ctrl e, perform action blah...
if(e.KeyValue == 69)
{
// do stuff
return;
}
}
else
{
}
Essentially what this does is check the keyvalue, then if it was the key you pressed it is handled and there is no reason to continue checking through each key value. I format my code like this as I find it nicer to read than the equivalent example with a singular exit point (also this method also prevents checking all other key values after the event has been handled)...
C#:
// single exit point
if(e.Control)
{
if(e.KeyValue == 83) // ctrl s, save
{
// code to save file
}
else if(e.KeyValue == 79) // ctrl o, open
{
// code to load file
}
else if(e.KeyValue == 69) // ctrl e, perform action blah
{
// do stuff...
}
}
else
{
}
return;
Now I'll freely admit that in this example I've give the code is perfectly understandable, but once you start adding alot of if / else, switch statements or loops in place of the comments I put above things soon start getting extremely complicated to follow. I guess Methods could be used for each key, but in some system that would be creating an awefull lot of methods, some of which wouldn't have more than a line or two of code. I just wondered what anyone else had to say about the matter.