• Post Reply Bookmark Topic Watch Topic
  • New Topic

public, private, protected, or package - I don't know... do you?  RSS feed

 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper Young wrote: . . . spaghetti code . . .
That's a nice article, particularly the pictures.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!