草庐IT

源代码之整洁代码

PetterLiu 2023-03-28 原文

源代码之整洁代码

     经常在研发面试中,询问代码质量是什么?能讲出核心点的人并不多,对于你自己代码是否反思过代码质量与意义吗? 有的人写了8年代码,还是没有这个意识,只能说LEVEL还是不够高。 让我们再来回顾下,整洁Clean Code代码

What Is Clean Code?

  • The code can be measured with either "good" or "bad" in the code review or by how many minutes it takes you to talk about it.

  • A clean code should be elegant, efficient, readable, simple, without duplications, and well-written.

  • You should add value to the business with your code.

  • Clean code offers quality and understanding when we open a class.

  • It is necessary that your code is clean and readable for anyone to find and easily understand. Avoid wasting others' time.

Meaningful Names 有意义命名

  • Names of the classes, variables, and methods must be meaningful and clearly indicate what a method does or what an attribute is.

  • Create pronounceable names to facilitate communication.

  • Avoid acronyms and avoid confusing names, which may bring anyone who reads the code to the wrong conclusions.

  • Use names that reflect the system domain, the context, and the problems that must be solved.

Functions 函数

  • The method should be easy to read and understand.

  • The method should convey its intention.

  • The methods should be small. Another rule for small methods is that they should be even lower.

  • They must have up to 20 lines. (I think they should have up to 10 lines.)

  • Methods should only do one thing: they should do it the right way and just do it.

  • You should use names with words that say what it really does.

  • The optimal number of parameters of a method is zero, after one and two.

  • Three should be avoided, but if you think it should be used, have a good justification.

  • Parameters of the Boolean type as a parameter already clearly states that it does more than one thing.

  • Methods must do something and return something.

  • Avoid duplication.

Comments 注释

  • One of the most common reasons for the comments is because the code is bad.

  • If you're thinking about writing a comment, then the code should be refactored.

  • Comments do not save a bad code.

  • Try to explain what the code causes to happen.

  • Comments can be useful when placed in certain places.

  • Create method names and informative variables instead of explaining the code with comments.

  • Comments can be used to express the importance of certain points in the code.

  • The best comment is one that needs to be written because your code already explained.

  • Do not write comments with redundant, useless, or false information.

  • They should not be used to indicate who changed or why, for that already exists in versioning.

  • Don’t comment code that will not be used, remove, it just pollutes the code and leaves no doubt in anyone reading.

Formatting 格式

  • Formatting should indicate things of importance since it is a developer of communication form.

  • A messy code is hard to read.

  • The readability of the code will take effect on all of the changes that will be made.

  • Try to write a class with a maximum of 500 lines. Smaller classes are easier to understand.

  • Set a limit of characters per line of code.

  • A good character limit on a line is 120.

  • Try to keep more next related concepts vertically to create a code stream.

  • Use spaces between operators, parameters, and commas.

Objects and Data Structure 对象与数据结构

  • Follow the Law of Demeter, which says that one M method of an object O can only consume services of the following types of objects:

    • The object itself, O.
    • The M parameters.
    • Any object created or instantiated by M.
    • Direct components of O.
  • Make good abstraction and encapsulation.

  • Do not make dumb objects.

  • Objects hide the data abstraction and expose methods that operate the data.

  • Data structures expose your data and do not have significant methods.

Error Handling 错误处理

  • Error handling should be planned carefully by all programmers.

  • When wrong things occur, we have to get it to do the right things.

  • We should give preference to launching an exception than treating it just to hide.

  • Create messages with information about the error.

  • Mention that it failed. Where was this failure? If possible, mention why it failed.

  • Look at separate business rules for errors and error handling.

  • Avoid returning a NULL in methods, preferably to return an empty object.

  • Avoid passing NULL to the methods; this can generate NullPointerExceptions.

