views:

61

answers:

2

I have something like 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.

+4  A: 

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.

Dave
Short-circuiting is a normal approach, that's what he's currently doing...do the work, and get out ASAP. It's not everyone's cup of tea, but it is a perfectly valid approach/style :)
Nick Craver
I don't want else because I may have a case like this: `while(something) if(something else) MethodThatBreaks()`
avance70
Then I don't see any problem with what you've already got, it's clear that if "something else" happens then you want to run a method then stop doing anything else. Like Nick says, it's perfectly normal.
Dave
Ok, I was just wondering, because each time I invoke `MethodThatBreaks()` I want to break whichever method invoked it. One thing I forgot to mention (and may be important) is that ALL methods that invoke `MethodThatBreaks()` are void.
avance70
A: 

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

Aliostad
Which is fine for errors but it seems like it needs to return regardless of the result of MethodThatBreaks. Using an exception for control flow in that cause is severely not advised...
Dave
@Dave "Using an exception for control flow in that cause is severely not advised". Absolutely! But the question was to do something that not a single line runs - not even a return. At least this is my understanding of the question.
Aliostad
Yes, thanks, but I cannot use exceptions. I didn't want to complicate the question by explaining the current architecture: This is a WCF service/client application. I use exceptions on service if something illegal is performed, for example, I would throw an exception if someone logs on with a wrong user/password combination. In this case `MethodThatBreaks()` is used to communicate a warning that should not terminate the current session, but will terminate the method execution.
avance70