>웹 프론트엔드 >JS 튜토리얼 >변수 및 폴더 이름 지정 규칙은 무엇입니까?

변수 및 폴더 이름 지정 규칙은 무엇입니까?

王林
王林원래의
2024-08-13 14:30:40821검색

What are the rules for naming variables and folders?

프로젝트의 변수 및 폴더 이름 지정은 코드의 가독성과 질서를 유지하는 데 매우 중요합니다. 다음은 몇 가지 일반적인 명명 규칙 및 규칙입니다.

변수 명명

  1. camelCase 사용: 변수, 함수, props 이름 또는 상태 변수의 경우 다음과 같습니다.

    • 사용자 이름
    • 로그인됨
    • 핸들클릭
  2. 명확하게 이름 지정: 변수 이름은 해당 기능이나 포함된 정보에 대해 명확해야 합니다. 예를 들면 다음과 같습니다.

    • cartItems(카트에 있는 항목)
    • authToken(인증 토큰용)
  3. 데이터 유형에 설명이 포함된 이름을 사용하세요: 동일한 변수에 여러 데이터 유형이 있는 경우, 예:

    • userAge(사용자에 대한 변수가 여러 개인 경우)
    • 상품가격
  4. 약어 사용 금지: 명확성을 위해 전체 이름을 사용합니다. 예:

    • usrProf 대신 userProfile을 사용하세요.

폴더 이름 지정

  1. kebab-case 또는 snake_case를 사용하세요. 폴더 이름은 다음과 같습니다. 예:

    • 사용자 프로필(kebab-case)
    • user_profile(스네이크_케이스)
  2. 설명적으로 이름 지정: 폴더 이름은 폴더의 내용이나 기능을 반영해야 합니다. 예:

    • 구성 요소/(React 구성 요소 저장용)
    • services/ (서비스 기능 또는 API 저장용)
    • 후크/(맞춤형 후크 저장용)
  3. 일관된 형식 사용: 프로젝트 전체에서 일관된 명명 형식을 유지합니다. 다음과 같은 주문:

    • 케밥케이스를 폴더로 사용하는 경우 모든 폴더에 동일한 형식을 사용하세요
  4. 일반적이거나 모호한 이름은 피하세요: 다음과 같이 폴더의 내용이나 기능을 반영하는 이름을 사용하세요.

    • misc/ 대신 utils/ 사용
    • data/ 대신 store/ 사용

폴더:

src/
├── components/
│   ├── Button.tsx
│   └── Header.tsx
├── hooks/
│   └── useFetch.ts
├── services/
│   └── apiService.ts
├── stores/
│   ├── auth/
│   │   ├── useAuthStore.ts
│   │   └── authTypes.ts
│   ├── user/
│   │   ├── useUserStore.ts
│   │   └── userTypes.ts
│   ├── product/
│   │   ├── useProductStore.ts
│   │   └── productTypes.ts
│   └── cart/
│       ├── useCartStore.ts
│       └── cartTypes.ts
└── index.ts

변수:

// ตัวอย่างใน useAuthStore.ts
interface AuthState {
  isAuthenticated: boolean;
  user: string | null;
  login: (username: string) => void;
  logout: () => void;
}

// ตัวอย่างใน useUserStore.ts
interface UserState {
  name: string;
  email: string;
  updateUser: (name: string, email: string) => void;
}

좋은 명명 규칙을 사용하면 코드가 체계적으로 보이고 이해하기 쉬워집니다.

다음과 같은 구성 값 또는 상수 이름 지정 DATABASE_CONFIG 목표를 쉽게 이해하고 달성할 수 있도록 원칙을 따라야 합니다. 구성 이름 지정 규칙은 다음과 같습니다.