Boundary 边界

 

 

  • In third-party code, to avoid passing objects, APIs look forward in order to keep things in the same class.

  • Performs tests on the API's third party.

  • Study the documentation and test the third API before you start using it.

  • Check well the features you will use.

  • These steps can help increase yield when there are new updates to the API and you can only run your tests to check for this update.

  • Create tests the functionality of the API.

Unit Tests 单元测试

  • Make sure each piece of code is doing what you expect it to do.

  • Follow the TDDs law:

    • Don't create code before you have a failing test.
    • Don't create more tests than necessary to fail. 
    • You cannot write more code than enough to pass the test that is failing.
  • Keep your test clean.

  • The tests must undergo changes in the same way that the code.

  • The dirtier the code, the more difficult test will be to maintain.

  • Use the F.I.R.S.T rule for testing:

    • The test is fast-running.
    • The tests are independent of other.
    • The test is repeatable in various environments.
    • The test is self-validating.
    • The test is timely.
  • The test is as important as the production code.

Classes 类

  • By default, Java classes should start with the variables:

    • Static and constantly public.
    • Static and variable private.
    • Instances and variables privates.
    • Soon after comes the functions.
  • The class name should represent your responsibility.

  • The class must have only one responsibility.

  • To know the size of the class is ideal or we should not measure her responsibility.

  • You should try to make a brief description of the class.

  • The methods should be:

    • Small...
    • ...and even lower.
    • They must have only one responsibility.

Systems 系统

  • It is important to recognize and separate responsibilities of a system.

  • It should be separate and modularize the logic execution, allowing an independent strategy for solving application dependency.

  • Is important to take care of dependency injections and to allow only objects to take care of the business of logic.

  • It is very difficult to create a system properly first. It must be made available to the story, then refactored, and then expanded to continue implementing new stories.

  • To get to the point that TDD is necessary, you need refactoring and clean code.

  • We must build POJOs-based logic through testing and evolve from simple to interconnect the various aspects necessary.

Emergence

Here are the rules that are given by Kent Beck to create good designs:

  • Run all tests. They verify that the system behaves as expected.
  • Eliminate duplication because duplicate code brings additional work.
  • To express the intention of the programmer, use more expressive code to facilitate maintenance. Choose good names for functions, classes and tests shouldn’t be small and well written. 
  • Minimize the number of classes and methods. Following this pattern can ignore it if the classes are very small.
  • Apply all knowledge to improve the design during refactoring. Increase cohesion, reduce coupling, separate responsibilities, reduce classes and methods, choose the best names.

Even applying it once, you will not be able to have good software. You need to do this over and over again to achieve continuous improvement.

Concurrence 并发

  • The concurrency is an aspect that may be present in the codes.

  • Uncoupling allows for improving the yield and structure of an application.

  • The concurrency can improve response times and application efficiency.

  • You should consider the following ideas about the concurrence:

    • It injects a certain overload.
    • It can be complex to operate.
    • Errors caused by it can be difficult to reproduce.
    • It usually requires design changes.
  • The concurrence problem is that different segments of an application may be following tangled multi-threading, which can cause unexpected problems in normal situations.

  • For concurrence reasons, it is important that each class has a unique responsibility.

  • Create sections that are synchronized and minimized. Running tests often is the best way to find any errors in the code. However, it is difficult to do when there are concurrence tests.

  • A good way to test is to insert codes for testing in the middle of the implemented code.

Successive Refinement 精益求精

  • The code-only work is not enough to have a good code.

  • Professionals who care only about the code that works cannot be considered professional.

  • We should ignore that we have no time to refactor to one code. The code that was not taken care of today can become a problem after becoming a problem for the team because no one will want to mess with it.

  • Try not to let the code rot. It is much cheaper to create a clean code than cleaning a rotten code, as a move in a tangle can be an arduous task.

  • The solution, then, comes down to maintaining the cleanest code possible and as simply as possible without ever letting it begin to rot.

JUnit

  • Look to cover tests each (not every method, but each code line).

  • No code is immune to improvement, and each of us has a responsibility to make the code a little better than we found it.

  • Refactoring is an iterative process full of trial and error, inevitably converging to something that we feel is worthy of a professional.

