Passing more than one parameter in a apex method as a single parameter from lightning component or refactoring the apex method.

,

In this post, we will see how to resolve the “CognitiveComplexity” Apex PMD error. Your apex method might be having more than one parameter. We will explore how you can make your apex method generic to get n numbers of parameters.

When working with Salesforce Apex and JavaScript, you might need to pass multiple parameters to an Apex method. However, the standard way of passing parameters can lead to PMD (“CognitiveComplexity”) errors. It also imposes limitations on the number of parameters that can be passed.

Suppose we have a JavaScript method, “mymethod,” that is passing three parameters: “param1,” “param2,” and “param3.” In the Apex class “mymethod” , getting more than 1 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
}

As a solution to this problem, we can use JSON.stringify in JavaScript to convert the parameters into a single string, and then use JSON.deserializeUntyped in Apex to convert the string back into the individual parameters.

We can modify the above example. We can have a JavaScript method, “mymethod,” that passes three parameters: “param1,” “param2,” and “param3.” In order to avoid PMD errors, we first convert these parameters into a single object, “params,” using JSON.stringify. This object is then passed as a single 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 => {
			
			});

In the Apex method, we use JSON.deserializeUntyped to convert the “paramsString” back into a map of objects. From there, we can access the individual parameters using the map’s “get” method. In this example, we use the “get” method. We assign the values of “param1,” “param2,” and “param3” to separate variables. However, these could also be used directly in 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');

}

Leave a comment