我正在练习如何查找和删除死代码。我有以下代码:
int c1 = Integer.parseInt(args[0]) ;
int c2 = Integer.parseInt(args[1]) ;
int c3 = Integer.parseInt(args[2]) ;
/* 1 */ c1 += 7 ;
/* 2 */ System.out.println( c1 ) ;
/* 3 */ while (c1 % 8 != 0)
/* 4 */ if ( c1 % 16 == 0 ) ;
/* 5 */ else
/* 6 */ do
/* 7 */ {
/* 8 */ c1 += 7 ;
/* 9 */ System.out.println( c1 ) ;
/* 10 */ if ( c2 < c3 )
/* 11 */ { c1 = c1+c1 ;
/* 12 */ c3 ++ ;
/* 13 */ c1 /= 2 ;
/* 14 */ c3 -= 1 ;
/* 15 */ }
/* 16 */ }
/* 17 */ while ( c1 % 8 != 0 ) ;
/* 18 */ c1 += 7 ;
/* 19 */ System.out.println( c1 ) ;
}
我对这段代码的看法是:首先可以去掉if语句,因为它不影响其余代码的执行。此外,c1%16 与 c1%8 相同。
如何处理循环?
最佳答案
c%16 与 c%8 不同。如果 c 等于 24,则前者返回 8,后者返回 0。如果 c 为 32,则它们都为 0,但如果 c 为 40,则前者再次返回 8,后者返回 0。
第 4/5/6 行不是最佳的。真正发生的事情是 if c1%16 != 0, 执行 do/while 循环,但它的编写方式很糟糕。它是这样写的:“如果 c1%16 == 0,则不执行任何操作,否则执行循环”,使用naked ;如果之后。我会通过执行以下操作来使其更具可读性:
bool shouldDoLoop = c1 % 16 != 0;
if (shouldDoLoop) {
// do/while here
}
关于java - 分解循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4639642/