【Clean Code】代码简洁之道

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/It_sharp/article/details/82771645

有意义的命名

名副其实

int elapsedTimeInDays // 消逝的时间,以日计
int daysSinceCreation // 自创建之日起的计算日子
int daysSinceModification // 自修改之日起计算的日子
int fileAgeInDays // 文件的创建时间
public List<Cell> getFlaggedCells()
{
	List<Cell> flaggedCells = new ArrayList<Cell>();
	for(Cell  cell in gameBoard)
	{
		if(cell.isFlagged())
		{
			flaggedCells.add(cell);
		}
		return flaggedCells;
	}
}

做有意义的区分

public static void copyChars(char[] source , char[] destination)
{
	for(int i=0 ; i<source.Length; i++)
	{
		destination[i] = source[i];
	}
}

使用读的出来的名字

错误例子

class DtaRcrd102
{
	private Date genymdhms;
	private Date modymdhms;
	private final String pszqint = "102";
}

正确例子

class Customer
{
	private DateTime generationTimestamp;
	private DateTime modificationTimestamp;
	private const String recordId ="102";
}

使用可搜索的名字

int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0 ;
for( int j=0 ;j<NUMBER_OF_TASKS ;j++)
{
	int realTaskDays = taskEstimate[j]* realDaysPerIdealDay;
	int realTaskWeeks = (realdays/WORK_DAYS_PER_WEEK);
	sum+= realTaskWeeks;
} 

成员前缀少用

public class Part
{
	string decription;
	void setDescription(string description)
	{
		this.description = description;
	}
}

类名避免动词

类名和对象应该是名词或名词短语,如Customer、WikiPage、Account、AddressParser避免使用Manager、Processor、Data或Info这样的类名。类名不应该是动词。

方法名使用动词或动词短语

方法使用动词短语如:postPayment、deletePage、或Save
属性访问器、修改器和断言应该加上 get、set、和is前缀

string  name = employee.getName();
Customer.setName("Mike");
if(paycheck.isPosted())...

重载构造器时,使用描述了参数的静态工厂方法名

Complex fulcrumPoint = Complex.FromRealNumber(23.0);
通常好于
Complex fulcrumPoint = new Complex(23.0);

添加有意义的语境

前缀:firstName、lastName、street、houseNumber、city、state、和zipcode变量
加上前缀后:addrFirstName、addrLastName、addrState等等提供语境,更好的方案是 创建名为Address的类

猜你喜欢

转载自blog.csdn.net/It_sharp/article/details/82771645