首页 全栈 正文
  • 本文约1367字,阅读需7分钟
  • 12
  • 0

项目小驼峰式变量命名建议,按功能分类整理

摘要

JavaScript和Java的小驼峰式变量命名建议,按功能分类整理 一、判断类(Boolean) // 状态判断 let isLoggedIn = false; let hasPermission = true; let isValidToken = checkToken(); let shouldRefresh = autoRefreshEnabled;...

JavaScript和Java的小驼峰式变量命名建议,按功能分类整理

一、判断类(Boolean)

// 状态判断
let isLoggedIn = false;
let hasPermission = true;
let isValidToken = checkToken();
let shouldRefresh = autoRefreshEnabled;

// 条件判断
let isProductionEnv = process.env.NODE_ENV === 'production';
let supportsWebp = document.createElement('canvas').toDataURL('image/webp').startsWith('data:image/webp');
let isEmptyResult = (response.data.length === 0);

二、验证类

// 输入验证
let validEmailFormat = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
let passwordStrength = zxcvbn(password).score;
let captchaMatched = (userInput === generatedCaptcha);

// 数据校验
let schemaValid = ajv.validate(schema, data);
let signatureVerified = verifySignature(data, signature);

三、查找类

// 搜索相关
let searchResults = await fetchSearchResults(query);
let lookupCache = new Map();
let findIndex = array.findIndex(item => item.id === targetId);

// 路径相关
let currentRoute = useRoute();
let elementSelector = '#mainContent';
let apiEndpoint = '/api/v2/users';

四、状态管理类

// 加载状态
let isLoading = true;
let loadingProgress = 0.65;
let abortController = new AbortController();

// 交互状态
let hoverState = 'hover';
let expandedSections = new Set(['section1']);
let activeTabIndex = 0;

五、数据存储类

// 缓存相关
let tempCache = new Map();
let persistentData = loadFromLocalStorage();
let storageKey = 'user_preferences';

// 集合操作
let filteredList = originalList.filter(item => item.active);
let groupedItems = _.groupBy(items, 'category');
let paginatedData = paginate(data, currentPage, pageSize);

六、循环计数类

// 遍历控制
for (let currentIndex = 0; currentIndex < totalItems; currentIndex++) {
  // ...
}

// 分页控制
let currentPage = 1;
const itemsPerPage = 10;
const totalPages = Math.ceil(totalItems / itemsPerPage);

七、配置类

// API配置
const apiBaseUrl = 'https://api.example.com';
const requestTimeout = 5000;
const defaultHeaders = { 'Content-Type': 'application/json' };

// 界面配置
let themeMode = 'dark';
let animationSpeed = 0.3;

八、错误处理类

// 错误标识
let validationError = null;
let networkErrorCode = 500;
let retryCount = 0;

// 异常捕获
try {
  riskyOperation();
} catch (error) {
  let lastError = error;
  let errorStack = error.stack;
}

九、日志相关变量

// 调试信息
let debugModeEnabled = false;
let perfLogEntries = [];
let lastErrorTime = Date.now();

// 审计日志
let accessLog = [];
let auditTrail = {
  user: 'admin',
  action: 'DELETE',
  timestamp: 1620000000000
};

十、用户相关变量

// 用户状态
let currentUserId = null;
let sessionToken = getCookie('session_token');
let lastActiveTime = new Date().getTime();

// 权限系统
let userRoles = ['admin', 'editor'];
let featureFlags = {
  newDashboard: false,
  betaFeatures: true
};

命名规范强化建议:

  1. 动词优先:布尔值使用is/has/should开头(isValid优于validFlag)
  2. 名词精准:集合类型用复数(userList优于users)
  3. 异步操作:正在进行的操作加ing后缀(fetchingData优于isFetching)
  4. 常量命名:全大写+下划线(MAX_RETRIES,但JS中通常用const MAX_RETRIES = 5)
  5. 类型标识:复杂类型可加类型后缀(userList: User[],configMap: Map<string, any>)
  6. 这些命名遵循Airbnb JavaScript Style Guide和Google Java Style Guide,适用于React/Vue前端和Spring Boot后端开发,保持前后端命名风格统一。
收藏

扫描二维码,在手机上阅读
    评论
    友情链接