读书人

Replace Assignment with Initializat

发布时间: 2013-03-21 10:08:17 作者: rapoo

Replace Assignment with Initialization -- 以初始化值取代赋值

Replace Assignment with Initialization

Refactoring contributed by Mats Henricson

You have code that first declares a variable and then assigns a value to it

你有段代码首先声明了一个变量,然后才去进行赋值。

Make it into a direct initialization instead

以初始化值取代赋值

void foo() {   int i;   // ....   i = 7;}

Replace Assignment with Initialization - 以初始化值取代赋值

void foo() {   // ...   int i = 7;}

Motivation

You often see functions in which the programmer has first declared lots of variables that will be used in that function, and then, further down the function, assigns values to them. This is often an artifact from older programming languages, where you had to declare in the beginning of the function all variables that are used in it. In C++ and Java this is not necessary, and in C++ this old style of programming can give you slower programs, since a declaration of a variable in C++ often means a call to the default constructor. In Java, declarations of variables are cheap, if not even free, but the problem is that you end up with unnecessary lines of code that adds no value to your program - you have two lines of code that can be expressed with one line of code. Another problem is the risk that at some parts of the program a variable is not explicitly initialized, so that its initial value may not be obvious, or even undefined, as is often the case in C++.

你经常会看到一些方法中,程序员首先声明了一些变量,然后再去进行赋值。

Mechanics

读书人网 >其他相关

热点推荐