| Author |
public, private, protected, or package - I don't know... do you?
|
Rooks Forgenal
Ranch Hand
Joined: Jun 05, 2009
Posts: 82
|
|
Say I have some code like:
and it accesses code like this:
Do I make the second bit of code public, private, protected, or package? I don't believe anyone would want to access that particular method but maybe. Say they wanted to run the search from a custom 'root'. I don't know, I am just making that up. I am pretty sure they can't break anything if they ran it directly, so what do you think?
|
 |
Sebastian Janisch
Ranch Hand
Joined: Feb 23, 2009
Posts: 1183
|
|
You always want to hide most of the implementation of a class and only expose the necessary parts to the outside world.
If private static Node getNode(Node Root, Object obj) is only a helper function for the use of other functions in the same class, the private modifier is appropriate.
If you really think the function on it's own makes sense to expose to other classes, feel free to mark it public.
|
JDBCSupport - An easy to use, light-weight JDBC framework -
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12911
|
|
Indeed, keeping the public API of your classes as small as possible is an important design principle. This has to do with loose coupling. If all classes in your application knew all the details of all other classes, you'd have a big mess of spaghetti code, which is hard to understand and maintain.
So, a good rule of thumb is: Make member variables and methods private, unless you have a good reason to make them more accessible.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
That's a nice article, particularly the pictures.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12911
|
|
The Wikipedia article doesn't really go into spaghetti code in object oriented programming, but I just learned that that's called spaghetti with meatballs... (hmm, it's lunchtime here in half an hour...).
|
 |
 |
|
|
subject: public, private, protected, or package - I don't know... do you?
|
|
|