Why is DML not allowed in Constructor?

DML is not allowed in a constructor. Is there a known reason behind this limit?

I have been searching for the answer & haven’t found anything which addresses the question. May be it’s not documented anywhere(Or google doesn’t know where it is).


The act of creation of object shouldn’t have immediate dangerous side effects. If I’ll create hundreds of your objects – will they all fire 1 DML?

This also holds true in Visualforce / any web context. The mere act of displaying some page (might be VF embedded in detail page layout, might be requested by some nasty Javascript like CSRF) shouldn’t cause say deletes to run. You can work around it with stuff like <apex:page ... action="{!afterCtorHook}"> but it would be caught for example in Salesforce security review.

User should understand what he’s doing (“are you sure you want to delete these 100 records?”), click something to confirm that this is really what he wants to do…

Check these too:

  1. http://wiki.developerforce.com/page/Secure_Coding_Cross_Site_Request_Forgery (actually have a look at all items from http://wiki.developerforce.com/page/Secure_Coding_Guideline, well worth a read).
  2. https://developer.salesforce.com/forums?id=906F0000000957bIAA
  3. Try submitting your app to security scan? The report should provide some examples & explanations of the vulnerabilities: http://wiki.developerforce.com/page/Security_Tools

Source : Link , Question Author : Ganesh Bhosle , Answer Author : eyescream

Leave a Comment