What is the proper way to format code?

前端 未结 22 2143
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题