【Clean Code】代码简洁之道

有意义的命名

名副其实
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的类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值