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
Kalpesh_007Kalpesh_007 

how to reduce if else statements in apex code

Is it possible to reduce the if else statements in the below code, I am interested to know :-
if (engagementStatusSet.contains(CommonConstants.CONS_CONT_NEW) && engagementStatusSet.size() == 1) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONS_CONT_NEW));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONTACT_ESTATUS_UNRESPONSIVE) && engagementStatusSet.size() == 1) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONTACT_ESTATUS_UNRESPONSIVE));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONS_CONT_RECYCLED) && engagementStatusSet.size() == 1) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONS_CONT_RECYCLED));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONTACT_ESTATUS_DONOTCONTACT) && engagementStatusSet.size() == 1) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONTACT_ESTATUS_DONOTCONTACT));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONTACT_ESTATUS_BADDATA) && engagementStatusSet.size() == 1) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONTACT_ESTATUS_BADDATA));
				} 
				else if (engagementStatusSet.contains(CommonConstants.CONS_CONT_CUSTOMER)) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONS_CONT_CUSTOMER));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONS_CONT_PROSPECT)) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONS_CONT_PROSPECT));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONS_CONT_ENGG_STS)) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONS_CONT_ENGG_STS));
				}
				else if (engagementStatusSet.contains(CommonConstants.CONTACT_ESTATUS_APPROACHING)) {

					lstAccount.add(new Account (Id=accountId,Engagement_Status__c = CommonConstants.CONTACT_ESTATUS_APPROACHING));
				}

 
Raj VakatiRaj Vakati
You can use the switch statement 


https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_switch.htm
Akhil ReddyAkhil Reddy
Please use switch statements.

Also you can make it bit neat using engagementStatusSet.size() == 1 as control statmenet at beginning to group them.