DNB*_*ims 1 optimization if-statement pseudocode
我想要打印正方形的边框......它可能只打印一面或正方形的更多边,所以我写了这个方法
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);
}
}
Run Code Online (Sandbox Code Playgroud)
它可以很好地工作,但我认为它不是那么优雅,它是太多了,如果,所有声明或多或少相同.我认为必须有办法简化这些代码,任何建议?
简化它的一种方法...即使你不需要它也可以进行调用,但是条件化实现:
printBorder(N, E, S, W){
square.printBorder(n, 0,0,0,10);
square.printBorder(e, 0,10,10,10);
square.printBorder(s, 10,0,10,10);
square.printBorder(w, 0,0,10,0);
}
Run Code Online (Sandbox Code Playgroud)
然后在Square(或其他):
printBorder(condition, top, left, bottom, right) {
if (!condition) {
return;
}
printBorder(top, left, bottom, right);
}
Run Code Online (Sandbox Code Playgroud)
类似的替代方案是保持条件printBorder与原始函数:
printBorder(N, E, S, W){
printBorder(n, 0,0,0,10);
printBorder(e, 0,10,10,10);
printBorder(s, 10,0,10,10);
printBorder(w, 0,0,10,0);
}
printBorder(condition, top, left, bottom, right) {
if (!condition) {
return;
}
square.printBorder(top, left, bottom, right);
}
Run Code Online (Sandbox Code Playgroud)
我不在乎ifs.我只是让它更具可读性:
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);
}
Run Code Online (Sandbox Code Playgroud)