Guard clauses vs. early return (Re: Accessors)
Guard clauses vs. early return (Re: Accessors)
- Subject: Guard clauses vs. early return (Re: Accessors)
- From: Marcel Weiher <email@hidden>
- Date: Thu, 8 Aug 2002 13:31:20 +0200
On Thursday, August 8, 2002, at 12:29 Uhr, Bill Cheeseman wrote:
on 02-08-08 2:03 AM, Shawn Erickson at email@hidden wrote:
- setSomeName: (SomeType*)newSomeName
{
if (newSomeName == _someName) return;
[_someName release];
_someName = [newSomeName copy];
}
I've noticed a couple of people testing for equality and returning in
the
first line, like this. My usual practice is to test for inequality,
then
fall through to the bottom if the test is false.
Yes, I do this as well.
Is there some advantage to the return?
No, there is no code-related advantage I can think of. I personally
see it as a disadvantage.
I've always thought it was just a matter of style.
Yes, it is a matter of style, but style matters ;-)
The style you use has several advantages from a readability perspective:
1. It states clearly what you want to do "up front"
Not what you do *not* want to do. It is therefore easier to read,
because the relevant part of the code (what it does) comes first. This
becomes even more obvious when you have several nested guards. You can
more easily ignore the parts that are not interesting.
2. It has a single exit
This is usually regarded as good style.
3. It is declarative, like a guard-clause
Reading the code does not depend on sequential execution semantics.
With the return-early style, you have to "simulate the machine" to
understand the code.
Here's a brief reference, I am sure you can google more if need be:
http://c2.com/cgi/wiki?GuardClause
Marcel
--
Marcel Weiher Metaobject Software Technologies
email@hidden www.metaobject.com
Metaprogramming for the Graphic Arts. HOM, IDEAs, MetaAd etc.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.