什么时候使用代码块? [英] When do you use code blocks?
问题描述
什么时候在C / C ++ / C#等等中使用代码块?我知道他们背后的理论原因,但你什么时候在实际程序中使用它们?
EDIT :我刚刚意识到我使用它们在 switch
语句,其中变量将在相同的范围(grr为 i
):
switch(x){caseabc:{/ * code * /} break; }
etc
(只是为了说明,在switch语句中,额外的大括号是<
我有时,但很少,使用裸代码块来限制范围。例如,取以下代码:
double bedroomTemperature = ReadTemperature(Room.Bedroom);
database.Store(Room.Bedroom,bedroomTemperature);
double bathroom温度= ReadTemperature(Room.Bathroom);
database.Store(Room.Bedroom,bedroomTemperature);
该代码看起来很好,但包含一个微妙的复制pasta错误。在数据库中,我们存储了两个读数的卧室温度。如果它已写成:
{
double bedroomTemperature = ReadTemperature(Room.Bedroom);
database.Store(Room.Bedroom,bedroomTemperature);
}
{
double bathroomTemperature = ReadTemperature(Room.Bathroom);
database.Store(Room.Bedroom,bedroomTemperature);
}
然后编译器(如果IDE足够聪明的话) this。
但是,90%的时间代码可以重构,使裸块不必要,例如上面的代码将更好地写为循环或两个调用读取和存储温度的方法:
foreach房间在[] {Room.Bedroom,Room.Bathroom})
{
double temperature = ReadTemperature(room);
database.Store(room,temperature);
}
裸块在某些时候是有用的。
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 just realised that I use them in switch
statements, where variables would otherwise be in the same scope (grr for things like i
):
switch (x) { case "abc": { /* code */ } break; }
etc (Just to clarify, in a switch statement, the extra braces are NOT required.)
Related:
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.
这篇关于什么时候使用代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!