Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: when to use function vs method

Tags:

objective-c

I've started using Xcode's refactoring abilities (edit > refactor > extract) and noticed that Xcode offers to extract a method or a function.

I've read here and elsewhere about the differences between the two and understand that a method is connected to a class while a function is not. So I'm not looking for definitions, please.

Assuming that no arguments are involved, when is it appropriate to use one instead of the other? I understand that if something isn't really about the class then it could be a function but again, that's just about the definitions. I'm looking for good ol' use cases.

In my personal case, I'm trying to refactor some code out of the AppDelegate's applicationDidEnterBackground. As it is the only place to handle events upon entering the background, the only way to clean up the code is to extract subroutines into .. well, functions. But they'd be inside AppDelegate.m so wouldn't they be methods?

Hmmm..

like image 218
ari gold Avatar asked Jun 01 '13 03:06

ari gold


People also ask

What is the difference between a function and a method in C?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.

How can you tell the difference between a function and a method?

Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again.

What are the three main differences between a method and a function?

Difference Between Function and Method:A function can pass the data that is operated and may return the data. The method operates the data contained in a Class. Data passed to a function is explicit. A method implicitly passes the object on which it was called.

What is the difference between a function and a method Swift?

Functions are the properties of structured languages. Methods are the properties of Object-oriented language. It is a self-describing piece of code. It is used to manipulate the instance variable of a class.


1 Answers

Personally, I only use functions if, and only if, the following two requirements are met:

  1. I use it so frequently within a given class, or throughout the project, that it warrants being generalized.
  2. It has no side-effects or context dependancies (none of that void *context mess).

In my opinion, C-style functions should only be used as a last resort or in cases where you truly need functional behavior within this kind of an application. Event handling is both application-specific, and context sensitive, so it's best if you left that alone and focused on refactoring common patterns out.

like image 178
CodaFi Avatar answered Sep 18 '22 16:09

CodaFi