Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Should I declare private methods?

I've been declaring private methods in class extensions, according to Best way to define private methods for a class in Objective-C.

But, I just realized that, in Xcode 4, if I leave out the declaration of a private method altogether and just implement it, the app compiles and runs without warning or error.

So, should I even bother declaring private methods in class extensions?

Why should we have to declare methods anyway? In Java, you don't... neither in Ruby.

like image 461
ma11hew28 Avatar asked Jul 20 '11 19:07

ma11hew28


People also ask

Should you make methods private?

Generally you should expose as little as possible and make everything private that is possible. If you make a mistake and hide something you should be exposing, no problem, just make it public.

Does it make sense to declare the method private final?

When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value.

When should I use private methods?

Private methods are typically used when several methods need to do the exact same work as part of their responsibility (like notifying external observers that the object has changed), or when a method is split in smaller steps for readability.


1 Answers

A method definition only needs to be defined if the caller is declared before the method. For consistency I would recommend defining your private methods in the extension.

-(void)somemethod
{
}

-(void)callermethod
{
    //No warning because somemethod was implemented already
    [self somemethod];
}

-(void)callermethod2
{
    //Warning here if somemethod2 is not defined in the header or some extension
    [self somemethod2];
}

-(void)somemethod2
{
}
like image 184
Joe Avatar answered Oct 12 '22 08:10

Joe