. The idioms for doing PassByReference
in Java are:
However, these smell bad.
Look for alternatives that smell better:
- If you are using reference parameters to return multiple values, then UseObjectsToReturnMultipleValues instead. But, if the multiple values share behavior, then create a first-class object for them, not just a dumb data object.
- If your function is modifying a single value, then ReturnModifiedParameter instead.
Sometimes neither of those approaches work. Specifically, a complex public method may require multiple private methods and multiple local variables, and some of the private methods may update multiple local variables. That situation requires an ObjectContainingLocalVariables?
, which I create at the start of the public method and pass to each private method. ObjectContainingLocalVariables?
is a last resort, which I use when it's the only alternative to a LongMethod?
: Learn how to program entirely without SideEffect
s, then go back to Java and use SideEffect
s only when they make your program cleaner and easier to understand. You'll find that your style has changed quite a bit. But I've been trying for quite a few years to explain how it changes, and haven't figured out how to explain it yet. -- RalphJohnson
The book LittleJavaFewPatterns
(A Little Java, A Few Patterns
is a nice step along the way. I'm only half way through it, but it is definitely worthwhile if you are interested in seeing things from another point of view.
One other way to get a smattering of the ideas of FunctionalProgramming
is to read this little tutorial for the HaskellLanguage
Also, the book Functional Programming Practice and Theory
by Bruce MacLennan? ISBN 0201137445
is extremely good. I found that one in the library at my local university. -- MichaelFeathers