Using the Dot Operator vs Bracketed Messages in Objective-C [duplicate] - objective-c

This question already has answers here:
What's the difference between dot syntax and square bracket syntax?
(5 answers)
Closed 8 years ago.
From 'Programming in Objective-C', 6th Edition, Stephen G. Kochan:
Although it’s syntactically correct to write a statement such as myFraction.print, it’s not considered good programming style. The dot operator was really intended to be used with properties; typically to set/get the value of an instance variable. Methods that do other work are typically not executed using the dot operator; the traditional bracketed message expression is the preferred syntax.
Are there performance drawbacks to backup this position, or is this merely social convention?

I don't think it's social convention that drives this. I think it's the improved readability that you get from it.
There isn't a performance hit but you will find it easier working with other devs if you follow the standard.
The Times Online style guide is one I work to and is fairly standard with Apple's own coding style.

It's just a social convention. Properties are just a syntax sugar. So when you use dot-notation, it is automatically translated into a call to a getter/setter.
But I'm totally agree with Mr. Stephen G. Kochan. Using dot-syntax for calling methods is misleading.

Messaging methods that are not properties with the dot syntax is allowed because at the time properties and dot operator were introduced there were hundreds of millions of lines of code just using get/set accessors methods, and that meant you could use the dot operator to signal that you were using property-like accessors even though they were not declared as properties. Theoretically, this could be removed by now.
Using the dot operator for something else than getting or setting properties is bizarre and will make your code incredibly confusing for yourself and for others, but there's no performance tax at runtime for doing so. On the flip side, there's also no reason to not declare your properties as properties any longer - particularly since it results in less code in Objective-C and enables them to show up as properties instead of as methods in Swift.

Related

object.method notation in Ada

does anyone know of a good resource to explain when the object.method notation can be used in ada?
for example:
person.walk(10);
I've been doing a bit of googling and haven't figured it out yet. Does it only apply to tagged records?
I use GPS as my Ada IDE, I quite like being able to go bla.<type something> and getting suggested methods to call.
I'm a bit confused also on why the dot notation can't be used for anything where the first parameter matches the type in question.
Thanks
Matt
Yes, it only applies to tagged record (the vtable is used to find the corresponding method). It can be used for all primitive operations, or for the 'Class operations defined in the same package.
One of the nice benefits of the notation is that you do not need a "with" on the package that defines the type.
We tend to use tagged types more often theses days, just so that we can use the dot notation indeed.
Dot notation also applies to task an protected types.

What's the benefit of case-sensitivity in a program language? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any advantage of being a case-sensitive programming language?
My first programming experiences where with the Basic family (MSX Basix, Q-basic, VB).
These are all not case-sensitive. Now, it might be because of these first experiences, but I've never grasped the benefit of a language being case sensitive. On the contrary, I think it is a source of unneeded overhead and bugs, and it still annoys me when I use e.g. Java or C.
Now, I just read on Clojure (a Lisp-dialect) and noticed - to my surprise - that one of the differences with Lisp is case-sensitivity.
So: what is actually the benefit (to the programmer) of having a case-sensitive language?
The only things I can think of are:
double the number of symbols
visual feedback and easier reading for complex variables using techniques like CamelCase, e.g. HopCount
However, the first argument doesn't hold because of being a major source for bugs (bad practice to use hopcount and HopCount in one method).
The second argument doesn't hold either, as a decent IDE can provide this also in an other way. A good example is the VBA IDE, which has a very good approach: the langauge is case-insensitive but as soon as you type a variable it will change it to the case used in its definition. For example, if you defined Dim thisIsMyVariable as string, it will change any occurrence of thisismyvariable into thisIsMyVariable). That provides the programmer with an immediate clue that the variable was actually typed-in correctly (because it changed appearance).
Edit: added ... benefit to the programmer ...
One point is, like you said, visual aid. Most programming languages (and even frameworks) have conventions on how to capitalize variables, names, etc.
Also, it enforces using uniform names everywhere, so you don't have a mess with the same variable referred to as "var", "Var" or even "VaR".
I can't remember of ever having bugs related to capitalization, so that point seems kind of contrived to me.
Using 2 variables of the same name but different capitalization to me sounds like a conscious attempt to shoot yourself in the foot. Different capitalization conventions almost everywhere signify objects of completely different type (classes, variables, methods and so on), so it's pretty hard to make such a mistake due to the completely different semantics.
I'd like to think of it in this way: what do we gain by NOT having case-sensitivity?
We introduce ambiguity, we encourage sloppiness and poor style.
This is a slightly subjective matter of course.
Many naming conventions demand that symbols denoting objects from different semantic classes (types, functions, variables) have their own name casing rules. In Java, for example, types names always begin with a upper case letter, while variables, member function names etc. begin with a lower case letter. This effectively puts type names in a different namespace and gives a visual clue what a statement actually means.
// declare and initialize a new Point
Point point=new Point();
// calls a static member function of type Point
Point.fooBar();
// calls a member function of Point
point.moveTo(x,y);

