问题描述
我只是想知道,在虚空中使用无参数返回是否合适
函数如下:
void SetMapLayer()
{
if(!Map)return;
layer = LAYER_MAP;
}
它运作良好但它被认为是一种很好的编程技术?
TIA,Max。
有些人会在风格上狡辩(更喜欢单个退出
点),但是这种技术没有任何问题。
[当然,你可以很容易地写出:
void SetMapLayer()
{
if(Map)layer = LAYER_MAP;
}
]
HTH,
- g
-
Artie Gold - 德克萨斯州奥斯汀
在结构化代码中,你会想避免从内部函数返回,但是在这种情况下它可能没什么区别。可怕的是
之类的东西:
void SomeFunc(){
if(...){
while(...){
if(...){
尝试{
if(... )返回
...
我不喜欢你的建筑有两个原因:
1)它破坏了结构化编程规则。每个函数只有一个返回点
。我把规则这个词放在了在引号中因为我自己打破它
随时我都喜欢它。但这里没有理由。
2)实际上是双重否定。如果!!地图我们将图层设置为LAYER_MAP。
你不觉得这更清楚吗?
void SetMapLayer()
{
if(Map)
layer = LAYER_MAP;
}
一个回报点,没有双重否定。
回到原来的问题,如果我认为我会使用无效的返回
函数净效应是使代码更简单。例如:
void fribble(int thing)
{
if(thing == 0)
返回; //解释为什么在这里
//这里有15行代码
}
结构化编程版本是
void fribble(int thing)
{
if(thing!= 0)
{
//这里有15行代码
}
}
我认为它的可读性稍差,虽然绝不是一个严重的错误。
-
Cy
Hi,
I was just wondering, is it good to use return without arguments in a void
function as following:
void SetMapLayer()
{
if( !Map ) return;
layer = LAYER_MAP;
}
It works well but it is considered a good programming technic?
TIA, Max.
Some will quibble about that stylistically (preferring a single exit
point), but there''s nothing wrong with that technique.
[Of course, you could just as easily have written:
void SetMapLayer()
{
if (Map) layer = LAYER_MAP;
}
]
HTH,
--ag
--
Artie Gold -- Austin, Texas
In structured code, you''d want to avoid willy nilly returning from inside functions,
but in this case it probably doesn''t make any difference. The scary ones are
things like:
void SomeFunc() {
if(...) {
while( ... ) {
if(...) {
try {
if(...) return
...
I don''t like your construction for two reasons:
1) It breaks the structured programming "rule" that each function have only
one return point. I put the word "rule" in quotes because I break it myself
anytime I feel like it. But here there is no reason to.
2) It is effectively a double negative. We set layer to LAYER_MAP if !!Map.
Don''t you think this is much clearer?
void SetMapLayer()
{
if (Map)
layer = LAYER_MAP;
}
One return point, no double negatives.
Getting back to your original question, I would use return in a void
function if I thought the net effect was to make the code simpler. Example:
void fribble(int thing)
{
if (thing == 0)
return; // explanation of why here
// 15 lines of code here
}
The structured programming version is
void fribble(int thing)
{
if (thing != 0)
{
// 15 lines of code here
}
}
which I think is somewhat less readable, although by no means a serious
mistake.
--
Cy
http://home.rochester.rr.com/cyhome/
这篇关于返回void函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!