The very first thing I do even before implementing class or method is to ask: "How would I want to use this from the outside?"
I never ever, never begin by writing the internals of my classes and methods first. By starting of with an elegant public API the internals tend to become elegant for free, and if they don't then the ugliness is at least contained to a single method or class, and not allowed to pollute the rest of the code with it's smell.
There are many design patterns out there, two decades of coding have taught me that the only pattern that stand the test of time is: KISS. Keep It Simple Stupid.
Some general rules of thumb, for any language or environment:
- Follow your gut feeling over any advice you have read or heard!
- Bail out early!
- If needed, verify inputs early and bail out fast! Less cleanup to do.
- Never add something to your code that you do not use.
- An option for "reverse" might feel like something nice to have down the road.
- In that case add it down the road! Do not waste time adding complexity you do not need.
- Method names should describe what is done, never how it is done.
- Methods should be allowed to change their implementation without changing their name as long as the result is the same.
- If you can not understand what a method does from it's name then change the name!
- If the how part is complex enough, then use comments to describe your implementation.
- Do not fear the singletons!
- If your app only have one data model, then it is a singleton!
- Passing around a single variable all over the place is just pretending it is something else but a singleton and adding complexity as bonus.
- Plan for failures from the start.
- Always use for
doFoo:error
instead of doFoo:
from the start.
- Create nice
NSError
instances with end user readable localized descriptions from the start.
- It is a major pain to retrofit error handling/messages to a large existing app.
- And there will always be errors if you have users and IO involved!
- Cocoa/Objective-C is Object* Oriented, not **Class Oriented as most of the popular kids out there that claim to be OOP.
- Do not introduce a dumb value class with only properties, a class without methods performing actual work could just as well be a struct.
- Let your objects be intelligent! Why add a whole new
FooParser
class if a fooFromString:
method on Foo
is all you need?
- In Cocoa what you can do is always more important than what you are.
- Do not introduce a protocol if a target/action can do.
- Do not verify that instances conforms to protocols, is a kind of class, that is up to the compiler.