开发者

Is it possible to break/return method execution from another method?

I have something l开发者_运维知识库ike this:

void MethodToBreak()
{
    // do something

    if(something)
    {
        MethodThatBreaks();
        return;
    }

    // do something
}

void MethodThatBreaks()
{
    // do something
}

So, I was wondering: is it possible to break execution from: MethodThatBreaks()? Then, I would have: if(something) MethodThatBreaks(); and if the condition inside if is true, nothing after that row would be executed.

NOTE: I know it's possible with else in this case, but I don't want that.


It would be a nightmare to maintain if you were to upset execution of one method from another. Trying to figure out why your control flow is all over the place six months down the line, or for a another developer, would be aneurysm-inducing.

There's nothing wrong with what you're already doing there, although personally I'd use an else. Is there a particular reason why you don't want to use else? If it's that the remaining code is too long that's perhaps and indication you should refactor.


Throwing an exception in MethodThatBreaks is one possibility. So in the client of the MethodToBreak you put try catch block.


This can be done by: declare global variable

 a=null;
void MethodToBreak()
{
    // do something

    if(something)
    {
        MethodThatBreaks();
        if(a==null){

        } else{
        return;
        }
    }

    // do something
}

void MethodThatBreaks()
{
     a="somevalue";
    // do something
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