Operator overloading - is it really reasonable to forbid?

Java forbids operator overloading, but coming from C++ I do not see any reason for that. In languages where operator symbols are symbols as any other, same rules apply to "+" as to"plus" and there is no problem. So what is the point?
Edit: To be more concrete, show me which disadvantage overloaded "+" may have over overloaded "equals".
Just as many other things in Java, this is a restriction because it may be confusing if used improperly. (Similarly as pointer arithmetic is forbidden because it is error prone.) I'm a big fan of Java, but I'm generally of the opinion that it shouldn't be forbidden just because it could be misused.
For instance, BigInteger would benefit greatly from overloading the + operator.
OK, I'll try my hand at this under the assumption that Gabriel Ščerbák is doing this for better reasons than railing against a language.
The issue for me is one of manageable complexity: How much of the code in front of me do I have to decode vs. simply read?
In most conventional languages, upon seeing the expression a + b I know what is going to happen. The variables a and b will be added together. I'm pretty confident that behind the scenes the code will be very concise, very fast native machine code that adds the two numbers, whether the numbers are short integers or double-precision or some mixture of the two. (In some languages I may have to also assume that these could be strings being concatenated, but that's a rant for an entirely different question -- but one that flavours this rant if you peer at it from the right angle.)
When I make my own user-defined type -- say the omnipresent Complex type (and why Complex isn't a standard data type in modern languages is way the Hell beyond me, but that, again, is a rant for a different question) -- if I overload an operator (or, rather, if the operator is overloaded for me -- I'm using a library, say), short of peering very closely at the code I will not know that I'm now calling (possibly-virtual) methods on objects instead of having very tight, concise code generated for me behind the scenes. I will not know of the hidden conversions, the hidden temporary variables, the ... well, everything that goes along with writing many operators. To find out what's really going on in my code I have to pay very close attention to every line and keep track of declarations that may be three screens away from my current location in the code. To say that this impedes my understanding of the code flowing before my eyes is an understatement. Important details are being lost because the syntactic sugar is making things taste too tasty.
When I'm forced to use explicit methods on the objects (or even static methods or global methods where that applies) this is a signal to me, while I'm reading, that tells me of the potential cost overheads and bottlenecks and the like. I know, without even having to think for an instant, that I'm dealing with a method, that I've got dispatching overhead, that I may have temporary object creation and deletion overhead, etc. Everything's in front of me right before my eyes -- or at least enough indicators are in front of me that I know to be more careful.
I'm not intrinsically opposed to operator overloading. There are times when it makes code clearer, yes indeed, especially when you have complicated calculations over many baffling expressions. I can understand, however, exactly why someone might not want to put that into their language.
There is a further reason not to like operator overloading from the language designer's viewpoint. Operator overloading makes for very, very, very difficult grammars. C++ is already infamous for being nigh-unparseable and some of its constructs, like operator overloading, are the cause of it. Again from the viewpoint of someone writing the language I can fully understand why operator overloading was left off as a bad idea (or a good idea that's bad in implementation).
(This is all, of course, in addition to the other reasons you've already rejected. I'll submit my own overloading of operator-,() in my old C++ days in that stew just to be really annoying.)
There is no problem with operator overloading itself, but how it's actually has been used. As long as you overload the operators to make sense, the language still makes sense, but if you give other meanings to operators, it makes the language inconsistent.
(One example is how the shift left (<<) and shift right (>>) operators has been overloaded in C++ to mean "input" and "output"...)
So, the reasoning when leaving out operator overloading was probably that the risk of misuse was greater than the benefits of having operator overloading.
I think that Java would benefit greatly from extending its operators to cover built-in Number object types. Early (pre-1.0) versions of Java were said to have it (in that there were no primitives - everything was an object) but the VM technology of the time made it prohibitive from a performance view.
But in terms of in general allowing user defined operator overloading, it is not in the spirit of the Java language. The main problem is simply that it is hard to implement an operator that is consistent with what you expect from mathematics across object types and it will open the door to a lot of bad implementations which lead to a lot of hard to find (therefore expensive) bugs. You can just look at how many bad equals implementations (as in violate the contract) there are in general Java code, and the problem would only get worse from there.
Of course there are languages that prioritize power and syntactical beauty over such concerns, and more power to them. It is just not Java.
Edit: How is a custom + operator different than a custom == implementation (captured in Java in the equals(Object) method)? It isn't, really. It is just that by allowing operator overloading, things that are intuitive to a sixth grader become untrue. The real world experience of equals(Object) implementations shows how such complex contracts become hard to enforce in the real world.
Further Edit: Let me clarify the above, as I shortened it while editing and lost the point. A + operator in math has certain properties, one of which is that it doesn't matter which order the numbers on either side appear - it has the same result. So consider even the simplest case of a + performing an add to a Collection:
Collection a = ...
Collection b = ...
a + b;
System.out.println(a);
System.out.println(b);
The intuitive understanding of + would lead to an expectation that a + b or b + a would give the same result, but of course they would not. Start mixing two object types that take each other as paramaters in their plus method (say Collection and String) and things get harder to follow.
Now certainly it is possible to design operators on objects which are well understood and lead to better, more readable and more understandable code than without them. But the point is that more often than not in home-grown corporate APIs what you would end up seeing is obfuscated code.
There are a few problems:
Overloading logical operators has side effects because of lazy evaluation.
Even in mathematical types there are ambiguities, is (3dpoint*3dpoint) a cross or scaler product
You can't define new operators, so people reuse existing operators in novel ways eg. "string1%string2" to mean split string1 on string2.
But you can't always protect idiots from themselves even with an outright ban.
The point is that whenever you see, for example, a plus sign being used in the code, you know exactly what it does given that you know the types of its operands (which you always do in Java, as it is strongly typed).

