Considering using Java Variable Arguments

one day i came across this situation, we have a Java project (LoggerCore) which is a common project used by many other projects. I had to modify a method signature in LoggerCore project, but was afraid that i would end up cascading changes in all the projects to satisfy java compiler.
Started thinking that there should be someway to modify my project and common projects with out touching other projects which also use this common one. Suddenly it flashed while driving home, Java Variable Arguments.

Let us have look at the code snippets:


public SpringBrainLogger logIt(String referenceNumber) {
...
}

This is the original method signature in LoggerCore project, if I have to pass extra information, i need to add new argument and add it through out its reference. How tedious? Easily error prone!


public SpringBrainLogger logIt(String referenceNumber, LogInfo... info) {
...
}

Intead, I considered doing this. I added LogInfo... info which is Java variable argument syntax.
Boon:
- Dont have to modify rest n number of projects, as java variable arg is treated optional. Yes, invoking it like logIt(String referenceNumber) in other project will compile happily.
- Just pass this extra argument from my project.
- We can pass any number of LogInfo objects.

Be careful with the type of variable argument passed and consider doing proper checks like:

if (LogInfo.class.isInstance(info[0])) { ... }


Thank you Var Args!

Comments

Popular posts from this blog

Spark Cluster Mode - Too many open files

Binary Data to Float using Spark SQL

HDFS filenames without rest of the file details