블록과 문장을 작성하는 데 다음과 같은 지침을 사용하라.
o 한 줄 당 오직 하나의 문장 만을 배치하라.
o 제어문(예를 들자면, 'if')에는 항상 중괄호({})를 사용하라.
o 특히 긴 블록이나 중첩된(nested) 블록일 경우, 주석으로 블록의 끝을 표시하는 것을 고려해보라.
(예를 들어, ) // end if)
o 변수의 선언은 블록의 시작 부분에 위치시켜라.
o 항상 변수를 초기화하라.
o 당신이 완벽주의자라면 변수 이름은 모두 왼쪽 정렬하여 나란히 배치되도록 하라.
o switch 블록 안의 case절(clause)을 들여 쓰라.
o 연산자의 앞과 뒤에 공백을 넣어라.
o if, for, while에서 여는 괄호 앞에 공백을 넣어라.
o 가독성을 높이기 위해 수식(expression)에 괄호와 공백을 사용하라.
for 루프에 사용된 변수들은 블록 시작부분에 변수를 배치한다는 것의 예외이다. 루프 변수들은 for 문의 초기화 부분에서
선언될 수 있다. 예를 들어, for (int i = 0; ...)
블록의 끝에 주석을 놓는 것은 당신이 지워진 닫는 중괄호())를 우연히 발견할 수 있도록 도와준다.
커다란 소스 파일에서 그러한 것들을 찾는 것은 당신을 거의 미치게 만들어버릴 수도 있다.
다음은 그러한 예를 보여주고 있다.
E x a m p l e 3 . 나쁜 블록 스타일.
try{
for(int i=0;i<5;i++){
...
}
int threshold=calculateThreshold();
float variance=(threshold*2.8)-1;
int c=0;
if (threshold<=15) c=calculateCoefficient();
switch(c){
case 1: setCeiling(c*2); break;
case 2: setCeiling(c*3); break;
else: freakOut();
}
}catch(Exception ex){ ... }
E x a m p l e 4 . 좋은 블록 스타일
try {
int threshold = 0;
float variance = 0.0;
int coefficient = 0;
// Prepare 5 cycles.
for (int i = 0; i < 5; i ++){
prepareCycle(i);
}
// Calculate the threshold and variance.
threshold = calculateThreshold();
variance = (threshold * 2.8) - 1;
// If the threshold is less than the maximum, calculate the coefficient.
// Otherwise, throw an exception.
if (threshold <= MAX_THRESHOLD) {
coefficient = calculateCoefficient();
} else {
throw new RuntimeException("Threshold exceeded!");
}
// Set the ceiling based on the coefficient.
switch (coefficient) {
case 1:
setCeiling(coefficient * 2);
break;
case 2:
setCeiling(coefficient * 3);
break;
else:
freakOut();
} // end switch
} catch(Exception ex) {
...
} // end try
소스 파일
일반적으로 자바 소스 파일을 보기 쉽게 하는 좋은 배치 순서라는 것이 존재한다.
다음의 구성순서는 추천할 만한 것 중의 하나이다.
1. 파일 헤더 주석 (선택적)
2. 패키지 선언
3. 빈 줄이나 다른 구분자(seperator)
4. import 문장들
5. 빈 줄이나 다른 구분자(seperator)
6. 클래스(들)
E x a m p l e 5 . 나쁜 파일 구조.
package org.rotpad;
import java.awt.*;
import javax.swing.event.*;
import org.javacogs.*;
import javax.swing.*;
import java.awt.event.*;
class Foo {
...
}
public class RotPad extends JFrame {
...
}
E x a m p l e 6 . 좋은 파일 구조
package org.rotpad;
// Java classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
// JavaCogs classes
import org.javacogs.*;
/**
* RotPad is a simple GUI application for performing
* rotation ciphers on plain text.
*
* @author Thornton Rose
* @version 1.0
*/
public class RotPad extends JFrame {
...
}
//------------------------------------------------------
/**
* Foo is ...
*
* @author Thornton Rose
* @version 1.0
*/
class Foo {
...
}
'Java' 카테고리의 다른 글
[펌] 자바 언어의 퍼포먼스(JVM의 작동 원리) (0) | 2006.05.17 |
---|---|
[Good Java Style -3] import 문장들 - End (1) | 2006.05.16 |
[Good Java Style -1] 탭 vs 스페이스 (Tab vs. space) (0) | 2006.05.16 |
[펌] 하루전/하루후/몇일전/몇일후 날짜 구하기 (0) | 2006.05.16 |
[펌] Java 초기 CLSSPATH 세팅 (SDK 설치) (0) | 2006.05.16 |