今日已更新 280 条资讯 | 累计 22470 条内容
关于我们

Write Code You Can Still Read 6 Months Later

Yilong Wu 2026年07月22日 08:38 0 次阅读 来源:Dev.to

I'm AlanWu. I'm in junior high. I've written a lot of bad code. Here's what I changed to make it less bad. 1. Name things like a human // Don't do this int d ; // days? distance? damage? int cnt = 0 ; // "cnt" — you know, the classic vector < int > v ; // v of what // Do this int daysUntilDeadline ; int errorCount = 0 ; vector < int > studentScores ; Full words, no abbreviations. idx instead of i in loops is fine. But sz for size, cnt for count, ptr for pointer — just type the word. You're not being charged by the character. 2. Functions should do one thing If you need the word "and" to describe a function, split it. // Bad: does two things, name lies void loadAndValidateConfig () { readFile (); checkSyntax (); } // Better Config loadConfig ( string path ) { return parseConfig ( readFile ( path )); } bool validateConfig ( const Config & cfg ) { return cfg . width > 0 && cfg . height > 0 ; } My rule of thumb: if a function is longer than what fits on one screen, break it. If I can't describe what it does in one sentence without "and", break it. 3. Comments explain WHY, not WHAT // Bad — tells me what the code already says // Loop through all students for ( auto & s : students ) { s . score += 5 ; } // Good — tells me WHY, which the code can't // Extra credit: 5 points for submitting early for ( auto & s : students ) { s . score += 5 ; } If you're writing a comment that just restates the next line of code, delete it. The only comments worth keeping are the ones that answer "why did I do it this way?" 4. Don't nest too deep // Bad — 3 levels deep, I've already forgotten what the top level was for ( auto & student : students ) { if ( student . hasSubmitted ()) { for ( auto & answer : student . answers ) { if ( answer . isCorrect ()) { score ++ ; } } } } // Better — flatten with early exits for ( auto & student : students ) { if ( ! student . hasSubmitted ()) continue ; for ( auto & answer : student . answers ) { if ( ! answer . isCorrect ()) continue ; score ++ ; } } Al

本文内容来源于互联网,版权归原作者所有
查看原文