Java Convention

이정빈·2023년 12월 14일
0

Java Algorithm

목록 보기
2/8

📖 Java Convention

Java Naming Convection은 코드의 식별자, 즉 클래스, 변수, 메서드 등의 이름을 짓는 규칙을 말합니다. 이 규칙은 코드의 가독성을 높이고 통일성을 유지하기 위해 사용됩니다. 이러한 Code Convection을 통해서 더욱 깔끔하게 코드를 공유하고 우선 순위를 둘 수 있습니다.

🗂️ File Names

Common File Names

File NameUse
GNUmakefileThe preferred name for makefiles. We use GNUmakefile to build our software.
READMEThe preferred name for the file that summarizes the contents of a particular directory

❗️ What is a Makefile?
메이크 파일은 명시적 룰, 암묵적인 룰, 변수 정의, 지시어 그리고 주석문 이렇게 다섯가지 종류의 것들이 들어 있습니다.

  • 명시적 룰 : 언제 어떻게 파일을 다시 컴파일할지를 알려줍니다. 이 룰에는 타겟이 의존하는 또 다른 파일들이 적혀 있고, 그 타겟을 새로 만들거나 업데이트를 할 명령어를 포함합니다.
  • 암묵적인 룰 : 언제 어떻게, 파일의 이름에 따라, 어떤 한 부류의 파일들을 다시 만들 것인지 알려줍니다. 해당 룰에는 특정 타겟이 다른 타겟과 비슷한 어떤 또 다른 파일에 의존하는지가 적혀 있고, 그러한 타겟을 새로 만들거나, 엡데이트하는 명령어가 들어 있습니다.
  • 변수 정의 : 변수의 문자열 값을 지정해서, 나중에 그 문자열 값 대신에 변수를 쓸 수 있도록 하는 줄입니다.
  • 지시어 : makefile을 읽을 때 make가 뭔가 특별한 작업를 하도록 만드는 명령어이다. ex) 다른 makefile 읽기, 일부 무시하고 코딩 등등
  • makefile은 주석문(#)으로 시작한다.
    GNUmakefile은 범용적으로 쓰이지 못하고 특정 프로그램에만 사용이 될 수 있다는 점이 있기 때문에 makefile이 더 범용적으로 사용이 된다.

Makefile example

JFLAGS = -g
JAVAC  = javac
RM     = rm
 
TARGET  = Helloworld.class
SOURCES = Helloworld.java
 
all: $(TARGET)
 
.SUFFIXES: .java .class
.java.class:
	$(JAVAC) $(JFLAGS) $<
 
clean:
	-$(RM) $(SOURCES:.java=.class)

이렇게 코드를 작성함으로써, 우리가 make라는 것을 Window terminal에 입력했을 때 결과를 똑같이 얻을 수 있는 것이다.


🗂️ File Organizations

Beginning Comments

/*

 * Classname
 * 
 * Version information
 *
 * Date
 * 
 * Copyright notice
 */

🙆🏻‍♂️ Comments

Implementation Comment Formats

Java can have four styles of implementation comments; Block, sigle-line, trailing, and end-of-line.

Block Comments

: Block Comments 는 파일, 메서드, 자료 구조 그리고 알고리즘에 대한 설명에 대해서 작성할 때 사용이 됩니다.

/*

 * Here is a block comment.
 */
/*-* Here is a block comment with some very special
* formatting that I want indent(1) to ignore.
*
*    one
*        two
*            three
*/

Single-Line Comments

if (condition) {/* Handle the condition. */
...
}

Trailing Comments

: Trailing Comment 는 같은 줄에 해당하는 코드가 어떤 식으로 동작하는지에 대해 나타내고 싶을 때 간략하게 탭을 한 후에 주석 처리하여 작성한다.

if (a == 2) {return TRUE;            /* special case */
} else {
return isPrime(a);      /* works only for odd a */
}

End-Of-Line Comments

: 일반적으로 사용하는 주석의 형태이다.

if (foo > 1) {// Do a double-flip.
...
}
else {
return false;          // Explain why here.
}
//if (bar > 1) {
//
//    // Do a triple-flip.
//    ...
//}
//else {
//    return false;
//}

Declarations

Number Per Line

int level; // indentation level
int size;  // size of table
/* Or
int level, size;

Do not put different type on the same line!!!!
*/ 

Initialization

: 변수의 초기화는 선언한 메서드 혹은 함수 안에서 바로하는 것이 좋다.

Placement

: 변수의 선언은 코드 블럭의 시작 부분에 삽입한다.

void myMethod() {
    int int1 = 0;         // beginning of method block

    if (condition) {
        int int2 = 0;     // beginning of "if" block
        ...
    }
}
</blockquote>

Try to avoid this form!

int count;
...
myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}

Class and Interface Declarations

: 자바의 클래스 혹은 인터페이스를 만들때, 아래의 룰을 따라서 만든다.

  • No space between a method name and the parenthesis "(" starting its parameter list
  • Open brace "{" appears at the end of the same line as the declaration statement
  • Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{"
class Sample extends Object {
    int ivar1;
    int ivar2;

    Sample(int i, int j) {
        ivar1 = i;
        ivar2 = j;
    }

    int emptyMethod() {}

    ...
}

Naming Conventions

  • 클래스 이름 (Class Names): 클래스 이름은 파스칼 표기법(Pascal Case)을 따릅니다. 각 단어의 첫 글자는 대문자로 시작합니다.
class CarModel;
class EmployeeInfo;
  • 메서드 이름은 카멜 표기법(Camel Case)을 따릅니다.첫 글자는 소문자로 시작하고, 각 단어의 첫 글자는 대문자로 시작합니다.
void calculateTutorial();
String getUserInfo();
  • 변수 이름은 카멜 표기법(Camel Case)을 따릅니다. 첫 글자는 소문자로 시작하고, 각 단어의 첫 글자는 대문자로 시작합니다.
int totalCount;
String firstName;
  • 상수 이름은 대문자와 언더스코어(_)를 사용합니다. 모든 글자는 대문자로 작성합니다.
final int MAX_SIZE = 100;
final double PI_VALUE = 3.14;

💡 final의 뜻은?
변수, 메서드, 클래스 들에 사용되며, 사용된 요소에 대한 변경을 금지하거나, 값이 한 번 할당되면 변경할 수 없음을 나타냅니다. 그리고 코드의 매직넘버(코드안에 하드코딩된 숫자를 의미합니다. 즉, 직접 사용된 숫자를 의미한다.)가 있으면 가독성이 떨어지고, 유지보수의 어려움이 있기 때문에 MAX_SIZE라는 이름으로 선언하여 사용을 한다.

  • 패키지 이름은 모두 소문자로 작성합니다. 계층 구조를 나타내기 위해 도메인 이름을 사용할 수 있습니다.
package com.example.myproject;
  • 인터페이스 이름은 파스칼 표기법(Pascal Case)을 따릅니다.
interface Drawable;
interface Serailizable;
  • 메서드 매개변수는 카멜 표기법(Camel Case)을 따릅니다.
void printDetails(String employeeName, int employeeId);
  • 여러 단어를 포함하는 이름은 각 단어의 첫 글자를 대문자로 작성합니다.
class CustomerOrder;
String processHttpRequest();

🧸 Better statements

if(condition) {
	return x;
}
return y;

보다는 아래와 같이 쓰는게 훨씬 효율적이다.

return (condition ? x : y);

references
1. Gerneral Rules of Makefile
2. Code Convention

profile
백엔드 화이팅 :)

0개의 댓글