I want to print the border of the square... It may print only one side, or more sides of the square, so I wrote this method
printBorder(N, E, S, W) {
if (N) {
square.printBorder(0,0,0,10);
}
if (E) {
square.printBorder(0,10,10,10);
}
if (S) {
square.printBorder(10,0,10,10);
}
if (W) {
square.printBorder(0,0,10,0);
}
}
It can work fine, but I think it is not so elegant, it is too many if, and all statement is more or less the same. I think there must be have a way to simplify this codes, any suggestions?
Personally, I really like binary comparisons.
const uint NORTH = 1;
const uint SOUTH = 2;
const uint EAST = 4;
const uint WEST = 8;
// ... some code ...
printBorder(NORTH + EAST);
// ... some other code ...
printBorder(uint Sides)
{
if((NORTH & Sides) > 0) square.printBorder(0, 0, 0, 10);
if((SOUTH & Sides) > 0) square.printBorder(0, 10, 10, 10);
if((EAST & Sides) > 0) square.printBorder(10, 0, 10, 10);
if((WEST & Sides) > 0) square.printBorder(0, 0, 10, 0);
}
Some might say that this makes the code inside the function less readable. However, my thinking is there is only a single occurrence of this function whereas you will be calling this function all over the place. If you're running through some code you haven't looked at in awhile which is more readable?
printBorder(true, false, true, true);
or
printBorder(NORTH + SOUTH + EAST);
Just my opinion. :)