Gagan Singh
Gagan Singh

Reputation: 986

Confusion with method syntax & naming convention in Objective C

I'm learning objective-c (via apple) and just finished up the portion that explains method syntax.

I decided to write a very simple method in a 'helper' class that would add two numbers...

the interface...

+ (int)addTwo:(int)num1 secondNum:(int)num2;

implementation...

+ (int)addTwo:(int)num1 secondNum:(int)num2 {
    return num1+num2;
}

usage...

int test = [MyClass addTwo:1 secondNum:2];

Now my problem is this..

everything compiles and is syntactically correct, however, in my opinion the usage of the method is extremely awkward, and in my opinion should be something along the likes of...

int test2 = [MyClass addTwo: firstNum:(1) secondNum:(2)]

basically, something that is more verbose in explaining that 1 is the first number and 2 is the 2nd.

As I write this I see that I could write something like "addTo:1, thisNumber:2" which is more clear, but I'm afraid I'm missing something important, or I didnt pick up on something that the lessons were trying to teach.

I'm used to Java so a lot of this is new in some ways, and If this is how objective c code is written, thats perfectly fine, but I just wanted to make sure I wasn't missing anything.

Thanks in advance.

Upvotes: 2

Views: 106

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Naming Objective C methods takes some time getting used to: the idea is to "glue" the description of the first parameter to the name of the method:

+ (int)addFirstNum:(int)num1 toSecondNum:(int)num2 {
    return num1+num2;
}

The idea is to make the name of your selector read as close to English as you think reasonable. In this case, the name of the selector is addFirstNum:toSecondNum:, and it reads OK in English.

Upvotes: 2

vikingosegundo
vikingosegundo

Reputation: 52227

int test2 = [MyClass addTwo: firstNum:(1) secondNum:(2)]

In this proposal you seem to treat firstNum and secondNum as variable names. that is wrong.

In Objective-C the method name is +addFirstNum:secondNum: and the parameters are passed in were the colons are: [MyClass addFirstNum:1 secondNum:2], but there is nothing like variable names.

In languages with named parameters like Python you could do addNums(first = 1, second = 2) and that would be equal to addNums( second = 2, first = 1), but in objective-C it is defined by the position of the colons. and the name of the method doesnt change.

Upvotes: 0

Related Questions