Naming conventions on IBAction functions - iphone

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.

Related

How do I check valid method name for an Object in Pascal?

I have a class (character) with inherited classes (solider, medic etc) that have specific game related methods. E.g. Shoot or Heal.
I want it so that the user can type in Heal, for example, and the program can check what type of character they have and therefore see if that is a valid name of a method in that Object.
I know it's possible in other languages but can't see how to do it in Pascal. It must work in Free Pascal as well as Delphi. Thank you
You don't need to be able to check for the validity of a method name to do this, and it is probably preferable if you don't.
You could do check a method name's using RTTI, but that is implemented somewhat differently in FreePascal than Delphi, (in particular for extended RTTI).
However, it would be far more straightforward to implement your own look-up mechanism to resolve in-game entity-names, properties and verbs in a dictionary of some sort. That would be trivial in both FP and Delphi and independent of the compiler used. It would also allow the names used by the end-user to be independent of the names used in code, which would be easier internationalisation, etc. It would also avoid the problem which would arise if an in-game identifier contained a character not permitted in a Pascal identifier (such as a space, accented character or whatever).
PS: You didn't ask this, BUT ... if I were contemplating writing a text-game of any size, I would seriously consider doing it as a hybrid Delphi of Prolog: Delpi for the gui and Prolog as a far easier language in which to code in-game actions, objects and rules, and there is one paricular implementation, Amzi Prolog, which has a very rich interface for interfacing a Prolog engine with Delphi -see https://www.amzi.com/#apls. Amzi used to be commercial but is now PD, fwiw.

Naming methods in Swift versus Objective-C

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.)

Code style of method chaining within Zend

