Making Objective-C Classes look Beautiful

Beauty is subjective. For me, an Objective-C class is beautiful if it is readable (I know what it is supposed to do) and maintainable (I can see what parts are responsible for doing what). I also don’t like to be thrown out of reading code by an unfamiliar idiom. Sort of like when you are reading a book and you read something that takes you out of the immersion and reminds you that you are reading.

You’ll probably get lots of different, mutually exclusive advice, but here are my thoughts.

  • Nothing wrong with private methods being in a private category. That’s what it is there for. If you don’t like the declarations clogging up the file either use code folding in the IDE, or have your extensions as a category in a different file.
  • Group related methods together and mark them with #pragma mark statements
  • Whatever code layout you use, consistency is important. Take a few minutes and write your own guidelines (here are mine) so if you forget what you are supposed to be doing you have a reference.
  • The controller doesn’t have to be the delegate and datasource you can always have other classes for these.
  • Use descriptive names for methods and properties. Yes, you may document them, but you can’t see documentation when Xcode applies code completion, where well named methods and properties pay off. Also, code comments get stale if they aren’t updated while the code itself changes.
  • Don’t try and write clever code. You might think that it’s better to chain a sequence of method calls on one line, but the compiler is better at optimising than you might think. It’s okay to use temporary variables to hold values (mostly these are just pointers anyway, so relatively small) if it improves readability. Write code for humans to read.
  • DRY applies to Objective-C as much as other languages. Don’t be worried about refactoring code into more methods. There is nothing wrong with having lots of methods as long as they are useful.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)