
배열의 인덱스 [0], [1], [2]를 직접 사용하면 코드의 가독성이 떨어진다. 코드를 봤을 때 [0], [1], [2]에 뭐가 들어있는지 예상이 되지 않기 때문이다.
// ❌ 숫자 인덱스만으로는 무엇을 가리키는지 알기 어려움
function operateTime(inputs, operators, is) {
inputs[0].split('').forEach((num) => { // inputs[0]이 뭘 의미하는거지?
cy.get('.digit').contains(num).click();
});
inputs[1].split('').forEach((num) => { // inputs[1]은 또 뭐지?
cy.get('.digit').contains(num).click();
});
}
가장 간단한 방법은 배열을 의미 있는 변수명으로 구조 분해하는 것이다.
// ✅ 변수명으로 의미를 명확하게 표현
function operateTime(inputs, operators, is) {
// firstInput, secondInput이라는 이름으로 의도가 명확해짐
const [firstInput, secondInput] = inputs;
firstInput.split('').forEach((num) => {
cy.get('.digit').contains(num).click();
});
secondInput.split('').forEach((num) => {
cy.get('.digit').contains(num).click();
});
}
한 단계 더 나아가서, 함수의 매개변수에서 직접 구조 분해할 수 있다.
// ✅ 더 간결하게 함수 파라미터에서 바로 분해
function operateTime([firstInput, secondInput], operators, is) {
// 함수를 사용하는 사람도 매개변수를 보고 배열의 구조를 바로 이해할 수 있음
firstInput.split('').forEach((num) => {
cy.get('.digit').contains(num).click();
});
secondInput.split('').forEach((num) => {
cy.get('.digit').contains(num).click();
});
}
// ❌ 인덱스로 접근하면 각 버튼의 역할을 알기 어려움
function clickGroupButton() {
const confirmButton = document.getElementsByTagName('button')[0];
const cancelButton = document.getElementsByTagName('button')[1];
const resetButton = document.getElementsByTagName('button')[2];
}
// ✅ 구조 분해 할당으로 한눈에 버튼의 역할을 파악할 수 있음
function clickGroupButton() {
const [confirmButton, cancelButton, resetButton] =
document.getElementsByTagName('button');
}
// ❌ 인덱스 접근은 split의 결과를 예상하기 어렵게 만듦
function formatDate(targetDate) {
const date = targetDate.toISOString().split('T')[0]; // [0]이 날짜부분이라는걸 어떻게 알죠?
const [year, month, day] = date.split('-');
return `${year}년 ${month}월 ${day}일`;
}
// ✅ 구조 분해 할당으로 개선
function formatDate(targetDate) {
const [date] = targetDate.toISOString().split('T'); // date만 필요하다는게 명확함
const [year, month, day] = date.split('-');
return `${year}년 ${month}월 ${day}일`;
}
// ✅✅ 유틸리티 함수로 더 명확하게
function head(arr) {
return arr[0] ?? ''; // 배열의 첫 요소를 가져오는 용도임을 함수 이름으로 표현
}
function formatDate(targetDate) {
const date = head(targetDate.toISOString().split('T')); // 첫 요소(날짜)만 필요하다는게 더 명확해짐
const [year, month, day] = date.split('-');
return `${year}년 ${month}월 ${day}일`;
}
[0], [1] 등을 직접 사용하면 코드의 의도를 파악하기 어렵다