What is the proper way to format code?

前端 未结 22 2203
没有蜡笔的小新
没有蜡笔的小新 2021-02-18 18:33

When I write code, I try to group lines of similar code together, then leave a blank line and write another block.

I believe this contributes to the neatness and readabi

相关标签:
22条回答
  • 2021-02-18 19:18

    We have a coding standart that states that we should not put more than one blank line in a row. All the other is up to developer. In practice we do as you say - try to group logically connected lines into groups and isolate them with blank lines.

    0 讨论(0)
  • 2021-02-18 19:19

    I think I do something similar, but there are no hard rules. I like code to spaced in 'paragraphs' of grouped/related logic.

    Code with no extra line spaces is terrible to read.

    0 讨论(0)
  • 2021-02-18 19:20

    It sounds like I space lines of code similar to you.

    But this is an irrelevant, personal preference and everybody is going to have thier own 'right way' to do it. The most important thing, IMHO, is to adapt the style of the environment you are going into.

    Also, you will find code like this in the 'real world' ... but it sounds like you have higher aspirations. ;-)

    EDIT: ... not higher aspirations than the 'real world', but higher than the mediocre crap common in the 'real world'. ... if you do happen to have higher aspirations than the 'real world' however, you might want to see a professional. ;-)

    0 讨论(0)
  • 2021-02-18 19:21

    Not to sound pretentious, but I think of blank lines in code as having a similar function to phrase marks in music notation, or line breaks in poetry: they communicate intent to the reader without changing the semantics of the content.

    Here's a method I just copied and pasted from a project:

    public static void Startup(bool startupUser)
    {
        URI = "";
        AutoComplete = new AutoCompleteWrapper();
        SessionToken = Guid.Empty;
        ExternalDataSetLock = new object();
    
        ConfigDS.Init();
        CalendarDS.Init();
        CalendarDSBuilder.Init();
    
        if (startupUser && UserName != null)
        {
            string autoCompleteFilename = Path.Combine(UserFolder, "autocomplete.xml");
            AutoComplete.Load(autoCompleteFilename);
        }
    }
    

    What do the blank lines do here? They clarify that there are basically three different kinds of initialization taking place in this method. If I add a new property that needs to be initialized on startup, I know where I'm going to put the line that initializes it. The blank lines also hint at how I intend to refactor this function if it doubles in size.

    The risk of using blank lines is the same as the danger of any other kind of implied meaning: it's implied. The implication you're making when you write the code may not be the implication that the person reading the code understands.

    But mercy, that's no reason not to use them.

    0 讨论(0)
提交回复
热议问题