【问题标题】:Prevent coding multiple if/else statements with two changing expressions防止使用两个变化的表达式编写多个 if/else 语句
【发布时间】:2021-09-15 21:11:02
【问题描述】:

我是一名初级 APEX 开发人员(基于 Java 的语言),我想知道是否有一种有效的方法来编写条件语句,其中两个条件发生变化,而其余条件保持不变。

例如,在我下面的代码中,Countryy__c 将更改为英国、美国和加拿大(法国除外),并且对于这些国家/地区中的每一个,行业将从会计变为医学再到法律。同时,潜在客户类型和状态将始终分别保持为 outbound 和 open。此外,每个国家和行业组合都有一个唯一的“所有者 ID”。

也就是说,总共会有 12 个 if/else 语句,其中包含 12 个不同的 OwnerId。鉴于如果国家和行业的数量增加,将来代码维护起来会很混乱,有没有更好的编码方式?

    public static void changeOwnerToQueue(List<String> DeactivatedUserIds){
    
    List<Lead> leadList = new List<Lead>();
    List<lead> updatedQueue = new List<Lead>();
    
    leadList = [SELECT Id, OwnerId, Countryy__c, Industry__c, Lead_Type__c, Status from lead 
    where OwnerId IN :DeactivatedUserIds];
    
    for(Lead l : leadList){
        
    if(l.Countryy__c == 'France' && l.Industry__c == 'Accounting' && l.Lead_Type__c == 'Outbound' && l.Status == 'Open'){
            
            l.OwnerId = '00G5J000000pX41';
            updatedQueue.add(l);      


   }
      }   

【问题讨论】:

  • 在核心 java 中,我将使用嵌套映射 Map&lt;String,Map&lt;String,String&gt;&gt;,其中外部地图的键是您的国家,内部地图的键是您的行业映射到您的 OwnerIds 值。

标签: java salesforce apex apex-code


【解决方案1】:

在 Apex 中,这种映射最易于维护的模式是使用自定义元数据。您将创建一些自定义元数据类型 (MyOwnerMap__mdt),其中包含 Country__cIndustry__cOwner__c 的字段。您将创建自定义元数据记录来表示您的所有映射。然后,在您的代码中,您将提取该数据以创建一个 Map,使用自定义类作为键来表示 Country + Industry -> Owner 的唯一映射:


class OwnerMapKey {
    public String industry;
    public String country;

    public OwnerMapKey(String ind, String ctry) {
        this.industry = ind;
        this.country = ctry;
    }

    public Boolean equals(Object other) {
        if (other instanceof OwnerMapKey) {
            OwnerMapKey o = (OwnerMapKey)other;

            return this.industry == o.industry && this.country == o.country;
        }

        return false;
    }

    public Integer hashCode() {
        return (this.industry + this.country).hashCode();
    }
}


List<MyOwnerMap__mdt> ownerMapValues = MyOwnerMap__mdt.getAll().values();
Map<OwnerMapKey, Id> ownerMap = new Map<OwnerMapKey, Id>();

for (MyOwnerMap__mdt eachOwnerMap: ownerMapValues) {
    ownerMap.put(new OwnerMapKey(eachOwnerMap.Industry__c, eachOwnerMap.Country__c), eachOwnerMap.Owner__c);
}

然后,您可以轻松访问任何行业和国家/地区组合的所需所有者值。请注意,如果您的自定义元数据中缺少该条目,您可能需要回退。

someRecord.OwnerId = ownerMap.get(new OwnerMapKey(SOME_INDUSTRY, SOME_COUNTRY)) || defaultOwner;

(免责声明:以上代码直接在 Stack Overflow 中编写且未经测试)。

此模式有价值的原因是您的解决方案随后变得可管理员维护:您可以更改映射而无需更改代码和部署,只需更改自定义元数据记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2020-10-29
    相关资源
    最近更新 更多