通过重构简化代码

Sai*_*ira 6 c java refactoring

是否存在可以简化此类冗余代码的C或Java重构工具.我相信这称为数据传播.

这基本上是优化编译器的功能.

public int foo() {
    int a = 3;
    int b = 4;
    int c = a + b;
    int d = c;
    System.out.println(c);
    return c;
}
Run Code Online (Sandbox Code Playgroud)

public int foo() {
    int c = 7;
    System.out.println(c);
    return c;
}
Run Code Online (Sandbox Code Playgroud)

Alf*_*rio 20

我认为这不是一个好主意.

例如,以下代码:

long hours = 5;
long timeInMillis = hours * 60 * 1000;
Run Code Online (Sandbox Code Playgroud)

这比以下更清洁,更容易理解:

long timeInMillis = 300000;
Run Code Online (Sandbox Code Playgroud)

  • @ Woot4Moo - 任何现代编译器都会自动优化它.因此,除了清理源代码之外,没有其他动机可以做到这一点.但是,使代码不易读取并不是一个好主意. (2认同)

Pas*_*uoq 6

我能为我的下一个解决方案解决方案使用,我在另一个答案中描述的两个工具在这里(以相反的顺序).

这是你的程序,翻译成C:

int foo() {
    int a = 3;
    int b = 4;
    int c = a + b;
    int d = c;
    printf("%d", c);
    return c;
}
Run Code Online (Sandbox Code Playgroud)

第1步:不断传播

$ frama-c -semantic-const-folding t.c -lib-entry -main foo
...
/* Generated by Frama-C */
/*@ behavior generated:
      assigns \at(\result,Post) \from \nothing;  */
extern int ( /* missing proto */  printf)() ;
int foo(void) 
{
  int a ;
  int b ;
  int c ;
  int d ;
  a = 3;
  b = 4;
  c = 7;
  d = 7;
  printf("%d",7);
  return (c);
}
Run Code Online (Sandbox Code Playgroud)

第2步:切片

$ frama-c -slice-calls printf -slice-return foo -slice-print tt.c -lib-entry -main foo
...
/* Generated by Frama-C */
extern int printf() ;
int foo(void) 
{
  int c ;
  c = 7;
  printf("%d",7);
  return (c);
}
Run Code Online (Sandbox Code Playgroud)