Instance variable naming conventions in Cocoa

This question is about variable naming style in objective c and cocoa. I just want to stress that I'm not looking for a "right" answer, just good ideas.
I've read through Apple and Google's objective c style guides and I'm not really happy with either of them. Apple's guide doesn't have any real style recommendations regarding instance variables vs local variables. In fact, the Cocoa library itself seems perfectly happy having function parameters of the exact same name as instance variables. That makes me cringe personally.
Googles guide specifies that instance variables should be indicated with a trailing underscore. Alright, all well and good, but it suggests that we then synthesize every public property with #synthesize property = property_. I don't know about anyone else, but I'll be damned if I'm going to do that for every instance variable in my project. I think it's a wasteful and confusing solution.
I'm tempted to go with the myX (eg "myInstanceVariable") naming style for object properties, but I have rarely seen that style in objective c.
So yeah, what do you use? Any style conventions out there I don't know about that you've found useful? Do you think function parameters with the same name as instance variables is dangerous, especially in multiple developer environments? Thanks guys and gals!
NOTE - As many people have pointed out, my terminology was off in the OP. Apologies if the original wording hurt the clarity, but I think the point was still clear.
I tend to use non-prefixed instance variable names (note that "member variable" is a C++ism as it's suggestive of structures and classes being mainly interchangeable, which is not the case in Objective-C), and in cases where ambiguity arises, I use the Smalltalk convention of naming the parameter by its type with "a" or "an", e.g.:
- (void)setFoo:(SOFoo *)aFoo;
{
foo = aFoo;
}
(of course, in modern ObjC you'd use a property for this.)
Using theFoo instead of aFoo is also somewhat common; see the answers to this question.
The Google convention makes sense if you're really worried about conflicts. If you use an Xcode text macro or tool like Completion Dictionary or Accessorizer to generate your directives, it's pretty simple to adopt.
Note that the Cocoa key-value coding guidelines pretty much assume either (a) you do not prefix/suffix your instance variable names, or (b) you implement (or synthesize) non-prefixed/suffixed accessors for them. As someone else mentioned, do not use the _ prefix; it's reserved for Apple's use in their frameworks.
First: there are no "member variables" in Objective-C, there are "Instance Variables" or "ivars".
Google is NOT any kind of authority on Objective-C coding or Mac development. Google Earth is a Qt app: 'nuff said.
I seem to remember seeing an official coding style guide from Apple for Objective-C, which I'm not finding at the moment. This article is a pretty good summary, though:
http://cocoadevcentral.com/articles/000082.php
Found it! Here's Apple's official coding guidelines for Cocoa:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html
In Cocoa, the style is to have pascalCased (or is that camelCased? I can never remember) names; and have the member variables be named the same as the accessor methods. (Such as NSInteger anInteger, - anInteger and - setAnInteger:).
It might not be the best style, but it's probably a good idea to get used to it if you are going to do any amount of work with Cocoa, as a number of mechanisms assume this particular kind of naming convention.
_foo is not bad habit. Or at least it is not anymore. See:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html
m_variableName is pretty common too for member variables.
Personally, most of the time, I just go with the same name for both variables and making the distinction between this.varname and varname.

What is the alternative to excessive use of the dot operator in Obj-C?

See what you think of this line of code:
if ([pickerViewController.picker.bvc.currentResolve.name isEqualToString:message])
...
Would you consider this to be excessive use of the dot operator?
If not, I can leave it as-is.
But if so, what's the preferred alternative?
This is more of a Law of Demeter violation than a problem with the dot operator. The "cleaner" way to do this would be to give the object the logic to figure this out itself, so you could do something like
if ([pickerViewController hasPickedName:message])
I don't think there is excessive use of the property notation. If an object has a property, access it as such; it demonstrates to the reader what the programmer means.
Oh, and pre-empting the "looks like a struct" brigade; if you can't tell a struc from an object in your code, refactor your code.
So long as each use of the dot operator there really is fetching a property (i.e. not a method which is chiefly concerned with doing work for purposes other than returning a value), then that's fine. In fact, if you check Wil Shipley's blog, he's actually a fan of chaining as many function calls together into a single line as is necessary (he dislikes excessive use of local variables).
I find that debugging this sort of thing is always more trouble than it's worth, so I tend to create intermediate variables for each of the property accesses. Or, as others suggested, refactor this so it looks simpler at the usage site (by putting the smarts in a method).
I agree with Chuck and commenters. Your method is dependent on too many other objects, but putting hasPickedName: on pickerViewController means pickerViewController still has to do [picker.bvc.currentResolve.name isEqualToString:message] somehow.
Instead, you could put hasPickedName: on bvc and inject bvc as a delegate (typed id<NamePickerDelegate> maybe) into your top-level object using Interface Builder. To be truly Demeter-compliant, make currentResolve grow a method nameMatches: that shortcuts [currentResolve.name isEqualToString:message].
You should look carefully at the complexity caused by the problem verses the complexity that would be introduced by each solution. If you judge that the original code is simpler and easier to maintain than the alternatives, keep it.