What Is Clean Code?
Photo by cottonbro studio: https://www.pexels.com/photo/person-wearing-white-pants-and-white-socks-standing-beside-brown-broom-4108715/

What Is Clean Code?

There is not the “ultimate” definition of what clean code really is.

Bjarne Stroustrup (inventor of C++), Dave Thomas (godfather of the Eclipse strategy) and Ward Cunningham (inventor of Wiki) give different definitions:

Best Practices

Some good practices have proven to be very useful and helpful in the past:

  • Javadocs: Brief comment about purpose of a file, @author, @version
  • Boyscout rule: “Leave the campground cleaner than you found it.”
  • Meaningful names - Use intention-Revealing Names: if a name (variable, function, class) requires a comment, then the name does not reveal its intent
  • ?Int d; ? // elapsed time in days
  • ?Int elapsedTimeInDays
  • Avoid Disinformation
  • Naming conventions:

? Use Pronounceable Names

? Use Searchable Names

? Use Descriptive Names

? Avoid Encodings

  • Make Meaningful Distinctions (Example: Product, ProductInfo, ProductData mean all the same)
  • Pick One Word per Concept (Example: It is confusing to have fetch, retrieve and get as equivalent methods of different classes)
  • Avoid copy & paste
  • Keep it small: Avoid long lines (>150 columns), avoid long functions, avoid long class files.

? “Functions should do one thing. They should do it well. They should do it only.”

  • Use comments properly:

? Legal Comments

? Informative comments

? Avoid useless comments

? Don’t comment out old code (history is in git/SVN)

? Add TODOs

? Avoid bad, redundant or misleading comments

  • Avoid mandated comments, such as “Every function must have a Javadoc or every variable must have a comment.”
  • Avoid Mental Mapping

? Single letter names except i, j, k which are traditional

? Clarity is king!

  • Class Names

? Classes and object should have noun or noun phrase names like Customer, WikiPage, Account

  • Method Names

? Should have verb or verb phrase names like postPayment, deleteAccount or save

? Accessors, mutators and predicates should be named for their value and prefixed with get, set, is

String name = employee.getName();

customer.setName(“Tom”);

If (paycheck.isPosted()))…

  • Use Exceptions Not Error Codes
  • Extract Try/Catch bodies out into functions of their own
  • Reading code from top to bottom: We want every function to be followed by those at the next level of abstraction.
  • Define Formatting Team Rules and Conventions

要查看或添加评论,请登录

VOQUZ Group的更多文章

社区洞察

其他会员也浏览了