this has previously been asked here (http://framework.zend.com/issues/browse/ZF-11135) with no response from Zend so really it has to come down to popular or majority decision.
The reason I am asking is because the company that I work for are increasing in size and having a standard style is obviously a sensible approach.
One example that is ignored from the example linked above is multiple methods per line, I.e
$this->setAction()->setMethod()->etc()
->etc()->andSoForth();
Which assists in the compliance of line length.
So whats your personal opinion?
Method chaining can get a little hard to follow on long lines, but if you add a return before each method call then it is perfectly readable and saves repetitively typing the class variable.
Regarding the question asked at http://framework.zend.com/issues/browse/ZF-11135 - the first and second code examples are identical - should they be showing a difference?

Simplest way to encapsulate multiple method arguments?

+ (Planet *)createPlanetInContext:(NSManagedObjectContext *)context
withName:(NSString *)name
type:(NSString *)type
group:(NSString *)group
andDiameter:(NSNumber *)diameter {
If I wanted to encapsulate the arguments "name", "type", "group" and "diameter" into a single entity for passing to the above method what is the best type to use for encapsulation? The above method is just a quick example which you could argue is just fine as presented, but what if there were many more arguments that needed to be passed. I would need to package the data before calling the method so the solution needs to be something quick and simple to setup.
+ (Planet *)createPlanetWithData:(Data *)data inContext:(NSManagedObjectContext *)context {
Or is it more inline with objective-c practices (more readable) to individually list all the arguments?
I'd say generally you would want to individually list your arguments, for clarity. The sample method you've posted above isn't terribly long, in the context of Objective-C.
It's really to do with readability and documentation. When you list all the arguments it's clear to developers coming to your project what's being passed in where, and what kinds of objects are floating around. Automatic documentation generation (eg, Doxygen) also works off lists of arguments particularly well.
But there is a point at which, as you say, it becomes a little unwieldy. Twenty parameters to pass in and your method calls are going to be very, very long! So there are other options available - the easiest one is probably to use a NSDictionary or similar, which is used already in iOS to ferry certain bits of data around (particularly with notifications, where you have the userInfo dictionary).
Reading code is harder than writing code, so optimize for readability. Shortness of selectors should not be a factor; clarity should be.
Ask yourself which version is more readable, and stick to that one. I think it's relatively obvious that the version with the direct arguments is more readable.
Objective-C has wonderful syntax for methods with multiple arguments, so use this to your advantage. In a language with c-like syntax, I'd also hesitate to use many arguments.
You could populate a dictionary with one key/value pair per property on your NSManagedObject.
If you want to be super flexible, you could go with #Novarg's comment and pass a dictionary as your argument. That way, you can add parameters to it without affecting your method signature.
I have a particular preference for creating a custom args object to pass into my methods. This not only has the flexibility of a dictionary, but also may have some built-in utilities or additional logic. Also, unlike a dictionary, you don't need to hardcode key names and/or constants, and is MUCH easier to refactor if you, say, need to change a name of a property using Xcode's refactoring capabilities:
+ (Planet *)createPlanet:(PlanetArgs *)args
{
//args.context
//args.name
//args.type
//args.group
//args.diameter
//Args can even have some built-in logic
//planet.color = [args generateRandomColor]; <<-Just a rough idea
}

Can something be initializable?

I've created an interface called Initializable, but according to Dictionary.com this is not a word. Searching Google only gives about 30k results and they are mostly API references.
Is there another word to describe something that can be initialized (which is a word)?
Edit:
Thanks for the questions about it being in the constructor, that may be a better way. Right now they are static classes (as static as can be in Ruby) that get loaded dynamically and have some initilization stuff to do.
Technical people create new words all the time. (see example below) But this isn't a case of creating a new word. This is a case of a "derivation". You have take a perfectly good word ("initialize") and added a perflecty good derivative suffix to it ("able"). The resulting word initializable is a derivative word.
In short, if something can be initialized, it is initializeable. Just like it can be runable, or stopable.
Now, I don't think it will be long before a grammar Nazi points out the error of my ways here. But English is rich and expressive language. A word doesn't have to be listed on "dictionary.com" for it to be valid. Nor even on m-w.com (which I believe is a better site).
One of my favorite books is Garner's Modern American Usage. Its a great book and is more than a dictionary - it is a reference and guide on how American English is used.
"Atomic" is a good example of a word we use in software development all the time that is somewhat of a "made up" word. In a development context something that is atomic either happens, or does not happen - it cannot be divided into separate operations. But, the common definition for this word doesn't take this usage into account.
Bah! Here is a better one.... "Grep" Not in the dictionary - but yet, a perfectly good word. I use it all the time
How about -
interface ICanBeInitialized
or...(and I had a little xmas drinky...so sorry)
interface ICanHazInitialization
I think the question --- other than the pedantic one about the word, which I'll mention below --- is what the behavior you intend to identify by this "Initializable" tag might be.
It's not an uncommon style to write a private method init() in, eg, Java to do complicated initialization; since that code may be needed in several places (what with copy constructors, clone operations and so on) it's just good form. Its less common, but a valid thing to so, to have a "Forward" class that is constructed, but that is waiting for some asynchronous operation in order to be fully initialized (eg, the Asynchronous Completion Token pattern). So it's not necessarily so that this should be just in the ctor, but I'm curious what the actual behavior you want would be.
On the word, English is a somewhat agglutinating language, like German: there are grammatical rules that construct works from base words and ther syllables in patterns. one of those is the one here, "Initial" -> "initialize" => "initializable". Any native speaker will recognize "initializable" as something that has the property of being able to be initialized. So it is a value word, but one they don't have in the dictionary for the same reason that don't have separate entries for the plurals.
I see nothing wrong with making up a word for an API-like thing if the invented word is clear.
I think worse words than Initializable have been invented - such as 'stringize' and 'RAII' (I nkow it's not a word, but it's still a term that's used often, and makes me cringe every time - even though the concept is doubleplusgood).
The problem I might have with Initializable is that it sounds like an interface that does what a constructor should be doing.
If Google gives back API references for "Initializable", it seems to me like a valid name for an interface, even though it might not be a valid English word. There's nothing wrong with using a made-up word, as long as it's descriptive.
The only thing I get confused about is classes are typically able to be initialized through their constructor. How does your interface provide functionality not available through the use of a constructor? The answer to this question may provide a more descriptive name than simply "Initializable". (i.e. in what way is it initializable?)
If Initializable most clearly describes what the interface is about, I wouldn't care about trying to find another word just so it is a valid English word. As long as it's not a UI string, the priority should be in naming clarity not validity of the word in the English language.
Yes, it's fine. Programming terms don't have to be in the dictionary. Dictionary.com also doesn't like "Serializable", and we all know that one's OK.
Yes. Don't let the lack of an existing word spoil your creativity if the meaning is clear
For those questioning the use of initialize - you may want to put constructor logic in a void method so to avoid race conditions when constructing weakly coupled classes through factories.
Example Factory:
public static T CreateSingleInstance<T>(string providerName, string sectionName)
{
//create the key
ProviderKey key = new ProviderKey(providerName, typeof(T));
//check key
if (!_singletons.ContainsKey(key))
{
object provider = _singletons[key] = CreateInstance<T>(providerName, sectionName);
IInitializable initializableProvider = provider as IInitializable;
if (initializableProvider != null)
initializableProvider.Initialize();
}
return (T)_singletons[key];
}
Example Implementation Constructors that would cause a race condition
public class Class
{
public Class()
{
Factory.CreateSingleInstance<OtherClass>(null, null);
}
}
public class OtherClass
{
public OtherClass()
{
Factory.CreateSingleInstance<Class>(null, null);
}
}
To echo what other's have said, it's valid English since English, like many languages, is formulaic and you're just applying a valid linguistic formula. Looks like there's precedence in what you're doing. The SQL Server team thinks what you're doing is valid since they came up with the same IInitializable Interface (see here). It looks something like this:
public interface IInitializable {
public void Initialize (IServiceProvider serviceProvider);
}