在同一类的多种方法中使用相同内容时的代码效率

如果我有3种不同的方法本质上是在做同一件事,而只有能引起差异的查询语句,我应该学习和做什么。

例如,下面的代码有2种方法,并执行一些SOQL,DML和Email发送,本质上两者在基于某些条件下发送电子邮件的过程完全相同,下面简要说明我的代码; >

2个方法执行特定的查询以获得所需的结果,然后对它们进行迭代,然后在我放入if语句的迭代中进行如下操作

FOR(Contact cont : contacts){

            if(cont.account.accountCountry__c == 'ID') {

                template = LostWinBackID;
            } 

            if(cont.account.accountCountry__c == 'MX') {

                template = LostWinBackMX; 
            } 

            if(cont.account.accountCountry__c == 'PH'){

                template = LostWinBackPH;
            }

然后,下一行代码将基于返回的查询以pdf附件发送电子邮件,因为这两种方法均采用差异查询,所以我决定将它们分为2。

我想编写聪明的代码来防止像这样的重复代码行。

    public class automatedCommunicationNew{


    public List<OrgWideEmailaddress> orgWideMail = [SELECT Id FROM OrgWideEmailaddress];

    //Template for ID
    public EmailTemplate ExpiringContractID = [SELECT Id,Name,Description,Subject FROM EmailTemplate WHERE Name =: 'Contract renewal notice ID' LIMIT 1];
    public EmailTemplate DueInvoiceID = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Invoice due reminders ID' LIMIT 1];
    public EmailTemplate BlockingOutstandingID = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Invoice overdue ID' LIMIT 1];
    public EmailTemplate BlockingaccountID = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'account has been blocked ID' LIMIT 1];
    public EmailTemplate DeactivatingaccountID = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'account has been deactivated ID' LIMIT 1];
    public EmailTemplate LostWinBackID = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'lost win back Id' LIMIT 1];

    //Template for MX
    public EmailTemplate ExpiringContractMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: '9. Contract renewal notice' LIMIT 1];
    public EmailTemplate DueInvoiceMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: '10. Invoice Due Reminder' LIMIT 1];
    public EmailTemplate BlockingOutstandingMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: '11. Invoice overdue' LIMIT 1];
    public EmailTemplate BlockingaccountMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: '12. account has been blocked' LIMIT 1];
    public EmailTemplate DeactivatingaccountMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: '13. account has been Deactivated' LIMIT 1];
    public EmailTemplate LostWinBackMX = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'lost win back mx' LIMIT 1];

    //template for PH
    public EmailTemplate ExpiringContractPH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'New Renewal Notice' LIMIT 1];
    public EmailTemplate DueInvoicePH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Invoice Due in 2 Weeks' LIMIT 1];
    public EmailTemplate BlockingOutstandingPH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Blocking Outstanding' LIMIT 1];
    public EmailTemplate BlockingaccountPH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Blocking account' LIMIT 1];
    public EmailTemplate DeactivatingaccountPH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'Deactivated Contract' LIMIT 1];
    public EmailTemplate LostWinBackPH = [SELECT Id,Subject FROM EmailTemplate WHERE Name =: 'lost win back Id' LIMIT 1];


    public Id emailtemplate;
    public String templateDescription;              // The template description will be assigned to the Task Subject of the task
    public String templateSubject;
    public Id invPDFattachmemt{get;set;}
    public Attachment attach{get;set;}
    public EmailTemplate template;
    public List<Invoice__c> linv;

    public String senderName = 'xxx';
    public String defaultReplyEmailID = 'test@test.com';
    public String defaultReplyEmailPH = 'test1@test.com';
    public String defaultReplyEmailMX = 'test2@test.com';

    public void sendRenewalReminder(){
        String ReplyToEmail;

/**** Set Template ****/

        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Set<Id> ids = new Set<Id>();

/**** Set filters and conditions (recipients and criteria -> To:,When?,who?,why?) ****/
        List<Contact> licontact = [SELECT Id FROM Contact
                            WHERE ContactForContracts__c = TRUE     // only contacts that are marked to receive contract info
                            AND Email <> ''
                            AND account.ExcludeFromAutomatedSendouts__c = FALSE                 // Checkbox on account to exclude account from sendouts
                            AND account.Contractsigneduntil__c =: system.today() + 35           
                            AND 
                               (account.accountCountry__c = 'ID'
                            OR  account.accountCountry__c = 'PH'
                            OR  account.accountCountry__c = 'MX') 
                            AND account.TypeOfCompany__c = 'Agent / Broker' 
                            AND (account.LastRenewalNoticeDate__c <: system.today() OR account.LastRenewalNoticeDate__c =: null)];  // avoids multiple sendouts in case the method is called several times on the same day
        system.debug('aaa' + licontact.size());


/**** Start process ****/

        IF(licontact.size() >0){
            /**** Set parameters ****/
            List<Contact> contacts = [SELECT Id,accountId,account.accountManager__r.Email,account.accountManager__r.isactive,account.Owner.Email,account.Owner.isactive,account.Contractsigneduntil__c
                                            FROM Contact WHERE Id in: licontact];
            FOR(Contact cont : contacts){
                ids.add(cont.account.Id);
            }
            List<account> accounts = [SELECT LastRenewalNoticeDate__c FROM account WHERE Id in: ids];

            /**** Create emails ****/

            FOR(Contact cont : contacts){

                if(cont.account.accountCountry__c == 'ID') {

                    template = ExpiringContractID;
                } 

                if(cont.account.accountCountry__c == 'MX') {

                    template = ExpiringContractMX; 
                } 

                if(cont.account.accountCountry__c == 'PH'){

                    template = ExpiringContractPH;
                }

                emailtemplate = template.Id;
                templateDescription = template.Description;              // The template description will be assigned to the Task Subject of the task
                templateSubject = template.Subject; 

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                mail.setTemplateId(emailtemplate); 
                //mail.setSenderDisplayName(senderName);
                mail.setOrgWideEmailaddressId(orgWideMail[0].Id);
                mail.setTargetObjectId(cont.Id); 
                mail.setWhatId(cont.accountId);

                /**** Set the email address to which the clients replies 
                      ** Aftersales manager by default
                          ** account Owner if AS is inactive
                          ** default email address otherwise                    ****/
                IF(cont.account.accountManager__r.Email <> null && cont.account.accountManager__r.isactive == TRUE)
                   ReplyToEmail = cont.account.accountManager__r.Email;
                ELSE IF(cont.account.Owner.Email <> null && cont.account.Owner.isactive == TRUE)
                   ReplyToEmail = cont.account.Owner.Email;
                ELSE IF(cont.account.accountCountry__c == 'ID')
                   ReplyToEmail = defaultReplyEmailID; 
                ELSE IF(cont.account.accountCountry__c == 'PH')
                   ReplyToEmail = defaultReplyEmailPH; 
                ELSE
                   ReplyToEmail = defaultReplyEmailMX;      
                mail.setReplyTo(ReplyToEmail);       

                mails.add(mail);
            }

            system.debug(mails.size());
            system.debug(mails);

        /**** Send emails ****/
            IF(mails.size() >0){
                Messaging.sendEmail(mails,false);

                /***** updates account date of last sendout to avoid multiple sendouts ****/
                FOR(account acc : accounts){
                    acc.LastRenewalNoticeDate__c = system.today();
                }

                update accounts;
            }
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    

       public void sendLostWinBackEmails(){
        String ReplyToEmail;

/**** Set Template ****/

        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Set<Id> ids = new Set<Id>();

/**** Set filters and conditions (recipients and criteria -> To:,why?) ****/
        List<Contact> licontact = [SELECT Id FROM Contact
                            WHERE ContactForContracts__c = TRUE     // only contacts that are marked to receive contract info
                            AND Email <> ''
                            AND account.ExcludeFromAutomatedSendouts__c = FALSE                 // Checkbox on account to exclude account from sendouts         
                            AND account.accountCountry__c = 'ID' 
                            AND account.TypeOfCompany__c = 'Agent / Broker' 
                            AND account.LostSince__c <: system.today().addmonths(-3)
                            AND account.SalesStage__c = '00. Lost Win Back'];  // avoids multiple sendouts in case the method is called several times on the same day
        system.debug('aaa' + licontact.size());


/**** Start process ****/

        IF(licontact.size() >0){
            /**** Set parameters ****/
            List<Contact> contacts = [SELECT Id,account.Contractsigneduntil__c
                                            FROM Contact WHERE Id in: licontact];
            FOR(Contact cont : contacts){
                ids.add(cont.account.Id);
            }
            List<account> accounts = [SELECT LastRenewalNoticeDate__c FROM account WHERE Id in: ids];

            /**** Create emails ****/

            FOR(Contact cont : contacts){

                if(cont.account.accountCountry__c == 'ID') {

                    template = LostWinBackID;
                } 

                if(cont.account.accountCountry__c == 'MX') {

                    template = LostWinBackMX; 
                } 

                if(cont.account.accountCountry__c == 'PH'){

                    template = LostWinBackPH;
                }

                emailtemplate = template.Id;
                templateDescription = template.Description;              // The template description will be assigned to the Task Subject of the task
                templateSubject = template.Subject; 

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                mail.setTemplateId(emailtemplate); 
                //mail.setSenderDisplayName(senderName);
                mail.setTargetObjectId(cont.Id); 
                mail.setWhatId(cont.accountId);
                mail.setOrgWideEmailaddressId(orgWideMail[0].Id);

                /**** Set the email address to which the clients replies 
                      ** Aftersales manager by default
                          ** account Owner if AS is inactive
                          ** default email address otherwise                    ****/
                IF(cont.account.accountManager__r.Email <> null && cont.account.accountManager__r.isactive == TRUE)
                   ReplyToEmail = cont.account.accountManager__r.Email;
                ELSE IF(cont.account.Owner.Email <> null && cont.account.Owner.isactive == TRUE)
                   ReplyToEmail = cont.account.Owner.Email;
                ELSE
                    ReplyToEmail = defaultReplyEmail;      
                mail.setReplyTo(ReplyToEmail);       

                mails.add(mail);

                if(Limits.getQueries() >= Limits.getLimitQueries()){
                    break;
                }
            }

            system.debug(mails.size());
            system.debug(mails);

        /**** Send emails ****/
            IF(mails.size() >0){
                Messaging.sendEmail(mails,false);

            }
        }
    }
}

期待听到代码专家的意见。

zy19890512 回答:在同一类的多种方法中使用相同内容时的代码效率

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3161691.html

大家都在问