Azurewrath

Hi,

In the book I am reading it shows examples like this:

if (!SourceFileExists()) return;

System.IO.File.Copy(txtSource.Text, txtDestination.text);

MessageBox.Show("The file has been successfully copied.");

Isn't it better to write it like this:

if (SourceFileExists())

{

System.IO.File.Copy(txtSource.Text, txtDestination.text);

MessageBox.Show("The file has been successfully copied.");

}

Is the above method to save lines

Thanks,

aw



Re: Visual C# General If condition

Friendly Dog

Someone believes the second style is better because it reduces possible exit routes of the method. But personally I think they are both fine.




Re: Visual C# General If condition

CalvinR

There are a couple of reasons why the first way is in my opinion the right way, first off it's clear that if the sourcefile doesn't exist we simply exit the method, so we don't have to jump to the bottom of the statement body to find out what happens. Secondly it prevents nesting of your code, now this is for me is a biggie as I generally edit my files in a seperate text editor, I like to keep my lines from going over 80 characters, so if we nest our if statements too deep then you begin to scroll past the edge of the screen.

For me these are issues that while when I was beginning to program were not an issue at all as I've matured and have started to work on larger projects with more and more people it has become very helpful to create easy to read and visually parsable code.

So technically there is no reason to pick one way over the other both will compile just fine, but when other people are looking at your code it's much better to pick the first way.





Re: Visual C# General If condition

Friendly Dog

Back in the old days (but believe me I'm not old, I just started early :)) where structured programming was revolutionary, single-entry and single-exit was a big deal. There are tons of theories why single-entry and single-exit was valuable and i think they still stand as today.

Some new programmers only care about OOP concetps however when it comes to method bodies structured programming still ned to be studied and applied.






Re: Visual C# General If condition

Azurewrath

So this is related to structured programming I didn't know it.

But isn't exiting a code using a return was slow I remember reading somewhere that it's slow in that it throws an exception internally. It wasn't c# though, maybe c or c++. So is this true

Thanks,

aw





Re: Visual C# General If condition

Figo Fei - MSFT

Hi,

In this case, logically when we start to copy files, we should first check if the source is exist, if not the process should be stop at once.

However, when the source does exist, it will certainly work successfully as we expect The answer should be no. Cause other errors (disk lack, permission denied etc) may occur as well.

So the first example is a little more clear logically, I think.

Of course, you may not in favour of me, it's ok. :)

Thanks

 






Re: Visual C# General If condition

ShellShock

Every method has a single entry point (enforced by the language semantics), and therefore I think every method should have a single exit point too (enforced by coding coventions). This makes it much easier to match each initialisation point with a corresponding clean up point.

For example if you use logging, you can easily add log lines to the start and end of a method to log entry and exit from the method.

Multiple returns make this much more difficult.

They also make it more difficult to add more code to the method as you need to be aware of all the preceding exit points which may mean your code is not executed.





Re: Visual C# General If condition

Matthew Watson

This is a highly debatable point.

"Single entry and single exit" sounds fine in theory, but it falls down in practise if you have a lot of error handling code early on in a function.

In my opinion, it is much easier to read and comprehend code that does early error returns rather than write more and more indented code...

People who dogmatically stick to the "single entry and single exit" scheme will nevertheless happily throw exceptions at various points in their functions - despite the fact that to do so is effectively the same as making an early return.

In fact, it is IMPOSSIBLE to stick to the "Single entry and single exit" dogma if you want to throw an exception. Which, to me, completely rules it out as a usable practice!

I do agree that with the normal flow of execution, "single entry and single exit" should be used wherever possible. But when it comes to early-return error-handing, and throwing exceptions, then it is not so practical.




Re: Visual C# General If condition

Ernst Kuschke

I agree - I think the single-entry-single-exit theory is something left from early (different) days of programming.

I also don't have any problems with "nesting", as long as it's easy to read. I do, for this reason, have a problem with very deep nesting.

I think the author of this piece of code most probably have the habit of coding like he did, and in this particular case it's a matter of personal taste Wink





Re: Visual C# General If condition

ShellShock

"In my opinion, it is much easier to read and comprehend code that does early error returns rather than write more and more indented code..."

The Microsoft guideline is not to use error returns, but to throw exceptions instead (taken from "Framework Design Guidelines" a book written by the designers of the .Net framework, and a very good read).

Throwing an exception is not the same as making an early return, especially in the way they propgate up the call stack, executing any finally blocks as it goes.

There are a lot of disadvantages of error returns compared to exceptions:

1. With error returns, error handling code is also near to the failing code. Exceptions give you the choice of handling errors further up the call stack.

2. To use error returns efffectively means a lot of if statements testing the return value of every method. If you omit the if statements, you are not dealing with errors properly. With exceptions you can handle errors in one place, at the top of the call stack.

3. Exceptions can contain a lot of info about the error. Error returns are usually just an error code.

Single entry and single exit is still valid as we are talking about normal execution flow through the program. Throwing an exception indicates an abnormal state, and the method cannot fulfil its purpose. This is also valid. We should not use a return statement to indicate an abnormal state. Return statements should only be use to return a value from a method where the value is the normal output from the method. I like to restrict this to one location - at the end of the method, so I can easily see that all execution paths through the method will end up at the same place.







Re: Visual C# General If condition

Azurewrath

- They also make it more difficult to add more code to the method as you need to be aware of all the preceding exit points which may mean your code is not executed.

I haven't thought about this. But IMO this is a valid reason too. With nested code, I will be able to see the flow of the execution quickly, checking out which conditions was met.

Also just I asked in my previous message, does using return to stop executing a method slower than using an if condition to disregard it I am not sure about this, but I read that c or c++ (I think) was thoring an exception internally to do this

Thanks alot for your insights!

aw





Re: Visual C# General If condition

ShellShock

I can't imagine any language designer using an internal exception to implement a function return.

I would also be surprise if there is any significant difference in performance between a return and an if, certainly not enough for this to be the main criteria in choosing between one or the other, unless you are writing really time critical code. In which case you should profile it intensively to find out where the real bottlenecks are in your environment, rather than assuming one language construct is more expensive than another - it all depends on the context.

Throwing an exception is slower than a return, but this is OK because it only happens in exceptional circumtances - your method can not perform its task.





Re: Visual C# General If condition

Azurewrath

Thanks ShellShock for replying.

So are you using the second method for this case in my first message

Thanks again,

aw





Re: Visual C# General If condition

Matthew Watson

 ShellShock wrote:

The Microsoft guideline is not to use error returns, but to throw exceptions instead (taken from "Framework Design Guidelines" a book written by the designers of the .Net framework, and a very good read).

Throwing an exception is not the same as making an early return, especially in the way they propgate up the call stack, executing any finally blocks as it goes.

There are a lot of disadvantages of error returns compared to exceptions:

1. With error returns, error handling code is also near to the failing code. Exceptions give you the choice of handling errors further up the call stack.

2. To use error returns efffectively means a lot of if statements testing the return value of every method. If you omit the if statements, you are not dealing with errors properly. With exceptions you can handle errors in one place, at the top of the call stack.

3. Exceptions can contain a lot of info about the error. Error returns are usually just an error code.

Single entry and single exit is still valid as we are talking about normal execution flow through the program. Throwing an exception indicates an abnormal state, and the method cannot fulfil its purpose. This is also valid. We should not use a return statement to indicate an abnormal state. Return statements should only be use to return a value from a method where the value is the normal output from the method. I like to restrict this to one location - at the end of the method, so I can easily see that all execution paths through the method will end up at the same place.


I quite agree that one should use exceptions rather than error returns. That wasn't, however, the point that I was making - although you seem to have answered as if that was the case...

The point I was making is that, given a choice between early error returns and multiply indented code, then early error returns are much easier to use. If your language supports exceptions, then you should use them!

And furthermore, in terms of seeing if a particular piece of code in the function is executed, you have to be aware of all the "throw" statements in a similar way to "return" statements. (The same of course applies to any looping and conditional constructs. This is a normal part of programming.)

The key thing is not to be dogmatic in your approach!

Here is an example of where I feel an early return is both easy to understand, and more efficient that rigidly sticking to structured programming.

We want to write a method that returns true if a collection contains a particular string (case sensitive comparisons). Ignore the fact that there already is a Collection.Contains() method!

Here's the method if you stick rigidly to structured programming:



private bool Contains(Collection<string> collection, string target)
{
    bool found = false;

    for (int i = 0; i < collection.Count && !found; ++i)
        if (ValueType == target)
            found = true;

    return found;
}

 


And here's the method if you allow an early return:



private bool Contains(Collection<string> collection, string target)
{
    foreach (string value in collection)
        if (value == target)
            return true;

    return false;
}

 


I prefer the second version, because it's easier to read, and only performs one comparison per iteration. The first version must perform two comparisons per iteration (comparing the string and the 'found' variable required to terminate the loop).

I admit the overhead of comparing an additional bool every iteration is small; but I think it just reads better.

It is also quite instructive to see how .Net approaches these things. For example, if you use Reflector to examine the code for ArrayList.Contains(), you find this:



public virtual bool Contains(object item)
{
    if (item == null)
    {
        for (int i = 0; i < this._size; i++)
        {
            if (this._itemsIdea == null)
            {
                return true;
            }
        }
        return false;
    }
    for (int i = 0; i < this._size; i++)
    {
        if ((this._itemsIdea != null) && this._itemsIdea.Equals(item))
        {
            return true;
        }
    }
    return false;
}

 









Re: Visual C# General If condition

CalvinR

>Also just I asked in my previous message, does using return to stop executing a method slower >than using an if condition to disregard it I am not sure about this, but I read that c or c++ (I >think) was thoring an exception internally to do this

C and C++ definitly do not throw an internal exception to return, if I remember correctly from my assembly courses what they do is put the return value into a register then pop everything off the stack and jump back to the place in code where they previously were. As for c# i'm not too sure what happens but I believe it's a similar process if you drill down deep enough.

>I would also be surprise if there is any significant difference in performance between a return

>and an if, certainly not enough for this to be the main criteria in choosing between one or the

>other, unless you are writing really time critical code. In which case you should profile it

>intensively to find out where the real bottlenecks are in your environment, rather than >assuming one language construct is more expensive than another - it all depends on the

>context.

If I remember correctly an if statement at least when you boil it down to assembly code is pretty much very similar to a return statement except instead of puting something into a register and jumping you make a comparison of two variables and then jump based on the result.

As for the single exit for me I don't see the point, I personally prefer shorter methods and less heavily nested, I personally do all of my code editing in VI, and then my debugging in Visual Studio, so I don't like lines that are longer then 80 characters because it makes it really hard to read whats going on. So if I have to throw multiple return statements into a method then so be it.

Also if the code is so complex that you have a hard time finding all of the return statements then maybe the code is a little too complex.

For me single exits are not really an issue, I have an easier time following code with multiple exit statements then trying to parse deeply nested code with one return statement.