58

I understand it is a very basic concept in the oops. But still I cannot get my head around. I understood why member variables are private, so class user cannot abuse it by setting up invalid values.

But how can this apply to the methods ?

4
  • 3
    To prevent the programmer from writing public methods that scroll forever in the vertical direction. You need private methods to break your public method implementations into readable/maintainable/cohesive/reusable(DRY) chunks - each chunk ideally being a private method with an intention revealing name.
    – Gishu
    Apr 12, 2010 at 8:34
  • 1
    It's important to point out that most times you probably don't actually want a private method, but a protected method. (Difference)
    – rinogo
    Jan 26, 2018 at 18:55
  • 1
    @rinogo That’s true in Java and C++, but not in all OO languages (or even most). There is little uniformity across languages for what, if any, difference exists between private and protected. Aug 5, 2020 at 20:38
  • It's not to break up public methods into more readable chunks. That can be done with more public methods, meaning the "privateness" of a method would be meaningless. The purpose of private methods rather is a) to help reduce the size of an object's public API and b) to indicate what's safe to refactor. Nov 8, 2022 at 2:22

10 Answers 10

117

Lot of good answers, but maybe one more from a self-taught Java programmer as I went through all that by myself with a lot of pain ;)

Think about a Class as something seen from the outside, not as something you see internally. If you look at a Class from the outside, what you see?

Taking the clock as an example again, a clock can give you info about the current time and it can be set up to show the right time.

So looking at things from the outside, a clock is a machine that can do those two things; public methods we call them.

