In this article, we will explore the resolution of the “CognitiveComplexity” Apex PMD error, specifically when encountering a situation where your Apex method has more than one parameter. We’ll discuss how to make your Apex method more generic to accommodate an indefinite number of parameters.
While working with Salesforce Apex and JavaScript, there are scenarios where you may need to transmit multiple parameters to an Apex method. However, the conventional approach to passing parameters can result in PMD (“CognitiveComplexity”) errors and constraints on the permissible number of parameters.
Consider a scenario where a JavaScript method, named “mymethod,” is transmitting three parameters: “param1,” “param2,” and “param3.” In the corresponding Apex class “mymethod,” the challenge arises when dealing with more than one parameter.
JS ------------------------ mymethod({param1: this.param1, param2: this.param2, param3: JSON.stringify(this.accList)}) .then(result => { }) .catch(error => { }); Apex ------------------------ mymethod(Integer param1, Boolean param2, Account param3){ // logic }
To address this issue, a viable solution involves utilizing JSON.stringify in JavaScript to transform the parameters into a singular string. Subsequently, JSON.deserializeUntyped in Apex can be employed to revert the string back into individual parameters.
Refining the previous example, let’s consider a JavaScript method named “mymethod” that initially passes three parameters: “param1,” “param2,” and “param3.” To mitigate PMD errors, the approach is modified by consolidating these parameters into a singular object, “params,” through JSON.stringify. This object is then transmitted as a solitary parameter, “paramsString,” to the Apex method “mymethod.”
JS ------------------------ const params = { param1: this.param1, param2: this.param2, param3: JSON.stringify(this.accList), }; mymethod({paramsString: params }) .then(result => { }) .catch(error => { });
Within the Apex method, we employ JSON.deserializeUntyped to transform the “paramsString” back into a map of objects. Subsequently, we can access the individual parameters by utilizing the map’s “get” method. In the given instance, the “get” method is employed to assign the values of “param1,” “param2,” and “param3” to distinct variables. However, these values could also be directly utilized within the method’s logic.
Apex ------------------------ mymethod(String paramsString){ Map<String,Object> values = (Map<String,Object>)JSON.deserializeUntyped(paramsString); Integer param1 = (Integer) values.get'param1'); Boolean param2 = (Boolean) values.get('param2'); List<Account> param3 = (List<Account>) values.get('param3'); }