*
64
1
布局与风格Layout and style
任课老师:黄武
*
64
2
提纲
基本原则
布局技术
布局风格
控制结构的布局
单条语句的布局
注释的布局
子程序的布局
类的布局
总结
问题
你从什么地方获得代码布局的知识?
为什么需要好的代码布局?
你更喜欢下面哪种布局风格?
64
3
1. Java的布局风格
void Sort( int iNum, int *pData) {
for( int i=0; i<iNum; i++ ) {
…
}
}
2. C++的布局风格
void Sort( int iNum, int *pData)
{
for( int i=0; i<iNum; i++ )
{
…
}
}
*
*
64
4
1. 基本原则
布局是指程序中软件代码的整体安排
编排出色的代码会带来视觉上和思维上的愉悦,这是非程序员不能感受的
尽管代码布局对于程序的执行速度、内存使用量等性能问题没有影响,但它对于代码理解、维护却是起到重要作用
*
64
5
1. 1 糟糕的布局
三段相同的代码具有不同的布局,但人理解的效果完全不同
清单 31-1 Java程序布局示例1
/* Use the insertion sort technique to sort the *data* array in ascending order. This routine assumes that data[ firstElement ] is not the first element in data and that data[ firstElement-1 ] can be accessed. */ public void InsertionSort( int []data, int firstElement, int lastElement ) { /* Replace element at lower boundary with an element guaranteed to be first in a sorted list. */ int lowerBoundary = data[ firstElement – 1]; data[ firstElement – 1 ] = SORT_MIN; /* The elements in positions firstElement through sortBoundary – 1 are always sorted. In each pass through the loop, sortBoundary is increased, and the element at the position of the new sortBoundary isn’t in its sorted place in the array, so it’s inserted into the proper place somewhere between firstElement and sortBoundary. */ for ( int sortBoundary = firstElement + 1; sortBoundary <= lastElement; sortBoundary++ ) { int insertVal = data[ sortBoundary]; int insertPos = sortBoundary; while ( insertVal < data[ insertPos – 1] ) { data[ insertPos] = data{insertPos - 1] ; insertPos = insertPos – 1; } data[ insertPos ] = insertVal; } /* Replace original lower-boundary element */ data[ firstElement – 1] = lowerBoundary; }
*
64
6
常见的布局
清单 31-2 Java程序布局示例2
/* Use the insertion sort technique to sort the *data* array in ascending order. This routine assumes that data[ firstElement ] is not the first element in data and that data[ firstElement-1 ] can be accessed. */
public vo
给孩子买保险的好处 来自淘豆网www.taodocs.com转载请标明出处.