Sometimes I’m building a class I want to have a reset function in. For instance
class DFA(val initialState:State) {
var states = Map[State,State]()
var currentState: State = initialState
reset
def reset {currentState = initialState}
}
Oops! Didn’t your DRY bells ring? I’m setting currentState to initialState twice. Once in reset and once in the constructor. I can’t just leave the vars uninitialized, or the compiler will complain.
Of course I could
class DFA(val initialState:State) {
var states = Map[State,State]()
var evilNullVariableWeMustNeverUse = null
var currentState: State = evilNullVariableWeMustNeverUse
reset
def reset {currentState = initialState}
}
but I think that the downside of this is obvious.
In this simple case, it’s not so bad, but if you have 5 variables, or more complex logic, it becomes obnoxious.
How can I design around this?
Maybe create a Resettable wrapper?
Then:
And:
The benefits can be seen with:
There is no need to store
0and"hi"in another variable in order to reset.