2025년 12월 31일 수요일
Conner Ardman는 하기와 같이 10가지 본인의 Clean Code 원칙이 있다고 말합니다.
본 포스팅은 첨부영상의 요약입니다.
조건분의 순번을 조절하여 불필요한 nesting을 피합니다.
function processUser(user) {
if (user !== null) {
if (user.hasSubscription) {
if (user.page >= 18) {
showFullVersion();
} else {
showChildrenVersion();
}
} else {
throw new Error("User needs a subscription");
}
} else {
throw new Error("No user found");
}
}
function processUser(user) {
if (user === null) {
throw new Error("No user found");
}
if (!user.hasSubscription) {
throw new Error("User needs a subscription");
}
if (user.age < 18) {
return showChildrenVersion();
}
showFullVersion();
}
변수나 함수에 의미를 알기쉬운 이름을 붙입니다.
const MIN_PASSWORD = 6;
function checkPasswordLength(password) {
return password.length >= MIN_PASSWORD;
}
const MIN_PASSWORD_LENGTH = 6;
function isPasswordLongEnough(password) {
return password.length >= MIN_PASSWORD_LENGTH;
}
정말로 필요한 때만 주석을 남깁니다.
// Function to check if a number is prime
function isPrime(number) {
//Check if number is less than 2
if (number < 2) {
// If less than 2, not a prime number
return false;
}
// At lest 1 divisor must but less than square root, so we can stop there
for (let i = 2; i <= Math.sqrt(number); i++) {
// Check if number is divisible by i
if (number % i === 0) {
// If divisible, number is not prime
return false;
}
}
// After all checks, if not divisible by any i, number is prime
return true;
}
function isPrime(number) {
if (number < 2) {
return false;
}
// At lest 1 divisor must but less than square root, so we can stop there
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
text concatenation과 template literal과 같은 formatting을 유지합니다.
const name = "Dug";
const age = 26;
function getUserInfo() {
console.log("User Info:");
console.log("Name:" + name);
console.log(`Age: ${age}`);
}
const name = "Dug";
const age = 26;
function getUserInfo() {
console.log("User Info:");
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
}
불필요하게 코드를 반복적으로 사용하지않습니다.
function logLogin() {
console.log(`User logged in at ${new Date()}`);
}
function logLogout() {
console.log(`User logged in at ${new Date()}`);
}
function logSignup() {
console.log(`User signed up at ${new Date()}`);
}
function logAction(action) {
console.log(`User ${action} at ${new Date()}`);
}
조건분을 빠르게 실패시켜 불필요한 코드가 실행되는 것을 피합니다.
function getUppercaseInput(input) {
const result = input?.toUpperCase?.();
if (typeof input !== "string" || input.trim() === "") {
throw new Error("Invalid input");
}
return result;
}
function getUppercaseInput(input) {
if (typeof input !== "string" || input.trim() === "") {
throw new Error("Invalid input");
}
return input.toUpperCase();
}
변수의 의미와 필요성을 명확히합니다.
let price = 10;
if (transactionType === 1) {
price *= 1.1;
}
const TAXABLE_TRANSACTION_TYPE = 1;
const TAX_MULTIPLE = 1.1;
let price = 10;
if (transactionType === TAXABLE_TRANSACTION_TYPE) {
price *= TAX_MULTIPLE;
}
버그를 예방하기 위해 global변수를 조작하는 것 보다 local변수를 조작합니다.
let area = 0;
function calculateAndUpdateArea(radius) {
const newArea = Math.PI * radius * radius;
area = newArea;
return newArea;
}
let area = 0;
function calculateArea(radius) {
return (newArea = Math.PI * radius * radius);
}
area = calculateArea(5);
코드를 읽기좋도록 합니다.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = numbers.reduce((acc, n) => (n & 1 ? [...acc, n * n] : acc), []);
console.log(result);
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredAndSquared = numbers.filter((n) => n % 2 !== 0).map((n) => n * n);
console.log(filteredAndSquared);
좋은 코드를 작성하기 위해, 최적화 이외의 요소도 고려합니다.
const arr = [4, 2, 2, 8, 3, 3, 1];
function countingSort(arr, min, max) {
let count = new Array(max - min + 1).fill(0);
arr.forEach((element) => {
count[element - min]++;
});
let index = 0;
for (let i = min; i <= max; i++) {
while (count[i - mix] > 0) {
while (count[i - mix] > 0) {
arr[index++] = i;
count[i - min]--;
}
}
}
return arr;
}
console.log(countingSort(arr, 1, 8));
const arr = [4, 2, 2, 8, 3, 3, 1];
const sorted = arr.slice().sort((a, b) => a - b);
console.log(sorted);