Programming and Programming Methods
Programming and Programming Methods
2
Developing Software (the traditional approach)
Developers go through a number of phases and complete each before moving to the next one:
Design
InstallationOperation and Maintenance
Analysis and Specification
Implementation
Testing
3
Choice of programming language Good programming practice Coding standards
Overview
4
Implementation
Real-life products are generally too large to be implemented by a single programmer
This chapter therefore deals with programming-in-the-many
5
Programming Languages
A program is written by a developer in a special computer language.– E.g. C, C++, Pascal, BASIC, Java.
It is then translated by a special program (compiler) into machine code (In case of Java Java byte code).– Machine code (and Java byte code) consists of
binary numbers (0s and 1s) that computers understand.
6
A Brief History of Programming Languages
Assembly language:– First and most basic language.– Each of the separate instructions that a computer
understand is represented by a word that is a bit like English.
e.g. MOV for move, SUB for subtract.– A special piece of software (called assembler) is
then used to convert our program into machine code.
– Low level language.
7
A Brief History…Continued
Most programs require sophisticated instructions. Very difficult to write in assembly.
High level languages (also known as 3GLs) were created.
– C, COBOL, PASCAL, BASIC
The set of programming instructions is called the program code, or source code.
Translation into the machine code is known as compilation (using a Compiler).
8
Object Oriented Programming Languages
The most recent development in the history of programming languages– E.g. Java, C++
Java programs are compiled and run differently to other languages.
Let’s see this difference!
9
** Generation Languages
First generation languages– Machine languages (binary machine code instructions)
Second generation languages– Assemblers (symbolic notation such as “mov $4, next”)
Third generation languages– High-level languages (COBOL, FORTRAN, C++, Java) – One 3GL statement is equivalent to 5–10 assembler statements
10
** Generation Languages
Fourth generation languages (4GLs ; 1970s-1990))– Non-procedural language (easier to code ) : Natural?– Each 4GL statement was intended to be equivalent to 30 or even
50 assembler statements– Visual Basic, Visual C++, Power Builder
Fifth generation languages– designed to make the computer solve a given problem without the
programmer.– used mainly in artificial intelligence research. – Prolog, OPS5, and Mercury
11
Fourth Generation Languages
It was hoped that 4GLs would :– One 4GL statement is equivalent to many assembler
statements : easier to understand, shorter .– Speed up application-building – Result in applications that are easy to build and quick
to change Reducing maintenance costs
– Simplify debugging – Make languages user friendly
Leading to end-user programming
Achievable if 4GL is a user friendly, very high-level language
12
Productivity Increases with a 4GL?
4GL productivity increases of 10 to 1 over COBOL have been reported
13
Fourth Generation Languages (contd)
Market share– No one 4GL dominates the software market– There are literally hundreds of 4GLs– Dozens with sizable user groups– Oracle, DB2, and PowerBuilder are popular
Reason– No one 4GL has all the necessary features
Conclusion – Care has to be taken in selecting appropriate 4GL
14
Good Programming Practice
15
Good Programming Practice
Use of consistent and meaningful variable names
– “Meaningful” to future maintenance programmers– “Consistent” to aid future maintenance programmers
16
Use of Consistent and Meaningful Variable Names
A code artifact includes the variable names :– freqAverage, frequencyMaximum, – minFr, frqncyTotl
What is the problem ?– A maintenance programmer has to know if freq, frequency,
fr, frqncy all refer to the same thing
What do instead :
– If so, use the identical word, preferably frequency, perhaps freq or frqncy,but not fr
– If not, use a different word (e.g., rate) for a different quantity
17
Consistent and Meaningful Variable Names
We can use frequencyAverage, frequencyMyaximum, frequencyMinimum, frequencyTotal
We can also use averageFrequency, maximumFrequency, minimumFrequency, totalFrequency
But all four names must come from the same set
18
The Issue of Self-Documenting Code
Self-documenting code is exceedingly rare
The key issue: Can the code artifact be understood easily and unambiguously by
– The SQA team– Maintenance programmers– All others who have to read the code
19
Self-Documenting Code Example
Example:– Code artifact contains the variable : xCoordinateOfPositionOfRobotArm
– This is abbreviated to xCoord
Is that fine to abbreviate?– This is fine, because the entire module deals with the
movement of the robot arm
What about for other users of the code ?– But does the maintenance programmer know this?
20
Prologue Comments
Minimal prologue comments for a code artifact
21
Comments
It is useful to have comments in your code:– It helps remind us what we were doing.– It helps other people to understand our code.
We want the compiler to ignore these comments! Two ways of doing this:
– Short comments: we place two slashes (//) at the beginning of the line-everything up to the end of the line is ignored.
– Longer comments (more than one line comments): /*we ecnlose the comment between two special symbols*/,
the opening (/*) and the closing (*/).
22
Other Comments
Suggestion– Comments are essential whenever the code is
written in a non-obvious way (?)– or when makes use of some subtle aspect of
the language (?)
Often a bad sign ! Instead :
– Recode in a clearer way– We must never promote/excuse poor
programming– However, comments can assist future
maintenance programmers
23
Code with Comments
// this is a short comment, so we use the first methodclass Hello5{ public static void main(String[] args) {
System.out.println("Hello world"); EasyIn.pause("Press <Enter> to quit");
} /* this is the second method of including comments – it is
more convenient to use this method here, because the comment is longer and goes over more than one line */
}
24
Code Layout for Increased Readability
Use indentation
Better, use a pretty-printer
Use plenty of blank lines– To break up big blocks of code
25
Nested if Statements
Example– A map consists of two squares. Write code to
determine whether a point on the Earth’s surface lies in map square 1 or map square 2, or is not on the map
26
Nested if Statements
Solution 1. Badly formatted
27
Nested if Statements
Solution 2. Well-formatted, badly constructed
28
Nested if Statements
Solution 3. Acceptably nested
29
Nested if Statements
A combination of if-if and if-else-if statements is usually difficult to read
Simplify: The if-if combination
if <condition1>
if <condition2>
is frequently equivalent to the single condition
if <condition1> && <condition2>
30
Nested if Statements
Rule of thumb :
– if statements nested to a depth of greater than three should be avoided as poor programming practice
31
C 언어의 예 2 : 짧을 수록 명확해 진다Void FillPowersArray(int base, int *power){
*powers = base;*powers+1 = base*base;*powers+2 = base*base*base;*powers+3 = base*base*base *base;*powers+4 = base*base*base *base *base;*powers+5 = base*base*base *base *base *base;*powers+6 = base*base*base *base *base *base *base;*powers+7 = base*base*base *base *base *base *base *base; base;
}(a) Not Desirable
void FillPowersArray(int base, int *power){
*powers = base;for( i=2; i<= 8; i++) *pwers +1 = *powers +1-1*base;
}
(b) Desirable
Desirable coding style
32
Style 1 ( 계속 ) : 짧을수록 간결하다 . 그러나 간결함보다 중요한 것은 명확함이
다 . 짧을수록 명확하지만 예외는 없다 . 16 진법으로 표현된 수를 문자형으로
읽어 해당하는 십진법의 정수를 리턴하는 프로그램이다 .
Int IntegerFromHex(char HexDigit){ if (HexDigit <58) return (HexDigit - 48) ; else return (HexDigit - 56) ;}
/** 예 ) 0-9 까지 ASCII 코드값이 48 에서 57 까지 순서대로 되어 있어 ASCII 값에서 48 을 빼면 된다 . A - F ==> 65 - 70 **/
Desirable coding style
33
int IntegerFromHex(char HexDigit){
Switch(char HexDigit){case ‘0’ : IntegerFromHex = 0 ; break ;case ‘1’ : IntegerFromHex = 1 ; break ;case ‘2’ : IntegerFromHex = 2 ; break ;case ‘3’ : IntegerFromHex = 3 ; break ;case ‘4’ : IntegerFromHex = 4 ; break ;case ‘5’ : IntegerFromHex = 5 ; break ;case ‘6’ : IntegerFromHex = 6 ; break ;case ‘7’ : IntegerFromHex = 7 ; break ;case ‘8’ : IntegerFromHex = 8 ; break ;case ‘9’ : IntegerFromHex = 9 ; break ;case ‘A’ : IntegerFromHex = 10 ; break ;case ‘B’ : IntegerFromHex = 11 ; break ;case ‘C’ : IntegerFromHex = 12 ; break ;case ‘D’ : IntegerFromHex = 13 ; break ;case ‘E’ : IntegerFromHex = 14 ; break ;case ‘F’ : IntegerFromHex = 15 ; break ;}
}
위 프로그램은 16진법을 구성하는 숫자와 문자의 ASCII값을 모르더라도 쉽게 의미를 파악할 수 있다 . 이 프로그램은 간결하지 않지만은 명확하다 .
Desirable coding style
34
구조적 코딩 기법구조적 코딩은 순차 , 선택 , 반복으로 프로그래밍하여 모든 제어의 흐름을 표현할 수 있다 . 무조건적 GOTO 문의 복잡한 제어의 흐름을 방지 하려고 노력한다 . 경우에 따라서는 GOTO 문의 사용이 코드를 명확하게 하고 단순하게 한다 .
DO 50 I=1, COUNT . . .IF (ERROR1) GO TO 60 . . .IF (ERROR2) GO TO 70 . . .
50 CONTINUE
60 {Code for Error1 handling}
GO TO 80
70 {Code for Error2 handling}
80 CONTINUE
GO TO 문을 이용한 오류처리
Use structured coding
35
I=1
While I <= TableSize and Table(I) <> Target do
I=I+1
If I>TableSize then {code for target not found}
else {code for target found}
(a) structured coding
for I=1 to TableSize do
if Table(I) = Target then goto Found
NotFound : {code for Target then goto Found}
Found : {code for Target found}
(b) GO TO statement
(a) 는 세 번의 논리형 테스터가 필요하였으나 (b) 가 더 자연스럽고 읽기 쉬운 프로그램이다 . 이상과 같이 구조적 프로그래밍을 한다고
반드시 명확하고 효율적인 프로그램이 작성되는 것은 아니다 .
구조적 프로그램의 원칙은 상황에 따라 위배될 수도 있으며 중요한 것은 구조적 스타일로 프로그램을 작성하는 것이다 .
Use structured coding (in table search)
36
Desirable coding style
스타일이란 어떤 작업의 선택에 있어서 일관된 유형을 말한다 .
*** 좋은 스타일의 대표적 판별기준 ***
- 복잡하지 않고 명확하여 이해하기 쉬운 것이다 .
- 프로그램을 이해하는데 노력이 필요치 않으며 수정이 용이하다 .
Style 1 : Write clearly.
C 언어의 예 1)
int i, j : float v{N}{N} ;. . .for( i=1; i<= N ; i++) for (j=1; j<= N; j++)
v[i-1][j-1] = (i-1)*(j-1) ;
for( i=0; i<=N ; i++) { for ( j=0; j< N; j++) {
v[i][j] = (i)*(j) ; } }
Not Desirable Desirable
37
Style 2 : Write directly what you intend to.
if ( x < y ) {
if ( x < z ) small = x ;
if ( x > z ) small = x ;
}
if ( x < y ) {
if ( y < z ) small = y ;
if ( y > z ) small = z ;
}
x, y, z 세개의 값 중에 가장 가장 작은 것을 small 이라는 변수에 기억시키려는 과정으로 변수의 이름을 암시 받을 수 있다 . 그러나 x, y, z 중에 같은 값을 가진 경우 small 값은 올바른 값을 갖지 못한다 .
Small = x ;
if ( y < small ) small = y ;
if ( z < small ) small = z ;
위의 프로그램에서는 세개 이상의 값에 대해서도 같은 방법으로 쉽게 확장 가능 .
Desirable coding style
Desirable !!
Not desirable !!
38
If . . . Else 선택구조에서는 짧은 구문을 먼저 쓰는 것이 이해하기 좋다 . 즉 else 구문은 if 조건과 가깝게 위치 시킨다 .
if (in_user_code){ in_user_code = FALSE ; r2 = r; reset_phariap() ; send_sig_segv() ;}else revert() ;
if not (in_user_code) revert() ;
else { in_user_code = FALSE ; r2 = r reset_pharlap() ; send_sig_segv() ;}
Desirable !!
Not desirable !!
Desirable coding style
39
Style 3 : Avoid temporary use of variables.효율적인 프로그램을 작성하겠다는 의도에서 간결하게 표현될 수 있는 것을 색다르게 표현하는 경우가 있다 .
예 )
t1 = x1-(x2+x2) ;
t2 = 7 - x2 ;
y = t1+t1+t2+t2 ;
/** 곱하기 보다 더하기가 수행시간이 빠르기는 하나 임시 변수 사용 불가 **/
y = 2*(x1-2*x2) + 2 *(7-x2) ;
( 임시로 사용된 t1,t2 라는 변수를 없애고 이로 인하여 프로그램의 의도가 더욱 분명해졌다 .)
Note : 프로그램에서 임시 변수가 적게 사용되면 초기화하지 않아서 일어나는 오류나 사용하기 전에 예기치 않게 값이 바뀌는 오류가 줄어든다 .
Desirable !!
Not desirable !!
Desirable coding style
40
Style 4 : Use variable name not confusing.- 오류를 유발할 수 있는 문자
- 비슷한 문자열을 같이 사용하거나 끝에 한 글자만 다른 변수명을 사용하는
것은 혼돈을 일으키기 쉽다 .
즉 , PositionX 와 PositionY 는 XPos, YPos 와 같이 첫 글자부터 다른 이름을 붙이는 것이 좋다 .
- 축약된 이름을 붙인다 . 발음이 가능한 이름으로 한다 .
예 ) XPstn 보다는 XPos
숫자 문자 예 1 과 I a1 Ai
0 과 O term0 termO
5 과 S TEXT5 TEXTS
I 과 l Iist list m 과 n 의 연속사용 mnnm mnmn
u 와 v 의 연속사용 vuvu uuvu
Desirable coding style
41
- Use similar or identical length of variable for consistency Not desirable)
n = K ;
nn = K*K ;
nnn = K*K*K;
Desirable)
nunit = K ;
nsqur = K*K ;
ncube = K*K*K;
Desirable coding style
42
Style 5 : Use Consistent Rule in Variable naming
(Not desirable program)
char buffer[500], mssge[80] ; /** 약자 사용에 일관성 결여 **/
void read_instance(void), SaveCurrent(void) ;
/** 단어의 연결이 다름 **/
void get_line(void), write_line(void) ;
int index1, index2 ;
/** 인덱스의 변수 이름은 너무 길다 **/
int dirctry, Vsble ;
/** 약자 사용법이 다름 **/
Desirable coding style
43
Style 7 : Use if…else only for selection purpose from exclusive choices
(Not Desirable if (swct1 = ‘1’) goto Conti ;else { dvict1 += 10; swct1 = 11 ; }Conti ;
(Desirableif (swct1==‘1’) { devct1+=10; swct1 =‘1’ ;}
한가지 조건에 의한 작업만 있을 경우에는 if문을 사용한다 .
Desirable coding style
44
Style 8 : if 다음에 if 가 따라오는 구조나 null else 는 피할 것 .
Not Desirable if (qty>10) if( qty > 200) if (qty >=500) bill_a+=1.00 ;
else bill_a + 0.50 ; else ; else bill_a = 0.0 ;
Desirable coding style
Desirable (a) if ( qty >= 500 ) bill_a += 1.0 ;else if ( qty > 200) bill_a += 0.5 ;else if (qty <= 10) bill_a += 0.0 ;
Desirable (b)if (qty >= 500.0 ) bill_a+10; if (qty < 500 && qty>200 ) bill_a + 0.5; if (qty <= 10 ) bill_a + 0.0;
45
Style 9 : 문장의 반복을 최소화 한다 . 같은 문장이 반복되면 이해도 어렵고 유지보수도 어렵다 .
함수나 매크로 , break, continue, return 을 반복 구조 안에 적절히 사용한다 .
Not Desirable get_t.ken () ; if (tkn = = T_END) return ;/* A */ if (tkn = = T_START) stant-proc () ; /* B */ while (ntokens < T_LIMIT) /* C */ { process_token () ; add_entry ; get_t.ken () ; if (tkn = = T_END) return ; if (tkn = = T_START) stant-proc() ; }
Desirable coding style
for ( ; ; ){ get_t.ken() ; if (tkn = = T_END) return ; if (tkn = = T_START) stant-proc() ; if (T_LIMIT <= ntokens) break; process_token () ; add_entry ;}
첫 세문장 A, B, C 가 반복구조 안에서 다시 사용되고 있다 . While 구조를 문한 루프의 for 문장으로 바꾸어 프로그램할 수 있다 .
Desirable
46
Programming Standards
Standards can be both a blessing and a curse
Modules of coincidental cohesion arise from rules like – “Every module will consist of between 35 and 50
executable statements”
Better– “Programmers should consult their managers before
constructing a module with fewer than 35 or more than 50 executable statements”
47
Remarks on Programming Standards
No standard can ever be universally applicable
Standards imposed from above will be ignored
Standard must be checkable by machine
48
Examples of Good Programming Standards
“Nesting of if statements should not exceed a depth of 3, except with prior approval from the team leader”
“Modules should consist of between 35 and 50 statements, except with prior approval from the team leader”
“Use of gotos should be avoided. However, with prior approval from the team leader, a forward goto may be used for error handling”
49
Remarks on Programming Standards
The aim of standards is to make maintenance easier:
– If they make development difficult, then they must be modified
– Overly restrictive standards are counterproductive– The quality of software suffers
50
Code Reuse
Code reuse is the most common form of reuse
However, artifacts from all workflows can be reused :
51
Conclusions