Refactoring 重构

 

 

  • Before making any kind of refactoring, it is important to have good coverage tests.

  • After increasing or creating test coverage, you can begin to leave the clearest code and fix some bugs.

  • Now, after leaving the code clearer, someone else can probably clean it even more.

Java

  • Avoid long lists of import using *.
  • Do not inherit constants. Instead, use enums constants.

Names 命名

  • Choose descriptive names.
  • Choose names at the appropriate level of abstraction.
  • Use standard nomenclature where possible.
  • Use long names for long scopes.
  • Avoid encodings.
  • Names should describe side effects.

 

结论
       整洁代码不是遵循一组规则编写的。您不能仅通过学习所做的工作清单就成为软件专业人员。专业精神和工匠精神来自价值和纪律,在构建代码时遵循价值和纪律,来判断应该做和不应该做的事情。

有关源代码之整洁代码的更多相关文章

  1. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  2. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  3. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

  4. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  5. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  6. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  7. 程序员如何提高代码能力? - 2

    前言作为一名程序员,自己的本质工作就是做程序开发,那么程序开发的时候最直接的体现就是代码,检验一个程序员技术水平的一个核心环节就是开发时候的代码能力。众所周知,程序开发的水平提升是一个循序渐进的过程,每一位程序员都是从“菜鸟”变成“大神”的,所以程序员在程序开发过程中的代码能力也是根据平时开发中的业务实践来积累和提升的。提高代码能力核心要素程序员要想提高自身代码能力,尤其是新晋程序员的代码能力有很大的提升空间的时候,需要针对性的去提高自己的代码能力。提高代码能力其实有几个比较关键的点,只要把握住这些方面,就能很好的、快速的提高自己的一部分代码能力。1、多去阅读开源项目,如有机会可以亲自参与开源

  8. 7个大一C语言必学的程序 / C语言经典代码大全 - 2

    嗨~大家好,这里是可莉!今天给大家带来的是7个C语言的经典基础代码~那一起往下看下去把【程序一】打印100到200之间的素数#includeintmain(){ inti; for(i=100;i 【程序二】输出乘法口诀表#includeintmain(){inti;for(i=1;i 【程序三】判断1000年---2000年之间的闰年#includeintmain(){intyear;for(year=1000;year 【程序四】给定两个整形变量的值,将两个值的内容进行交换。这里提供两种方法来进行交换,第一种为创建临时变量来进行交换,第二种是不创建临时变量而直接进行交换。1.创建临时变量来

  9. git使用常见问题(提交代码,合并冲突) - 2

    文章目录git常用命令(简介,详细参数往下看)Git提交代码步骤gitpullgitstatusgitaddgitcommitgitpushgit代码冲突合并问题方法一:放弃本地代码方法二:合并代码常用命令以及详细参数gitadd将文件添加到仓库:gitdiff比较文件异同gitlog查看历史记录gitreset代码回滚版本库相关操作远程仓库相关操作分支相关操作创建分支查看分支:gitbranch合并分支:gitmerge删除分支:gitbranch-ddev查看分支合并图:gitlog–graph–pretty=oneline–abbrev-commit撤消某次提交git用户名密码相关配置g

  10. ruby - 这两段代码有什么区别? - 2

    打印1:defsum(i)i=i+[2]end$x=[1]sum($x)print$x打印12:defsum(i)i.push(2)end$x=[1]sum($x)print$x后者是修改全局变量$x。为什么它在第二个例子中被修改而不是在第一个例子中?类Array的任何方法(不仅是push)都会发生这种情况吗? 最佳答案 变量范围在这里无关紧要。在第一段代码中,您仅使用赋值运算符=为变量i赋值,而在第二段代码中,您正在修改$x(也称为i)使用破坏性方法push。赋值从不修改任何对象。它只是提供一个名称来引用一个对象。方法要么是破坏性

随机推荐