function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kishan a 2kishan a 2 

can i make dml in constructor)? if its NO why?

Tad Aalgaard 3Tad Aalgaard 3
Yes you can perform DML in a constructor.
public class blah {
    public blah (){
        Integer i = [select count() from lead];
        System.debug(i);

        Lead l = new Lead();
        l.lastName = 'test';
        l.company = 'test';
        insert l;
    }
}


// run the following from developer console
blah b = new blah();

 
dandamudidandamudi
@Kishan,
We can make DML operations in Constructor,
1) Constructor is called each and every time whenever Page is loaded so DML in Constructor will slow down initialization of your object (Constructor to be as fast as possible and do only the work needed to load the page).
-- this point referes to only VF loading , but there is lot of other scenario's  constructors Plays role with out running Pageload. 
2) Some security issues.
Give me some scenarios related for security issues?
Ajay K DubediAjay K Dubedi
Hi kishan,
Yes, you can create DML operation in constructor.but problem is-
 - If you create DML in constructor then you DML calls every time when you Instantiate class.
 - Each time when you want the class instance DML will call automatically.
 - It is a bad practice when you work on the projects.
 - It will taken more time when your page load.
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi