I have noticed that the more I use Apex, and the more I come across other folks Apex code, that coding standards are really slacking. Sure there will always be folks who write SOQL code and DML method calls within for loops forcing us to bulkify that code, but the real problem is developing Apex code in a manner that is easy to understand and maintan for other developers.
Far too often I find business code slammed inside triggers, breaking sharing rules and just being downright hard to maintain and understand. Add to that some weird naming conventions on Apex classes and I get lost! Oh man, and I shouldn't even mention unit test methods bunched together into one giant test method, and/or a bunch of unit tests bunched into one class that aren't labeled clearly.
Pile on top of that the fact that Apex doesn't allow packaging (I.E. com.client.apex.data.xxxxxxx) so your left with a flat structure for all your code. How can one make this easy to understand and maintain? My brain is frazzled!
I have learned a few things and approaches I use so I thought I'd share. I'd love to hear what other ideas folks have for structuring their Apex code. These are just some guidelines I've used and they've worked on several projects to keep the organization clean.
1. Only have 1 trigger per object, and name it "ObjectTrigger". Inside the trigger, delegate calls to a "ObjectTriggerHandler" class based on the trigger context variables (trigger.isInsert for example).
2. For each Trigger, create a test class and call it "ObjectTriggerTest". Don't bunch up a bunch of different trigger tests into one huge test class and call it "TriggerTests". That makes it hard for another developer to quickly break down where the tests for a trigger are located.
3. Create multiple test methods inside your trigger tests. Don't lump up a bunch of test conditions into one huge test method. Clearly break out your test methods to test specific unit test cases and name them meaningfully. Then when another developer runs your tests, and one fails, they can see what exactly failed without running through a ton of code.
4. Break out your SOQL calls into data access objects and name them "ObjectDAO". This allows you to reuse SOQL calls in different classes.
5. Create a constants class and call it something like "ClientConstants". This allows reusue of constants and is easy for someone to look at and maintain those values.
6. Batch and schedule apex you can name "ObjectBatch" and "ObjectScheduler", with tests names "ObjectBatchTest" and "ObjectScheduler". Perhaps you see a patter to my naming evolving here?
If you follow the structure I've provided above, when another person comes into your org to look at your org they will see Apex code lined up cleanly and they will see the related objects grouped together (Triggers,Tests,Batch,Scheduled will all be next to each other for their corresponding objects).
Happy coding folks! And let me know if you have other ideas on structuring your orgs code!