Why shouldn’t coders use under-bars at the beginning of ivariables in Objective-c

This is an interesting question simply because lots of senior programmers tell junior programmers they shouldn’t do but it, yet it seems to work. Why shouldn’t you do this? The main reason is, it’s really bad forum. If you are writing a little app for yourself, do what ever you want. You are the only person that will ever look at that code or maintain it. If you are part of a larger team this will reduce the ability to maintain the code and increase the cost of the project over time.

Why is this bad forum? In objective-c if you create a ivar that is in int called x:

@property (readwrite, nonatomic) int x;

In the class that this ivar exists in you can reference this variable in two ways; self.x for _x. Those to statement are equal for example:

if (self.x == _x) {
    NSLog(@”This will always be true”);
}

Now what happens if I create a ivar called _x, what happens:

@property (readwrite, nonatomic) int _x;

In the class we want to reference the variable in the same two ways; self._x and __x. This two statements is once again equal:

if (self._x == __x) {
    NSLog(@”This will always be true”);
}

That is fine. It should be noted that with the second example some problems could arise; __weak, __strong and __block for example are all reserved in objective-c. So if you create an ivar called _weak you are going to get problems, in objective-c it means something else.

We have established what works now what doesn’t work when we are creating ivars. What happens if we create to ivars in the same class:

@property (readwrite, nonatomic) int x;
@property (readwrite, nonatomic) int _x;

Big problems will now occur. We are attempting to create two variables that the compiler will think at certain times are the same. If you attempt to do this your program will crash. Here is a sample program to play around with to see what happens. It is just attempting to read and write two ivar named as above.

In summary why should you not use _ in front of the name of an ivar? It is very bad forum. It makes it harder for other coders to look at your code. It introduces possible errors down the road. It can cause crashes if you are not careful. It is like anything in life, why should we wear a helmet while driving a motorcycle? If you crash it saves your head. Do you have to? No.