Why is it a bad idea to write business logic in trigger. The organization that I work for asked me to move all the business logic in to apex class and call it in a trigger. Can anyone explain me why is that a best practice because it's the same logic.
Once I implemented this pattern, http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers , I never looked back.
Why did I never look back?
because I knew that every trigger
- Would be implemented by the exact same structural logic
- That I had a consistent approach to bulkification using gateway classes to collect related records
- That I never had to worry about order dependency of multiple triggers on the same SObject
- That I could easily introduce exception handling and limits monitoring in a single place that would benefit all my triggers
- That I could readily introduce wrapper classes on my SObjects to do operations in an OO way; it also made it easy to implement services that might need invoking from triggers - controllers - REST services - I wasn't tempted into locking up the service logic within a trigger
It is seductive to code up simple business logic in triggers and you'll see many examples of such in various forums, but over time, it grows unwieldy. Take the plunge and you'll never regret it.
As a code base evolves and extends it becomes valuable to introduce layers of architecture, abstractions and certain patterns to your code. That is the goal, not just moving code out of your triggers for the sake of doing only that.
Organizing a code base should aim for better maintainability and re-use of business logic, the prevention of bugs, easier debugging, separation of responsibilities, replace-ability by abstraction, and much more.
This is why many developers/companies use some sort of custom apex trigger framework, or even more advanced code architecture. There is an excellent blog about these things on the developerforce website by Andrew Fawcett: Apex Enterprise Patterns - Separation of Concerns
Code organization should not be overlooked. Just because your code works does not mean that it is complete, in my opinion. As your codebase grows, code entropy also increases, which down the line means what should have been a trivial change may end up taking days to complete and test.
This doesn't apply to just Apex code, but to any language you are coding in. I would suggest picking up the book Clean Code to get a good primer and start you on your journey to writing, as the book says, clean code.
Because trigger is hard to understand when you have much logic there. In my opinion trigger is place to manage methods and class is place to store them