Create Privately Publish Later

I've been thinking about how to manage dependencies in Java code...

I've noticed myself creating all new methods with the least visibility that can be justified (preferably private) on the basis that it's easy to widen visibility, but more difficult to reduce the visibility of a feature in working code.

Reducing the visibility would mean finding all the code that depends on that feature, checking whether those code blocks can still see the feature with its new visibility, and and making adjustments to code that used to access the feature which now can't. Some people will build it all and see what's been broken, some people will get as far as UnitTests - but it's difficult to ensure you found all the dependent code blocks.

The fewer code blocks depend on a feature, the easier it should be to optimise and refactor, because we minimise opportunities for unnecessary access to the feature.

When you see a method marked "public" in code built this way, at least you know it needs to be accessible in its own class, in its descendants and in code from other packages. In short, you know the visibility is determined by need rather than speculation.

Does anybody else work this way? Does anybody disagree?

-- DafyddRees


I do this too. -- CurtisBartley

Me too. -- WayneConrad

Me too. MethodsShouldBePublic has an opposing view. -- DaveHarris

In general I agree, too. BankOfEngland has an opposing view. -- OliverRode

I prefer explicit parameter passing between methods in a class instead of sharing the private variables within a class. This helps us during the refactoring, if we decide to move the method to a different class. Also note that the least visible variable is one that is declared inside a method (and not the private variable). Whenever possible declare variables with the minimum scope. For instance, a private variable which is used by only one method can be moved to inside the method. -- Bala Paranj

I think this was a mistype and what was meant was creating features (i.e. methods) private at first and slowly loosening their scope as needed. If so, I do this as well. However, I have to say that I do so much programming with interfaces that I rarely have the chance since you can restrict visibility of an existing feature in Java (I suppose this is to support the LiskovSubstitutionPrinciple). I rarely add a feature, private or public, unless I'm really backed into it and have no other choice. I rarely add a feature based on an anticipated need - I really have to be forced to add it. -- RobertDiFalco

See also: YouArentGonnaNeedIt, JavaIdioms


CategoryJava
EditText of this page (last edited January 14, 2003)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006