代码之美:聊聊代码整洁之道
2.1 什么是整洁代码?
2.2 概念对比
2.3 如何实现整洁代码?
命名基本规则
命名变量
函数命名
类命名
命名大忌
代码的变量、函数、类的命名有几大忌讳:
function renderContent(renderInformation) {const element = renderInformation.element;if (element === 'script' || element === 'SCRIPT') {throw new Error('Invalid element.');}let partialOpeningTag = '<' + element;const attributes = renderInformation.attributes;for (const attribute of attributes) {partialOpeningTag =partialOpeningTag + ' ' + attribute.name + '="' + attribute.value + '"';}const openingTag = partialOpeningTag + '>';const closingTag = '</' + element + '>';const content = renderInformation.content;const template = openingTag + content + closingTag;const rootElement = renderInformation.root;rootElement.innerHTML = template;}
function renderContent(renderInformation) {const element = renderInformation.element;const rootElement = renderInformation.root;validateElementType(element);const content = createRenderableContent(renderInformation);renderOnRoot(rootElement, content);}
function saveUser(email, password) {const user = {id: Math.random().toString(),email: email,password: password};db.insert('users', user);}saveUser('[email protected]', 'test-pass');
class User {constructor(email, password) {this.email = email;this.password = password;this.id = Math.random().toString();}save() {db.insert('users', this);}}const user = new User('[email protected]', 'test-pass');user.save();
void processTransactions(List<Transaction> transactions) {if (transactions && transactions.length > 0) {for (Transaction transaction: transactions) {if ("PAYMENT".equals(transaction.type)) {if ("OPEN".equals(transaction.status)) {if ("CREDIT_CARD".equals(transaction.method)) {processCreditCardPayment(transaction);} else if ("PAYPAL".equals(transaction.method)) {processPayPalPayment(transaction);} else if ("ALIPAY".equals(transaction.method)) {processAliPayPayment(transaction);}} else {console.log("Invalid transaction status!");}} else if ("REFUND".equals(transaction.type)) {if ("OPEN".equals(transaction.status)) {if ("CREDIT_CARD".equals(transaction.method)) {processCreditCardRefund(transaction);} else if ("PAYPAL".equals(transaction.method)) {processPayPalRefund(transaction);} else if ("ALIPAY".equals(transaction.method)) {processAliPayRefund(transaction);}} else {console.log("Invalid transaction status!");}}}}}
void processTransactions(List<Transaction> transactions) {if (isEmpty(transactions)) {showErrorMessage("No transactions provided!");return;}for (Transaction transaction: transactions) {processTransaction(transaction);}}void processTransaction(Transaction transaction) {if (!isOpen(transaction)) {showErrorMessage("Invalid transaction status!");return;}if (isPayment(transaction)) {processPayment(transaction);} else if (isRefund(transaction)) {processRefund(transaction);} else {showErrorMessage("Invalid transaction method!");}}boolean isEmpty(List<Transaction> transactions) {return transactions == null || transactions.length == 0;}boolean isOpen(Transaction transaction) {return "OPEN".equals(transaction.status);}boolean isPayment(Transaction transaction) {return "PAYMENT".equals(transaction.type);}boolean isRefund(Transaction transaction) {return "REFUND".equals(transaction.type);}
main() {List<Transaction> transactions = [...];try {processTransactions(transactions);} catch (Exception e) {showErrorMessage(e.message);}}void processTransactions(List<Transaction> transactions) {validateTransactions(transactions);for (Transaction transaction: transactions) {processTransaction(transaction);}}void validateTransactions(List<Transaction> transactions) {if (isEmpty(transactions)) {throw new TransactionException("No transactions provided!");}}void processTransaction(Transaction transaction) {try {validateTransaction(transaction);if (isPayment(transaction)) {processPayment(transaction);} else if (isRefund(transaction)) {processRefund(transaction);}} catch(Exception e) {showErrorMessage(e.message);}}void validateTransaction(Transaction transaction) {if (!isOpen(transaction)) {throw new TransactionException("Invalid transaction status!");}if (!isPayment(transaction) && !isRefund(transaction)) {throw new TransactionException("Invalid transaction method!");}}
class Database {private String uri;private Provider provider;private Connection connection;void connect() {try {connection = provider.establishConnection(uri);} catch (Exception e) {log.error("Failed to connect!");}}void disconnect() {connect.close();}void storeData(Data data) {...}}const Database db = new Database("mysql-db:8100", sqlEngine);db.connect();db.storeData(data);db.disconnect();
class Database {private String uri;private Provider provider;public Connection connection; // 设置为public}const Database db = new Database("mysql-db:8100", sqlEngine);db.connect();db.connection.close(); // 违反原则
public ServiceResponse<List<List<Long>>> batchQueryBelongedIdsFromGivenCrowdIds(QueryCrowdIdsBatchReqDTO batchReqDTO) {...List<List<Long>> result = Lists.newArrayList();CallerInfo callerInfo = UmpUtil.methodReg("bmallCrowdPinQueryProvider.batchQueryBelongedIdsFromGivenCrowdIds", batchReqDTO.getForcebot());try {PipelineClient pipeline = bmallCrowdJimdb.pipelineClient();Map<String, JimFuture<Set<String>>> jimFutureMap = Maps.newHashMap();List<String> jimdbKeyList = Lists.newArrayList();Map<String, List<Long>> jimdbKeyCrowdIdListMap = Maps.newHashMap();String bmallUseOriginalPin = labelDuccManager.getAvailConfigStr("bmallUseOriginalPin");for (int index = 0; index < batchReqDTO.getBatchReq().size(); ++index) {QueryCrowdIdsReqDTO queryCrowdIdsReqDTO = batchReqDTO.getBatchReq().get(index);String fieldVersion = dorisExecuteComponent.getBmallFieldJimdbValidVersion(queryCrowdIdsReqDTO.getFieldId());String jimdbKey = String.format(virtualBpinJimdbKeyFormat, queryCrowdIdsReqDTO.getFieldId(), queryCrowdIdsReqDTO.getCrid(),(queryCrowdIdsReqDTO.getFieldId().equals(LabelConstants.BMallPlatformFieldId) ? queryCrowdIdsReqDTO.getIndustryId() : ""),(StringUtils.isNotBlank(bmallUseOriginalPin) && bmallUseOriginalPin.equals("true")) ? queryCrowdIdsReqDTO.getPin().trim() : queryCrowdIdsReqDTO.getPin().trim().toLowerCase(),queryCrowdIdsReqDTO.getSceneId(), fieldVersion, envAlias);Long maxCrowdId = 0L;Long minCrowdId = Long.MAX_VALUE;for (Long crowdId : queryCrowdIdsReqDTO.getCrowdIds()) {...}jimdbKeyList.add(index + "_" + jimdbKey);jimdbKeyCrowdIdListMap.put((index + "_" + jimdbKey), queryCrowdIdsReqDTO.getCrowdIds());JimFuture<Set<String>> jimFuture = pipeline.zRangeByScore(jimdbKey, minCrowdId, maxCrowdId);jimFutureMap.put((index + "_" + jimdbKey), jimFuture);}// 执行管道中的命令pipeline.flush();for (String jimdbKey : jimdbKeyList) {...}return ServiceResponse.ok(result);} catch (Exception e) {...} finally {...}}
你可能还想看👇
- END -
👇点关注,不迷路👇