What is the code cleanliness that is often said

    Clean Code

    • The price of messy code?

    Subsequent maintenance and modification are difficult, and productivity and time are negatively correlated.

    • What is clean code?

    Clean code only does one thing well: each class, each function, and each module focuses on one thing, completely free from interference and pollution from surrounding details.

    A more comprehensive generalization is: reduce duplication of code, improve expressiveness, and build simple abstractions earlier.

    More specific implementation: please read on!


    Better variable naming

    1. See the name and know the meaning

    2. Abstract factory: Do not name the interface IShapeFactory. The leading letter is actually disturbing to the user. The user only needs to know that it is an abstract factory. It is recommended to use CShapeFactory for a better experience.

    3. Use nouns for class names and verbs for methods. Words such as get and fetch with similar parts of speech should not appear together. You can add suffixes getNumber and fetchData to achieve the same effect

    4. Don’t be afraid of long names: Use descriptive names, even longer ones, than short, confusing ones


    Better function

    1. The structure of the function should be short and short in nature, with the goal of not accommodating if/else if/else nested structure

    2. Only do one thing: As mentioned earlier, it is enough for a function to do one thing well, and the sign is "see if you can also extract a function, which is not just a simple reinterpretation of its implementation"

    3. Each function has an abstraction level: the code is generally "top-down" reading order, and each function should be followed by the function of the next abstraction level
      [Abstract level: getHtml function is at a higher abstraction layer, pagePathName = pathParser.render(pagePath) is at an intermediate abstraction layer, and .append("\n") is at a lower abstraction layer]

    4. Switch statement: It is necessary to do N things naturally, but it can be placed at a lower abstraction level, but when a new type appears, it will violate the "single responsibility principle, open and closed principle". At this time, it is best to create multiple state object

          //In the original text: Each case branch is processed separately, adding new types does not need to modify the original code to add new processing classes
      function getName(name){
           switch(name){
               case 'ming':
                   return new ClassMing(name);
               case 'hu':
                   return new ClassHu(name);
               case 'uzi':
                   return new ClassUzi(name);
               default:
                   throw new ClassCommon(name);
           }
      }
      
      //I prefer to use another method: the modification only needs to be modified in the object, and the simplicity of the function is improved
      const nameCollectionUtils = {
           ming: new ClassMing('ming');
           hu: new ClassHu('hu');
           uzi: new ClassUzi('uzi');
      }
      function getName(name){
           return nameCollectionUtils.hasOwn(name) ? nameCollectionUtils[name] : new ClassCommon(name)
      }
      
    5. There are no more than two function parameters: including input parameters and output parameters

    6. No side effects: Do not make unexpected changes inside the function, and do not affect the outside

    7. Use exceptions instead of returning error codes: use try...catch instead of multi-level if nesting, always walk on the main road, don't think too much about boundaries, so that you can keep your thinking coherent

    8. the error handling is extracted separately: I think this one can be determined according to the situation, after all, the extraction is only for aesthetics

    9. Don’t repeat: the code of the same logic used by multiple functions must be extracted. You can refer to the object-oriented base class. This is also the idea of component-oriented programming and module-oriented programming in front-end development.


    Notes & Formatting

    Everyone has their own habits, just adopt some general guidelines


    Unit Test

    The vast majority of Internet companies today are agile development. Few companies can abide by the test-driven principle, and few technical teams will require unit testing to ensure progress.


    Class

    1. Class organization: in the following order, Do not expose internal attributes, use methods to achieve the same purpose

      class DemoOrganization{
        static sname = 'sname'
        private pname = 'pname'
        private _pname = '_pname'
        protected tname = 'tname'
      
        public getPublicName(){
          return this.pname
        }     
        private _getPrivateName(){
          return this._pname
        }
      }
      
    2. Single Responsibility Principle (SPR): A class or module should have one and only one reason for modification, and classes that implement this principle are more likely to be reused

    3. Maintain cohesion: the variables defined in the class should be used by as many methods as possible, if not, split the functions that use the variables into small classes

    4. Open-Closed Principle (OCP): Classes should be open to extensions and closed to modification. New functions can be added without touching other classes by means of subclassing

    5. Dependency Inversion Principle (DIP): Classes should depend on abstractions rather than on specific details

    6. Decoupling: Do not affect each other between different methods and modules, that is, "divide and conquer" and "break into parts"


    Iterate

    To sum up the above, as long as the following principles are followed, a well-designed iterable program can be obtained:

    • run all tests
    • not repeatable
    • Expresses the programmer's intent
    • Minimize the number of classes and methods as much as possible
    • The above rules are arranged in order of importance


    Refactor

    I think this module is the most important module, even more important than how to write new programs, because the number of deposition projects in a company is huge, and it is likely to refactor several or more of them (or because of the previous The code is too bad to maintain), so the points that need to be paid attention to in refactoring should also have a clear understanding.

    Just follow one rule: Checked-in code is cleaner than checked-out code

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)

    Win10 远程计算机或设备将不接受连接