When do you use code blocks?

后端 未结 4 1836
名媛妹妹
名媛妹妹 2020-12-21 03:08

When do you use code blocks in C/C++/C#, etc.? I know the theoretical reason behind them, but when do you use them in real programs?

EDIT: I have ju

4条回答
  •  失恋的感觉
    2020-12-21 03:35

    I sometimes, but rarely, use naked code blocks to limit scope. For example, take the following code:

    double bedroomTemperature = ReadTemperature(Room.Bedroom);
    database.Store(Room.Bedroom, bedroomTemperature);
    
    double bathroomTemperature = ReadTemperature(Room.Bathroom);
    database.Store(Room.Bedroom, bedroomTemperature);
    

    The code looks fine at first glance, but contains a subtle copy-pasta error. In the database we have stored the bedroom temperature for both readings. If it had been written as:

    {
        double bedroomTemperature = ReadTemperature(Room.Bedroom);
        database.Store(Room.Bedroom, bedroomTemperature);
    }
    
    {
        double bathroomTemperature = ReadTemperature(Room.Bathroom);
        database.Store(Room.Bedroom, bedroomTemperature);
    }
    

    Then the compiler (or even IDE if it is intelligent enough) would have spotted this.

    However, 90% of the time the code can be refactored to make the naked blocks unnecessary, e.g. the above code would be better written as a loop or two calls to a method that reads and stores the temperature:

    foreach (Room room in [] { Room.Bedroom, Room.Bathroom })
    {
        double temperature = ReadTemperature(room);
        database.Store(room, temperature);
    }
    

    Naked blocks are useful on occasion though.

提交回复
热议问题