- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 09-27-2021 02:11 AM
Hello,
There are often times we write bunch of switch cases, or if else statements to evaluate multiple conditions and execute a code snippet which matches condition. Though its okay, but if you have multiple statements/logics inside your if-else or switch-case, and multiple conditions putting everything inside that would be cumbersome and sometimes lead to un-manageable or un-organized coding practice.
In cases like above (and in many other complex cases), what if we could invoke a single function and that function would decide and eventually call functions dynamically? Here, all our logics should be kept inside those small functions. In this way, this would make our code more simpler, readable and organized.
Let's see that how we could achieve this.
Script Include -
var DynamicCallingScript = Class.create();
DynamicCallingScript.prototype = {
initialize: function() {
},
_sudiptaFunction: function(myName) {
gs.info("DynamicCallingScript :: I am sudi " + myName);
},
_nitushreeFunction: function(myName) {
gs.info("DynamicCallingScript :: I am nitu" + myName);
},
_othersFunction: function() {
gs.info("DynamicCallingScript :: I am " + gs.getUserName());
},
execute: function(name) {
this[name]();
},
execute1: function(name, prm_xTra) {
this[name](prm_xTra);
},
type: 'DynamicCallingScript'
};
Background script -
callDynFun();
function callDynFun() {
var v_sCurrFName = gs.getUser().getRecord().getValue("first_name").toLowerCase();
var v_oDyn = new DynamicCallingScript();
if (v_sCurrFName == "sudipta" || v_sCurrFName == "nitushree") {
v_oDyn.execute1("_" + v_sCurrFName + "Function", gs.getUserName());
} else {
v_oDyn.execute1("_othersFunction", gs.getUserName());
}
}
In above Script Include, we have three different functions named _sudiptaFunction(), _nitushreeFunction(), and _othersFunction(). Now, each of those functions could have different logic inside it as per business need; however for time being and for our quick understanding, I just have one single statement inside each one of that.
Now, there are two more functions named execute() and execute1(). These functions are the generic functions and should be exposed to outer world.
In background script, we are calling execute1(), with a parameter, and one additional parameter. As the first argument here is dynamic (based on Logged in User's name), that means we are able to invoke one single function and that function invokes the actual function dynamically.
The above example can be extended further in many more complex scenarios. And I hope this would be of some help who would like to handle scenarios in this way.
Regards,
Sudipta
- 2,481 Views