กฎในการตั้งชื่อค่าคอนฟิก

  1. ใช้รูปแบบ UPPER_SNAKE_CASE: ชื่อของค่าคอนฟิกหรือค่าคงที่ควรใช้รูปแบบ UPPER_SNAKE_CASE เพื่อแสดงให้เห็นว่านี่คือค่าคงที่และไม่ควรถูกเปลี่ยนแปลง เช่น:

    • DATABASE_CONFIG
    • API_ENDPOINT
    • MAX_RETRY_ATTEMPTS
  2. สื่อความหมายได้ชัดเจน: ชื่อของค่าคอนฟิกควรบ่งบอกถึงการใช้งานหรือวัตถุประสงค์ของมัน เช่น:

    • DATABASE_HOST (สำหรับโฮสต์ของฐานข้อมูล)
    • CACHE_EXPIRATION_TIME (สำหรับเวลาหมดอายุของแคช)
  3. รวมคอนเท็กซ์และการใช้งาน: ค่าคอนฟิกควรมีชื่อที่รวมคอนเท็กซ์หรือการใช้งานเพื่อให้เข้าใจได้ง่าย เช่น:

    • EMAIL_SERVICE_API_KEY (สำหรับคีย์ API ของบริการอีเมล)
    • JWT_SECRET_KEY (สำหรับคีย์ลับของ JSON Web Token)
  4. หลีกเลี่ยงการใช้ชื่อที่คลุมเครือ: ชื่อของค่าคอนฟิกควรเฉพาะเจาะจงและไม่ควรใช้ชื่อที่คลุมเครือหรือทั่วไปเกินไป เช่น:

    • ใช้ DATABASE_PORT แทน PORT
    • ใช้ SESSION_TIMEOUT แทน TIMEOUT
  5. ใช้คำที่สื่อถึงประเภทของค่า: ชื่อค่าคอนฟิกควรสื่อถึงประเภทของค่า เช่น ค่าเชิงตัวเลข, สตริง, หรือ Boolean เป็นต้น เช่น:

    • MAX_CONNECTIONS (ค่าตัวเลขสูงสุดของการเชื่อมต่อ)
    • ENABLE_LOGGING (ค่า Boolean สำหรับเปิดหรือปิดการบันทึก)

ตัวอย่างการตั้งชื่อค่าคอนฟิก

ไฟล์คอนฟิก

// ตัวอย่างในไฟล์ config.ts

export const DATABASE_CONFIG = {
  HOST: 'localhost',
  PORT: 5432,
  USER: 'dbuser',
  PASSWORD: 'password',
  DATABASE_NAME: 'mydatabase'
};

export const API_CONFIG = {
  BASE_URL: 'https://api.example.com',
  TIMEOUT: 5000, // Timeout in milliseconds
  API_KEY: 'your-api-key-here'
};

export const APP_SETTINGS = {
  MAX_RETRY_ATTEMPTS: 3,
  SESSION_TIMEOUT: 3600, // Timeout in seconds
  ENABLE_LOGGING: true
};

การใช้ค่าคอนฟิกในโค้ด

import { DATABASE_CONFIG, API_CONFIG, APP_SETTINGS } from './config';

// การใช้ค่าคอนฟิกในการเชื่อมต่อฐานข้อมูล
const dbConnection = connectToDatabase({
  host: DATABASE_CONFIG.HOST,
  port: DATABASE_CONFIG.PORT,
  user: DATABASE_CONFIG.USER,
  password: DATABASE_CONFIG.PASSWORD,
  database: DATABASE_CONFIG.DATABASE_NAME
});

// การใช้ค่าคอนฟิกสำหรับ API
const fetchData = async () => {
  try {
    const response = await fetch(API_CONFIG.BASE_URL + '/data', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${API_CONFIG.API_KEY}`
      },
      timeout: API_CONFIG.TIMEOUT
    });
    const data = await response.json();
    return data;
  } catch (error) {
    if (APP_SETTINGS.ENABLE_LOGGING) {
      console.error('Error fetching data:', error);
    }
    throw error;
  }
};

การใช้หลักการเหล่านี้จะช่วยให้คุณตั้งชื่อค่าคอนฟิกอย่างมีระเบียบและเข้าใจง่ายครับ

위 내용은 변수 및 폴더 이름 지정 규칙은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.