ryan fehr ryan fehr - 1 year ago 62
Java Question

Anyone have suggestions on how to make this Java switch case more efficient/readable?

It is a pretty standard switch case used within a program that replicates an electric circuit. The main thing I am looking for is easier readability of the code and brevity, without disregarding efficiency.

edit: Didn't realize that I was unclear on the purpose of offset, the way offset works is that it will offset the input char by a number of characters equal to offset which is an integer. So for example if source is 'a' and offset is 2 this will return the value within the paths array at index 2.

char passCurrent(char source)
source += offset;

case 'a':
return this.paths[0];
case 'b':
return this.paths[1];
case 'c':
return this.paths[2];
case 'd':
return this.paths[3];
case 'e':
return this.paths[4];
case 'f':
return this.paths[5];
case 'g':
return this.paths[6];
case 'h':
return this.paths[7];
case 'i':
return this.paths[8];
case 'j':
return this.paths[9];
case 'k':
return this.paths[10];
case 'l':
return this.paths[11];
case 'm':
return this.paths[12];
case 'n':
return this.paths[13];
case 'o':
return this.paths[14];
case 'p':
return this.paths[15];
case 'q':
return this.paths[16];
case 'r':
return this.paths[17];
case 's':
return this.paths[18];
case 't':
return this.paths[19];
case 'u':
return this.paths[20];
case 'v':
return this.paths[21];
case 'w':
return this.paths[22];
case 'x':
return this.paths[23];
case 'y':
return this.paths[24];
case 'z':
return this.paths[25];
return '/';

Answer Source

Eliminate the switch and use subtraction after checking the range. Something like,

if (source >= 'a' && source <= 'z') {
    return this.paths[source - 'a'];
return '/';

And, we can shorten that further with a ternary like

return (source >= 'a' && source <= 'z') ? 
        this.paths[source - 'a'] : '/';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download