Indent lines in code

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. [I talked about the code indent line at the London Golang UK conference in 2016] (https://raw.githubusercontent.com/studygolang/gctt-images/master/line-of-sight/1_CBjBs9EzL8q1AL6XvjjpJg.png) In the recent [Golang UK conference] (HTTPS://WWW.YOUTUBE.COM/WATCH?V=YEETIGNEIKC) in London, I am in the [native Go language tips] (https://www.youtube.com/watch V=YEETIGNEIKC) communication ([slideshow] (http://go-talks.appspot.com/github.com/matryer/present/idiomatic-go-tricks/main.slide# 1), I'd like to explain a little bit about the indentation in the code. > Indent lines are "the line of sight of the observer without obstruction"! [Indent lines in code: The indentation of the left image is the happy path for error handling and edge conditions] (https://raw.githubusercontent.com/studygolang/gctt-images/master/line-of-sight/1_nXXRSHi_1kmgorkcDHyc1Q.png) Good code indentation not only has no effect on your functionality, but also helps other people in need to read your code. Other programmers, including your future self, can browse a column and understand the expected flow of code. If they had to analyze the ' if ' statement in their brains, it would make the task very difficult without a good indent line. > Most people pay attention to the cost of writing code, such as "How long does it take to complete?" "But the cost of maintaining the code is much higher-especially in mature projects. It is important to make the function obvious, clear and easy to understand. Recommendations for good indent lines: * Let [Happy Path] (Https://en.wikipedia.org/wiki/Happy_path) align to the left so you can quickly scan a column to see the expected execution flow * Do not hide the code logic in the indent braces * Exit early ' function ' * avoid ' else return ', consider flipping ' if ' statement * take ' return ' as the last line * extract ' function ' and ' method ' to keep the structure small and readable * asYou need to indent the code, consider it as a ' function ' decomposition of course, there are many good reasons to break all these rules-but with this style as the default rule, we find our code more readable. # # The key to avoiding ' else return ' writing well-visual code is to keep the ' else ' structure small, or, if possible, to avoid them altogether. Look at this code: "' GOif something. OK () {something. Lock () Defer something. Unlock () Err: = something. Do () if Err = = Nil {stop: = Starttimer () defer stop () log. Println ("Working ...") doWork (something) <-something. Done ()//wait for Itlog. Println ("finished") return nil} else {return err}} else {return errors. New ("Something Not OK")} "" This represents how we initially think about what our function is doing ("If something is OK, then do it, if there is no error, then do these things" and so on), but it becomes very difficult to follow. The code above is difficult to follow the ' Happy Path ' (the route that runs smoothly). It starts indenting on the second line and continues from there. When we check from ' something. Do () ' ERROR returns when we indent further. In fact, the statement "' Return nil '" is completely lost in the middle of the code. The ' else ' structure is often returned as a single row in go and other languages because they are handling abort or exit functions. I don't think they can guarantee to indent our other code. # # Flip If statement if we want to translate the ' if ' statement * (If you like *, * turn them * over) *, you can see the code becomes more readable: ' ' goif!something. OK () {//Flippedreturn errors. New ("Something Not OK")}something. Lock () Defer something. Unlock () Err: = something. Do () if err! = Nil {//Flippedreturn Err}stop: = Starttimer () defer stop () log. PrIntln ("Working ...") doWork (something) <-something. Done ()//wait for Itlog. Println ("finished") return nil ' ' In this code, we are exiting as early as possible, and the exit code is different from normal code. And, * The happy path remains down along the left side, * We indent just to handle the error and edge situation, * our ' retutn ' declares "' Return nil '" in the last line, and, * we have fewer indentation blocks. # # Promote the functionality of large conditional blocks if you can't avoid a cumbersome ' else ' structure or a bloated selection switch (I understand, sometimes you can't), then consider decomposing each structure into its own function: "' Gofunc processvalue (v interface{ }) Error {switch val: = V. (type) {case String:return processstring (val) case Int:return Processint (val) case Bool:return Pro Cessbool (val) Default:return FMT. Errorf ("Unsupported type%T", V)}} "is easier to read than reading a lot of processing code. # # Share your experience if you agree with me, please consider sharing this article-as more and more people register, a better (more consistent) Go code will appear. Do you have some hard-to-read code? Why not in [Twitter @matryer] (https://translate.googleusercontent.com/translate_c?depth=1&hl=zh-CN&prev= Search&rurl=translate.google.com.hk&sl=en&sp=nmt4&u=https://twitter.com/matryer&xid= 17259,15700023,15700124,15700149,15700168,15700173,15700186,15700201&usg= ALKJRHGR995EKJEXZDOQL9LYU8SL7EQ3TA) to share it, you can see if we can find a cleaner, simpler version. # # Thank you ... Critic [Dave Cheney] (HTtps://translate.googleusercontent.com/translate_c?depth=1&hl=zh-cn&prev=search&rurl= Translate.google.com.hk&sl=en&sp=nmt4&u=http://dave.cheney.net/&xid= 17259,15700023,15700124,15700149,15700168,15700173,15700186,15700201&usg= ALKJRHGTC1JMFDNNABAZ1IX8DJSOJYUDDW), [David Ernandez] (https://translate.googleusercontent.com/translate_c?depth=1& hl=zh-cn&prev=search&rurl=translate.google.com.hk&sl=en&sp=nmt4&u=http://twitter.com/ dahernan&xid=17259,15700023,15700124,15700149,15700168,15700173,15700186,15700201&usg= ALKJRHHM04BLUEW6J4VCW3ACIXTPEMMMXA) and [William Kennedy] (Https://translate.googleusercontent.com/translate_c?depth=1&hl =zh-cn&prev=search&rurl=translate.google.com.hk&sl=en&sp=nmt4&u=https://twitter.com/ goinggodotnet&xid=17259,15700023,15700124,15700149,15700168,15700173,15700186,15700201&usg= ALKJRHI57B943KOWPS6PE4_ARSLBMY-7MW).

via:https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88

Author: Mat Ryer Translator: Yuhanle proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

419 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.