All:
In Objective-C, the name is constructed by concatenating the signature keywords, e.g., application:didFinishLaunchingWithOptions:
How do people refer to the equivalent method in Swift, when discussing it with other programmers (including students)? For example, would you refer to verbally as application(), or application(_ didFinishLaunchingWithOptions:)?
Thanks,
Michael
Apple's style is to include all the parts of the declaration that make its unique function signature (and omit things that matter only to the implementor, like local parameter names). If you set the view on one of Apple's reference pages to Swift-only, you'll see this style in the method listings:
application(_:willFinishLaunchingWithOptions:)
application(_:didFinishLaunchingWithOptions:)
applicationDidBecomeActive(_:)
applicationWillResignActive(_:)
Obviously, when speaking aloud one can omit the punctuation and people will still know what you're talking about.
(Notice you can't call either of the first two just application(), because there are two distinct methods with that base name and different external parameter labels.)
Related
In my (chemistry related) project, I'd like to use the words Elementand Sequence for data structures. Will there be a conflict with the same names that are already used in Swift, should I rename them to MyElement and MySequence to be safe?
UPDATE:
I'm editing the question to hopefully make it more clear as was requested. The following quote is from the Generics section of Apple's Swift documentation:
Element defines a placeholder name for “some type Element” to be
provided later on. This future type can be referred to as “Element”
anywhere within the structure’s definition. In this case, Element is
used as a placeholder in three places
So, my question was if I can use the word Element for a structure without conflicting. The same for Sequence which I have seen used as well in sample code - although I cannot find it anymore. The accepted answer below explains this.
Those are not reserved words in Swift. The identifier Element is used as an associated type inside some generic types in the standard library, but you can also use it for your own type if you want, although it might become confusing. The identifier Sequence is not currently used by the standard library.
I am doing another iOS application and I wonder if there are any naming conventions or good practices on how to name actions that I could follow. I am thinking of names on the functions that are invoked when user e.g. touches a button.
Go with Apple's guidelines. What were in the past good suggestions have now been codified in ARC (Automatic Reference Counting) and are necessary to be followed for ARC to generate correct code. Using these guidelines may well future-proof your code, it did for ARC!
Apple's guidelines
Coding Guidelines for Cocoa
From the method naming section:
Start the name with a lowercase letter and capitalize the first letter of embedded words. Don’t use prefixes.
There are two specific exceptions to these guidelines. You may begin a method name with a well-known acronym in uppercase (such as TIFF or PDF)), and you may use prefixes to group and identify private methods
For methods that represent actions an object takes, start the name with a verb.
- (void)invokeWithTarget:(id)target;
- (void)selectTabViewItem:(NSTabViewItem *)tabViewItem
Do not use “do” or “does” as part of the name because these auxiliary verbs rarely add meaning. Also, never use adverbs or adjectives before the verb.
If the method returns an attribute of the receiver, name the method after the attribute. The use of “get” is unnecessary, unless one or more values are returned indirectly.
- (NSSize)cellSize;
Use keywords before all arguments.
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag
Make the word before the argument describe the argument.
- (id)viewWithTag:(int)aTag;
I haven't come across much in the way of specifics when it comes to naming conventions for IBActions. However, if you were to follow the trend Apple seems to be setting in its sample apps, then some examples are as follows:
-(IBAction)cameraAction:(id)sender;
-(IBAction)done:(id)sender;
-(IBAction)takePhoto:(id)sender;
Hope this helps.
I guess any method name in Objective - C should be readable like you reading an english sentence. Lets say below method.
[fileWrapper writeToFile: path atomically: YES updateFilenames: YES];
// This is not a real example but purpose of sharing is to make sure
method name is readable, so programmers can actually read code and can
have SmallTalk.
When you read left to right it helps you to read and explains it self what it is going to do.
Check out this below link,
http://cocoadevcentral.com/articles/000082.php
Jump on page No. 5 of 7
There are lots of tips has been given. More tips can be found in Apple's developer library.
Happy Coding
Here is a discussion about how to name IBAction functions/methods.
I am learning Objective C and noticed this funky quirk while reading up on methods.
Like Java and C++, Obj.C can take in multiple parameters, which is fine, however it states that objective C methods can have multiple names which does not seem to register to well with me.
For instance:
-(NSArray *)shipsAtPoint:(CGPoint)bombLocation withDamage:(BOOL)damaged;
In the above example, there are two parameters, bombLocation (return type CGPoint) and damaged (return type BOOL) and alongside the method name seems to be split as shipsatpoint:withDamage
I don't understand what's up with this...
What does it signify when it states that a method can have multiple names?
Is this applicable only for methods that require multiple parameters? Alternately, say I want to name my method with a single name but provide it with multiple parameters, is that possible or I must provide it with multiple names each of which correspond to a parameter? If yes, then why?
Thanks for jumping in with my confusion!!! :)
The reason is to make it easier to understand.
With your example, the method would be something like this in C++:
int shipsAtPointWithDamage (CGPoint bomb, BOOL damage) //I don't really know C++
OK, so the first parameter is the ship's point, and the damage is the second. It's easy enough to figure out, but that's the thing, you have to FIGURE it out, you have to look at the method to try and figure out what each thing is.
In Objective-C you have
-(NSArray *)shipsAtPoint:(CGPoint)bombLocation withDamage:(BOOL)damaged;
Each parameter is clearly defined, the first is the ship's point, the second is damage. It reads like a sentence, whereas with C++ (and almost every other language) it doesn't.
If you want a method to have multiple parameters in Obj-C you have to write it this way:
-(returnType)paraOne:(type*)name paraTwo:(type*)name
It's something that just takes getting used to, every language is different. Once you get used to the way Objective-C does things, you'll think it's absolutely fantastic.
EDIT: and as filipe pointed out, because the method as multiple parameters it doesn't mean it has multiple names, in the example I gave above, the method name would be paraOne:paraTwo, NOT paraOne:
Objective-C uses a system of message passing based on selectors. This is not quite the same thing as method calling. When you see code like this:
[world shipsAtPoint:point withDamage:YES];
That is converted into the following C call (in the most common case):
objc_msgSend(world, #selector(shipsAtPoint:withDamage:), point, YES);
The #selector() construct returns a unique identifier. The exact format of that identifier is an internal implementation detail.
objc_msgSend includes quite a lot of logic in it's few dozen bytes of assembler. But in simplest case, it looks up the class for world, walks through a table of selectors until it finds the one that matches shipsAtPoint:withDamage: and then grabs the function pointer at that slot. It then jumps to that function pointer, leaving the rest of the parameters alone (in registers or on the stack as appropriate for the processor). The function at that location is your method, and it knows the order and types of its parameters based on your declaration.
What's important in all this for you is that the selector is shipsAtPoint:withDamage:. This is generally the one-and-only name of the method. There are not "multiple names" as you suggest. (Usually.... the Objective-C runtime is very powerful and it's possible to point multiple selectors to the same implementation.)
As Joe points out, a selector can be in the form foo::. This would represent a method that took two parameters and would be called like [world foo:point :YES]. You should never do this. It's incredibly confusing to read. But it's legal.
Here is the best explanation i've ever seen. It includes comparisons with C++/C as well as lots of other good info.
I think you are confused. A method cannot have multiple names, but the argument may be named differently in the header then they are in the implementation.
The name of that method is shipsAtPoint:withDamage:. This is also known as a selector.
This method returns an instance of NSArray, and accepts a CGPoint as the first argument, and a BOOL as the second argument.
The names of the arguments may differ, however. This is totally valid:
// .h file
-(NSArray *)shipsAtPoint:(CGPoint)bombLocation withDamage:(BOOL)damaged;
// .m file
-(NSArray *)shipsAtPoint:(CGPoint)loc withDamage:(BOOL)dmg {
// ...
}
Lastly, ObjC is mainly some nice syntax sugar. You should know that any method invocation really just boils down to some C that looks more or less like this:
objc_msgSend(receiverObj, #selector(shipsAtPoint:withDamage:), point, damage);
So at the end of the day, you have a receiver, a selector, and your arguments. But the ObjC syntax is much nicer than that.
It is possible provide a method without labeled parameters but it is obviously discouraged.
-(void)badmethod:(id)obj1:(id)obj2:(id)obj3
{
}
//...
//Usage
[self badmethod:nil :nil :nil];
SEL sel = #selector(badmethod:::);
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
List selectors for obj-c object
Does anybody know how to get all selectors that a instance respond to during runtime in objective C?
As answered here, #import < objc/runtime.h > and use class_copyMethodList().
In general, this is not possible. "The selectors an instance responds to" may be an infinite set. For example, it is possible to implement a class that is sent Roman numerals as messages and returns the corresponding integer value. If you want to know the precise set of instance methods implemented by a class at a given time (which is a different question), you can just use the Objective-C runtime functions to get a class's instance method list and walk up the class tree to find the ones it inherits from superclasses. Again, though, these are two totally different things. A class might have a method for a message that it chooses not to respond to and it might respond to messages for which it does not have a directly corresponding method.
dapptrace (Dtrace) is your friend.
on the man page (man dapptrace):
dapptrace prints details on user and
library function calls
dapptrace is written for the Dtrace scripting language (D). This means you can adjust dapptrace or pull ideas from it's script file to do many things. For instance:
wait for myFunctionWhichCreatesSpecialObject to be called. Store the object address that it returns (the special object). Print out any selectors invoked on that object.
You can also invoke dtrace directly to write simple single-line spells. I'll let you go search for those.
During runtime you would use
the class method "+ (BOOL)instancesRespondToSelector:(SEL)aSelector"
provided you know the selectors you want to check on.
We seems to be abstracting a lot of logic way from web pages and creating "helper" classes. Sadly, these classes are all sounding the same, e.g
ADHelper, (Active Directory)
AuthenicationHelper,
SharePointHelper
Do other people have a large number of classes with this naming convention?
I would say that it qualifies as a code smell, but remember that a code smell doesn't necessarily spell trouble. It is something you should look into and then decide if it is okay.
Having said that I personally find that a name like that adds very little value and because it is so generic the type may easily become a bucket of non-related utility methods. I.e. a helper class may turn into a Large Class, which is one of the common code smells.
If possible I suggest finding a type name that more closely describes what the methods do. Of course this may prompt additional helper classes, but as long as their names are helpful I don't mind the numbers.
Some time ago I came across a class called XmlHelper during a code review. It had a number of methods that obviously all had to do with Xml. However, it wasn't clear from the type name what the methods had in common (aside from being Xml-related). It turned out that some of the methods were formatting Xml and others were parsing Xml. So IMO the class should have been split in two or more parts with more specific names.
As always, it depends on the context.
When you work with your own API I would definitely consider it a code smell, because FooHelper indicates that it operates on Foo, but the behavior would most likely belong directly on the Foo class.
However, when you work with existing APIs (such as types in the BCL), you can't change the implementation, so extension methods become one of the ways to address shortcomings in the original API. You could choose to names such classes FooHelper just as well as FooExtension. It's equally smelly (or not).
Depends on the actual content of the classes.
If a huge amount of actual business logic/business rules are in the helper classes, then I would say yes.
If the classes are really just helpers that can be used in other enterprise applications (re-use in the absolute sense of the word -- not copy then customize), then I would say the helpers aren't a code smell.
It is an interesting point, if a word becomes 'boilerplate' in names then its probably a bit whiffy - if not quite a real smell. Perhaps using a 'Helper' folder and then allowing it to appear in the namespace keeps its use without overusing the word?
Application.Helper.SharePoint
Application.Helper.Authentication
and so on
In many cases, I use classes ending with Helper for static classes containing extension methods. Doesn't seem smelly to me. You can't put them into a non-static class, and the class itself does not matter, so Helper is fine, I think. Users of such a class won't see the class name anyway.
The .NET Framework does this as well (for example in the LogicalTreeHelper class from WPF, which just has a few static (non-extension) methods).
Ask yourself if the code would be better if the code in your helper class would be refactored to "real" classes, i.e. objects that fit into your class hierarchy. Code has to be somewhere, and if you can't make out a class/object where it really belongs to, like simple helper functions (hence "Helper"), you should be fine.
I wouldn't say that it is a code smell. In ASP.NET MVC it is quite common.