Alternatives To Pass By Reference

JavaPassesByValue. The idioms for doing PassByReference in Java are:

However, these smell bad.

Therefore: Look for alternatives that smell better:


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 FunctionalProgramming: Learn how to program entirely without SideEffects, then go back to Java and use SideEffects 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: http://www.haskell.org/tutorial/

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


CategoryJava JavaIdiom


EditText of this page (last edited September 1, 2005) or FindPage with title or text search