Here’s a situation that comes up quite often that never sits too easy with me. I thought I’d ask how others handle it.
Imagine if the handling of a demo=60 command line argument was done like this:
if DemoOptionSpecified() {
timeout = ReadInDemoTimeout();
DoDemoVersion(timeout);
} else
DoRealVersion();
DemoOptionSpecified() does some sort of grep on the argument string and return true or false.
ReadInDemoTimeout() also does some sort of grep, same string, and returns an integer.
Two greps doing two different things, but of course only a single grep is needed to do both. Two greps instead of one might not matter here, but in other scenarios, two database or Ajax calls might.
I don’t particularly like having DemoOptionSpecified() do anything more than seeing if the option is supplied. An additional capturing of the value would not be suggested by the method name.
I don’t particularly like the alternative of having a method called ReadInDemoTimeout() returning false if the demo option doesn’t exist, as I only want to hear about timeout values if the option is set. DoRealVersion() does not care about the timeout value.
I don’t feel there’s a good no-compromise clean-code pattern for this. Thoughts?
I don’t see any problem with having a method that does both – you just have to name it correctly:
You could even make it simpler, and have the method return the value, or null if the option was not set:
And then i’d make the method general-purpose:
I don’t see that as being a method which does two things. The one thing it does is “get the valueof the option if there is one”. You can then ask two questions about the result – is there one, and what is its value? – but that’s happening in the calling code.
If you insist on not bringing back the value unless it’s needed, how about injecting it?
But seriously, if i was reading your code and i saw anything other than the third version, i’d see overcomplication and start refactoring. The idiom of speculatively getting a value and dealing with null and non-null cases differently is very widespread (in Java, at least); no useful purpose is served by avoiding it in pursuit of some notional kind of purity.