Unlock Groovy’s Default Parameters: From Simple Overloads to Performance Insights
This article explains Groovy’s default‑parameter feature, shows how to embed scripts and random values in defaults, demonstrates practical API‑testing examples, and compares the execution cost of using default values versus explicit arguments in a high‑iteration performance test.
Groovy allows method parameters to have default values, effectively providing overloads without writing multiple method signatures. When a caller omits such a parameter, the default is used.
Default Parameter Syntax
For a simple sum function, the traditional Java‑style declaration is:
/**
* int sum
**/
public static int add(int a, int b) {
return a + b;
}Adding a default value for a (e.g., 10) changes the signature to:
/**
* int sum
**/
public static int add(int a = 10, int b) {
return a + b;
}Script Support in Default Values
Groovy can evaluate expressions or call methods inside default values. For example, a greeting method can generate a random user name when none is supplied:
/**
* greet
**/
public static void sayHi(String user = "DefaultUser${StringUtil.getEmojis(2)}") {
output("Hello, FunTester user: " + user);
}Random Parameter Generation
In API testing, a parameter can be assigned a random value from a set, enabling varied request scenarios without manual enumeration:
/**
* get group user list
**/
public static void getUser(int group = random(1,2,3,4,5)) {
output("Fetched users for group $group");
}Performance Comparison
A micro‑benchmark runs one million calls to an add method, once using the default‑value version and once using a version without defaults. The script records the elapsed time:
public static void main(String[] args) {
def start = Time.getTimeStamp();
1000000.times {
// def i = random(1,2,3,4,5,6,7,8);
// add(i);
add();
}
def end = Time.getTimeStamp();
output(end - start);
}
/**
* test method
**/
public static int add(int a = random(1,2,3,4,5,6,7,8)) {
return a * a;
}Results show that using the default‑value version consumes about 3500 ms, while the non‑default version takes roughly 700 ms for the same number of iterations. Although the default‑value approach adds overhead, the extra cost is acceptable for many testing scenarios, and overall script maintenance benefits outweigh the performance penalty.
The article concludes that Groovy’s default‑parameter and script‑in‑default capabilities simplify test script writing, enable randomised input generation, and provide a flexible way to model realistic traffic patterns.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
