Reputation: 4348
I have to create an instance of class BenchmarkOption
based on the command line arguments. I certainly use pojo style, but this is not immutable. So I use Builder Pattern of Java style. Here is the class I implement :
object CommandLineHelper {
//TODO: use configuration file ?
val MILLI_SEC_SEPERATORS = 0 + "," + Int.MaxValue
val SBE_ID = "SBETEST5";
val SBE_PSW = "GZ@API53";
val NUM_OF_REQUESTS = 1
val NUM_OF_WORKERS = 1
val PAUSE_IN_MILlI_SECOND = 1L;
}
class BenchmarkOption private {
import com.ggd543.mulerestletdemo.{CommandLineHelper => CLH}
private var _msSeperators = CommandLineHelper.MILLI_SEC_SEPERATORS
def msSeperators = _msSeperators
private var _nOfReq = CLH.NUM_OF_REQUESTS
def nOfReq = _nOfReq
private var _sbeId = CLH.SBE_ID
def sbeId = _sbeId
private var _sbePsw = CLH.SBE_PSW
def sbePsw = _sbePsw
private var _pauseInMilliSec = CLH.PAUSE_IN_MILlI_SECOND;
def pauseInMillSec = _pauseInMilliSec
private var _dataFile = new File("./data.csv")
def dataFile = _dataFile
// may be too many fields
}
object BenchmarkOption {
def newBuilder() = new Builder
class Builder {
private val bmo = new BenchmarkOption
def buildBenchmarkOption = bmo;
def msSeperators_=(s: String) = bmo._msSeperators = s
def msSeperators = bmo._msSeperators
def nOfReq_=(n: Int ) = bmo._nOfReq = n
def nOfReq = bmo._nOfReq
def sbeId_=(s: String) = bmo._sbeId = s
def sbeId = bmo._sbeId
def sbePsw_=(s: String ) = bmo._sbePsw = s
def sbePsw = bmo._sbePsw
def pauseInMilliSec_=(milliSec: Long) = bmo._pauseInMilliSec = milliSec
def pauseInMilliSec = bmo._pauseInMilliSec
def dataFile_=(file: File) = bmo._dataFile = file
def dataFile = bmo._dataFile
}
}
As you can see that the code is lengthy and not good at reading. I think there is an alternative to rewrite it . Any suggestion ?
Upvotes: 2
Views: 882
Reputation: 4348
How about this ?
class BenchmarkOption private {
protected val instance = new {
var msSeperators = CommandLineHelper.MILLI_SEC_SEPERATORS
var nOfReq = CLH.NUM_OF_REQUESTS
var sbeId = CLH.SBE_ID
var sbePsw = CLH.SBE_PSW
var pauseInMilliSec = CLH.PAUSE_IN_MILlI_SECOND;
var dataFile = new File("./data.csv" )
def buildInstance() = BenchmarkOption.this;
}
def msSeperators = instance.msSeperators
def nOfReq = instance.nOfReq
def sbeId = instance.sbeId
def sbePsw = instance.sbePsw
def pauseInMilliSec = instance.pauseInMilliSec
def dataFile = instance.dataFile
}
object BenchmarkOption {
def newBuilder() = new BenchmarkOption{}.instance
}
Upvotes: 0
Reputation: 16859
The Builder Pattern is built into Scala. Just use named constructor arguments and default values whenever possible. If there are too many arguments, then rethink your design. I bet there are plenty opportunities to group them somehow into proper data structures, thus reducing the number of constructor arguments.
Upvotes: 3
Reputation: 4932
I don't see why you can' just use constructor arguments - are all parameters not known from the start?
Upvotes: 1