But we as constructors of this clock we know that before any time operation we have to switch from 23 to 11 on our display (it's that kind of clock), so we have to rearrange things internally a bit to do so. Changing from 23 to 11 works just fine for us in both cases - setting the clock and showing the current time - but we do it "on the side" as the user doesn't have to know about all that complicated math. These are private methods!

So our Clock Class could have two public methods (showTime and setTime) which are all that the user wants to see, and a private method (recountTime) that provides functionality for these public methods and are something that the user doesn't want to see.

So on the one hand, you should keep in mind that private is what won't be reimplemented and accessed by future programmers using your code (as was pointed at in the answers above). But private also means things done on the side, so the user don't see it. That's why we call the public methods a public interface - it's all the user will see from the outside.

For me it is helpful (I'm self-taught, so maybe it's not a very popular methodology...) to write down everything the users (real users and other Classes) will do with my Class (public interface with just public methods' signatures), then to write the signatures of private methods that I-the-implementer will use to accomplish the public goals that promised to provide to my users and then just fulfill it with code.

It can be helpful to keep in mind that the old C rule is still valid (as was expressed in 97 Things Every Programmer Should Know): a function/method should be just a few lines long, really!!

0
27

Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.

2
  • 2
    I'm not quite sure how private methods have any direct correlation to breaking tasks up or preventing duplication of code. What we are talking about here is method scope.
    – J.C.
    Apr 13, 2010 at 21:36
  • 4
    Suppose that you have a group of preconditions which you need to validate before calling various methods in your class, or a lock which needs to be acquired, or really any block of code which would be repeated in multiple methods, but has no sense outside of the class. This code is a perfect candidate for being put into a private method, exactly because it's repeated and has no sense outside of the class. This latter reason is about method scope.
    – uckelman
    Apr 14, 2010 at 8:45
10

Private = Free to modify

The whole issue is other people can't behave. Let me explain.

In a perfect world you would not gain anything by "hiding" stuff from others, you could make all your methods public, tell them which ones to use, and go have fun. But sooner or later someone will rely on a method you wrote, let's say a method that's meant to be internal, just for you, some low level stuff that you expected to be able to change anytime - alas, now you can't, because someone else is relying on it. You change it, and something else breaks. For no visible reason. Because someone didn't use your class as you advised, someone called your inner methods and you improved something in your code.

So the shortest takeaway:

Hiding methods is reserving the right to change them.

Public interfaces should not change, unless it's a major step, like a new version. But the inside world is your playground. No matter how you get things done, as long as you deliver the expected output, it's no one else's business.

So the biggest reason to make methods private is your own freedom. Some will say it's for "security" reasons, but nowadays your code is often visible/editable so obviously we're not talking about access levels here. It's there, but it's not recommended to use. That's what private (and protected) means.

3
  • Suppose you make your method private, and expose a public method to fellow programmers that connects to the same private method. Now, Even if we make a change to the private method, it can still break things as others still rely on the public method that internally connects to the private method. Please answer
    – wayne
    Jul 4, 2023 at 7:57
  • Also, can you please provide examples of how someone can use our classes not in the way we advised?
    – wayne
    Jul 4, 2023 at 7:58
  • 1
    @user2488801batman - "it can still break things", yes, but it's your responsibility not to. It's inside your class. Your public method will know how to call the private one. Trivial example would be modifying the function arguments' order, or their defaults; now you can still call them the right way because you know you changed them. But someone else's code would break if they call the altered version directly. Hope this clarifies the situation.
    – dkellner
    Jul 4, 2023 at 13:41
9

Methods are (also) used to structure code, and I don't want the internal structure of my implementation to leak out through the interface. Often I have a method which to the outside seems to do a single task, but actually has to perform a couple of smaller tasks. In such cases I make one small private method for each of the subtasks and call them from the publicly visible method.

2
  • I agree, and I would say that this is also the main reason for having private member variables too. The fact that you then can validate any changes to them to avoid invalid values I see as a byproduct of this. Apr 12, 2010 at 8:37
  • Visibility is not a main feature of "private" of this access modificator. "protected" is also hidden from public access.
    – l00k
    Feb 17, 2018 at 4:47
7

For exactly the same reason - some methods are only intended for use inside the class, and use by non-class objects would be abuse. Think of methods that increment and decrement an object count for the class - these should only be called from a class's constructors or destructor, and so should be private.

4

Well in some cases you want only that specific class to use a method, and protect it from being used by any other class.

Just an example to show how it can be used:

You have a class Clock, it runs and runs keeping track of the time and date. You can get the time or date from it trough public methods. But the clock has to be right. so you can't adjust the time or date from outside of the class. But the clock itself needs to be able to adjust the time (daylights saving time for example)

In this case the Clock will have a private method to adjust the time.

Then you also have an additional pro, which is structuring the code. You can split up your code in smaller private methods which structure the code but prevent them from being used outside your class.

3

Methods that are private can only be called by methods within the same class or within the same "module". Methods are not commonly made private; usually they're made protected so that children can call them, or public so that other code can call them.

2
  • "so that children can call them" - best answer IMO. "private" access modificator makes child class to not inherite method / variable. This is main difference between private and protected.
    – l00k
    Feb 17, 2018 at 4:50
  • @l00k That’s true of Java. Other OO languages have very different visibility rules, even if they use the same terms as Java does. Jul 28, 2020 at 21:39
2

Having all other answers in mind. It is worth to remember that private method are only a tip for a programmer in many languages. In most cases it is still possible to use private method. For example by creating an object that inherits from object with private method and overrides its method with new public method.

In some modern highly object oriented languages private methods exist only by convention. Method with '_' on beginning is considere to be private.

1

Private methods are those methods which can’t be accessed in other class except the class in which they are declared. We can perform the functionality only within the class in which they are declared. But in C++ they can also access by Friend class.

Public methods are those methods which can be accessed in any class.

Protected methods are those which can be accessed in derived class too.

Thanks

0

Private methods can also be useful for breaking down a larger method into smaller, more manageable pieces. By breaking a method into smaller private methods, the code can be made more modular and easier to understand, since each private method only has a specific, well-defined responsibility.

Here's a sample example

public class Calculator {
    private int add(int x, int y) {
        return x + y;
    }

    public int calculateSum(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum = add(sum, num);
        }
        return sum;
    }
}

The Calculator class contains a private method, add, which performs the addition of two integers. This method is invoked internally by the public calculateSum method, which is responsible for computing the sum of an array of numbers. By defining add as private, the Calculator class ensures that other classes cannot access or modify this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.