Andreas Heger
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Clean Code Best Practices ## Definition **Clean code is code that is easy to understand and easy to change.** It is easy to understand the execution flow of the entire application. It is easy to understand how the different objects collaborate with each other. It is easy to understand the role and responsibility of each class. It is easy to understand what each method does. It is easy to understand what is the purpose of each expression and variable. ## Motivation Clean code enables us to keep our software products adaptable and maintainable. It allows us to make changes with confidence and estimate the impact of these changes. Clean code makes us a reliable and trustworthy partner for our stakeholders. ## Guide Lines ### Boy Scout Rule > Leave the campground cleaner than you found it ### Write code for humans Your code is directed at your future self and your co-workers, not the machine. ### K.I.S.S. - Keep it simple stupid A simpler solution is better than a complex one because simple solutions are easier to maintain. This includes increased readability, understandability, and changeability. Furthermore writing simple code is less error prone. ### Y.A.G.N.I - You ain't gonna need it When faced with a decision what to implement, implement only the features that are necessary at the moment. Features which are regarded as useful but don't seem necessary at the moment are better left for the time when they are deemed necessary. That way the necessary features will be developed faster. In addition no time will be lost on creating and maintaining features that never become necessary. ### Avoid premature optimization The performance of readable and maintainable code will be sufficient most of the time. Optimizations that harm the readability should only be made after severe bottlenecks have been doubtlessly identified and been considered mission critical. ### The Great Refactoring in the Sky If you find yourself thinking: 'We can clean that up later' - Try to replace the word 'later' with 'never'. The reality of software development is that tasks move out of focus quickly and this clean up work gets forgotten or overruled by new interests. Most of the time if you do not clean it up now it will never be cleaned. ### Naming > Say what you mean. Mean what you say. #### Use meaningful and pronouncable names This makes the code searchable and reveals its intend. Pronouncable names are easier for the human mind to process and facilitate collaboration when referencing these names. Meaningful names are more valuable than a few saved keystrokes. ``` // DON'T let d; const ages = arr.map((i) => i.age); // DO let daysSinceModification; const agesOfUsers = users.map((user) => user.age); ``` #### Use the same vocabulary for the same context ``` // DON'T getUserInfo(); getClientData(); getCustomerRecord(); // DO getUser(); ``` #### Avoid unneeded context ``` // DON'T const car = { carColor: 'red', startCar() {}, }; throw new AccessViolationException; // DO const car = { color: 'red', start() {}, }; throw new AccessViolation; ``` #### Avoid disinformation ``` // DON'T // the getUser() function will actually create new entities function getUser(id) { const user = userRepository.get(id); if (!user) { user = userRepository.create(id); } return user; } // DO // the function name makes it clear that new entities may be created function getOrCreateUser(id) { const user = userRepository.get(id); if (!user) { user = userRepository.create(id); } return user; } ``` #### Classes Classes and objects should have a noun like `Customer`, `Account` etc. #### Methods Methods should have verb or verb phrases like `postPayment`, `deleteAccount` etc. ### Functions > First rule: functions should be small > Second rule: functions should be smaller than that #### One or Two arguments Limiting the number of arguments to 1-2 makes the function easier to test. Having more arguments leads to an combinatorial explosion of possible test cases and takes a lot of conceptual power. #### Do one thing A function should only do the thing its name indicates. ``` // DON'T function getUser(id) { const user = userRepository.get(id); user.isActiveUser = true; UserCache.add(id, user); return user; } ``` #### One level of Abstraction per Function Function that traverse multiple layers of abstraction are hard to test and reason about. ``` // DON'T function storeUser(user) { // code to serialize the user // code to get a file handle // code to write the serialized user to disk } // DO function serializeUser(user) { // code to serialize user }; function writeSerializedData(data) { // code to get a file handle // code to write serialized data } function storeUser(user) { const serializedUserData = serializeUser(user); writeSerializedData(serializedUserData); } ``` #### Avoid flag arguments Having a flag argument directly indicates that this function is not only doing one thing. Split them into separate functions. ``` // DON'T function save(toTempFile) { if (toTempFile) { writeToDisk(tempPath); } else { writeToDisk(defaultPath); } } // DO function save() { writeToDisk(defaultPath); } function saveToTempFile() { writeToDisk(tempPath); } ``` #### Argument objects When a function seems to need more than two or three arguments it is likely that some of these arguments ought to be wrapped into a class of their own. ``` // DON'T function makeCircle(x, y, radius) { } // DO function makeCircle(point, radius) { } ``` #### Have no side effects A function should only do what it promises and not execute hidden functionality. ``` // DON'T function checkPassword(userName, password) { const passwordHash = getUserPasswordHash(userName); if (hash(password) === passwordHash) { // side effect Session.initialize(); return true; } return false; } ``` #### Command Query Separation Functions should either do something or answer something, but not both. ``` // DON'T // does 'set': // - check wether username is set? // - return true when the 'username' equals 'foo' // - return true when username was set successfully? if (set('username', 'foo')) { ... } // DO if (attributeExists('username')) { setAttribute('username', 'foo'); } ``` ### Comments #### Explain yourself in code When you feel the need to explain your code in comments the code should probably be refactored to be clearer. ``` // DON'T // does the module from the global list <mod> depend on the // subsystem we are part of? if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())) // DO const moduleDependees = smodule.getDependSubsystems(); const ourSubSystem = subSysMod.getSubSystem(); if (moduleDependees.contains(ourSubSystem)) ``` #### Avoid Commented-Out code Others who see that commented-out code won’t have the courage to delete it. They’ll think it is there for a reason and is too important to delete. So commented-out code gathers. #### Avoid Noise comments ``` // get the user data function getUserData() {} ``` #### Good comments - Warning of consequences - Provision of additional context - TODO comments ### Formatting Use automatic tooling like `eslint` and/or `prettier`. #### Vertical density Related code should be vertically dense. Unrelated code should be vertically separated. ### Objects and Data structures #### Law of Demeter > A module should not know about the innards of the objects it manipulates. If this is not the case the object encapsulation is non-existant. #### Do not mix objects and data structures Objects expose behavior and hide data. This makes it easy to add new kinds of objects without changing existing behaviors. It also makes it hard to add new behaviors to existing objects. Data structures expose data and have no significant behavior. This makes it easy to add new behaviors for existing data structures but makes it hard to add new data structures to existing functions. ### Unit Tests #### Basic TDD process 1) Write the test that defines the behavior 2) Write the code to make the test succeed in any shape or form. Do not focus on style here. 3) Refactor the code until it is fit to be understood by other developers. #### F.I.R.S.T. rules **Fast** Tests should be fast. They should run quickly. When tests run slow, you won’t want to run them frequently. If you don’t run them frequently, you won’t find problems early enough to fix them easily. You won’t feel as free to clean up the code. Eventually the code will begin to rot. **Independent** Tests should not depend on each other. One test should not set up the conditions for the next test. You should be able to run each test independently and run the tests in any order you like. When tests depend on each other, then the first one to fail causes a cascade of downstream failures, making diagnosis difficult and hiding downstream defects. **Repeatable** Tests should be repeatable in any environment. You should be able to run the tests in the production environment, in the QA environment, and on your laptop while riding home on the train without a network. If your tests aren’t repeatable in any environment, then you’ll always have an excuse for why they fail. You’ll also find yourself unable to run the tests when the environment isn’t available. **Self-Validating** The tests should have a boolean output. Either they pass or fail. You should not have to read through a log file to tell whether the tests pass. You should not have to manually compare two different text files to see whether the tests pass. If the tests aren’t self-validating, then failure can become subjective and running the tests can require a long manual evaluation. **Timely** The tests need to be written in a timely fashion. Unit tests should be written just before the production code that makes them pass. If you write tests after the production code, then you may find the production code to be hard to test. You may decide that some production code is too hard to test. You may not design the production code to be testable. ## Additional references ### Books [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/) [The Pragmatic Programmer](https://www.amazon.de/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/) ### Language specific Style Guides [Clean Code JavaScript](https://github.com/ryanmcdermott/clean-code-javascript) [Airbnb JavaScript](https://github.com/airbnb/javascript) [Clean Code PHP](https://github.com/jupeter/clean-code-php) ### Videos [Uncle Bob Martin - Expecting Professionalism](https://www.youtube.com/watch?v=BSaAMQVq01E) [Uncle Bob Martin - The Principles of Clean Architecture](https://www.youtube.com/watch?v=o_TH-Y78tt4)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully