Re: [Obj-C] if (self) vs. if (self != nil)
Re: [Obj-C] if (self) vs. if (self != nil)
- Subject: Re: [Obj-C] if (self) vs. if (self != nil)
- From: Thomas Davie <email@hidden>
- Date: Sat, 25 Feb 2012 08:31:11 +0000
To me, it breaks one of my golden rules, and exposes one of the things I dislike about C. Expressions, at least in my mind, should not involve state change – that's what statements are for.
My rationale behind this is that it makes it easier to read expressions – you get one more guarantee about what they're doing – they're computing a value, not changing some state behind your back.
This has a few implications for how I write code:
• I don't use the increment/decrement operators in expressions.
• I don't use the result value of assignments within expressions.
• Functions I try to keep as much as possible mathematical functions – they don't change state, they just return the result of a computation.
• If I need to return something from a subroutine that does change state, I tend to use a pointer argument rather than the result.
More specifically
• I don't use assignments in an if's condition, as below.
Bob
if (*ra4 != 0xffc78948) { return false; }
On 25 Feb 2012, at 01:12, Wade Tregaskis wrote:
>> if(nil != (self = [super init]))
>>
>> Myself I find it elegantly brief and imminently readable.
>
> I don't mind it, but to me it begs the question of what it offers over:
>
> self = [super init];
> if (self) {
>
> My rationale is, generally you avoid assignments within conditionals because it's just plain awkward. The if (self = [super init]) pattern is a rare exception, that is justified purely by convention at this point. If you're going to break that convention, and increase the verbosity to boot, you should probably just revert to fundamentals - i.e. treat it like any other assignment and test.
> _______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden