
When your sharing requirements get complex enough that rules and role hierarchy can't handle them, you need to write code. This covers how Apex managed sharing works, the Share object structure, inserting and deleting shares correctly, and the operational details that will trip you up if you skip them.
Salesforce Security
OWD, sharing, profiles, permissions -- the full security model.