November 8, 2016 by LanceShi
If you do these 6 things in Apex then nobody dies (Repost from LimitException.com)
There is a lot of advice in programmer land; much of it is labelled best practice or gentle encouragement in the form of a school teacher paternally lecturing their students.
This advice often mixes suggestions you ‘should do’ with other suggestions that will get you seriously hurt.
E.g. lists like:
- Call your mother.
- Obviously good advice and all of us who can should do that, but if you don’t you aren’t going to die (Although you may want to if she calls).
- Don’t eat saturated fats
- Also good advice, but the affect is not immediately obvious and its only over many years you may find it a problem
- Do not attempt to cut your toe nails with a chainsaw.
- Very clearly a bad idea and on a different level of wrong.
The trouble with programming is as a novice the list above can be difficult. Figuring out the nice to haves from the ‘this will kill you’ may not be obvious.
So I’ve decided to make it easier by giving 1 simple list:
Do not put SOQL in loops.
Not ever, no. Don’t. There is no excuse, it WILL cause your code to crash, it will turn up in code reviews (automated). People will find it and curse your name. Don’t do it. Ever.
Do not put DML in loops
Same as above. It will fail, it is slower, it helps no one except for you and the 5 minutes you ‘saved’ writing it.
Use asserts in tests.
No asserts, you didn’t write a test. No excuse, you’re just wasting your time and everybody elses.
Do not use (SeeAllData=true) unless Salesforce makes you.
Using existing data in an org is madness. It won’t work in a Sandbox, it won’t work if things change. The ‘making you’ disclaimer is related to the Chatter API which requires its use. Best case — don’t use the Chatter API in apex.
Use one trigger per object.
A few years ago I didn’t really get this rule, then I spent too much time in orgs with multiple triggers on single objects. It makes things unpredictable and unpredictable code is bad code. Bad code will hurt you.
Do not cut and paste code you don’t understand.
If your train of thought is ‘I think this does what I want, so I’m just going to copy it’ then you’ve done the programming equivalent of closing your eyes and walking into traffic. You should have your Ctrl/Cmd key removed. Stop it.
The final word…
Lets be clear, if you knowingly do any of the things in this list in Apex and thing ‘oh, it’ll be okay’ or worse ‘I don’t care’ then I think you are incompetent and you should find another job.
Harsh? Yes. But you’re being paid to do this, show some goddamn pride.
If you didn’t know you were doing something wrong then you should go back and read the list again.
Memorize it, print it out and do not forget.