1

I found this article on how to read a file line by line, and it uses a function to read each line: Objective-C: Reading a file line by line

I'd like to increase my code reuse and put more code into smaller reusable pieces. Should I use Objective-C methods or functions? I'm talking about code that would be executed hundreds of times a minute.

Thank you!

Community
  • 1
  • 1
Alex Stone
  • 46,408
  • 55
  • 231
  • 407

2 Answers2

3

Choosing between methods and functions is never a matter of reusability, and quite rarely a matter of speed (anyway, hundreds of times per minute means several times a second, which is almost nothing).

The main points to consider are

  1. Will you prefer to think in functions doing something to objects or in objects doing something at your command?
  2. Are you going to inherit from the object and override its behaviour?

In case of reading file line by line I would suggest a simpler approach—unless of course you're doing an OOP assignment or doing OOP just for practice. It's not that as if there were anything wrong with OOP—it's a great technique, by all means use it when you need to model complex behaviour. It's just that for a simple script it's almost always an overkill.

alf
  • 8,377
  • 24
  • 45
  • Lets say I have a loop that needs to iterate over 3 differently named variables. When I was working in java, I would simply define a method method(variableA,VariableB,VariableC) with a certain return type and call that. This produced a very clean code, and allowed me to manage complexity. Somehow this got lost when I switched to objective C, because I'm not a C programmer and did not know when it was proper to use functions and not. I do not intend to override or reuse those functions in other classes, they are just for my own sanity! – Alex Stone Oct 18 '11 at 01:43
  • I use a simple technique based on [GRASP](http://en.wikipedia.org/wiki/GRASP_\(object-oriented_design\)) patterns — if I can assign responsibility to an object using any of the approaches listed, I write a method. If I cannot, a function is the way to go. – alf Oct 18 '11 at 09:36
2

Use classes and methods. Code reuse is one of the main goals of object oriented programming. Code reuse is also one of the main reasons for which Objective-C was invented, to add classes and methods to C, which only supported functions and thus no OOP.

rid
  • 61,078
  • 31
  • 152
  • 193
  • 3
    And how exactly does converting a function to an instance method improve code reuse? In particular, what code reuse improvement would there be in the OP scenario? –  Oct 18 '11 at 00:18
  • @Bavarious, from what I understand, the OP wants to "increase his code reuse and put more code into smaller reusable pieces", in general, not in a particular case. But please do correct me if I'm wrong. – rid Oct 18 '11 at 00:26
  • True; reading it again gives that impression as well. Now I’m not really sure what the question is. :) –  Oct 18 '11 at 00:28