What is the practical difference between declaring a private vs public function?

So, since I read / studied classes and methods inside them, I found very little about the practical differences between a method declaration, both public and private.

I know that the difference in a private class can only be accessed inside the class, while the public method can be accessed from code outside the class (other classes, functions). But I really want to know:

  • Why do you want / don't want to declare it anyway when you deploy the application?
  • Are there better methods that can determine if a public vs private method should be declared?

Also, I don't know if this matters, but I mostly study VB.Net and C # in a web application environment, so this will help.

+5
source share
4 answers

Encapsulation means that you should think of each class as a machine that provides a service. For example, a chair allows you to sit on it, or a lawn mower allows you to cut your lawn.

private methods relate to the internal operation of the machine. In contrast, public methods relate to how you (other classes) interact with the machine.

Example One: Chair ...

When you are sitting on a chair, you do not need to know the amount of filling or the amount of paperclip, you basically need to know whether it is busy or not, and if it is stable.

  • Public Methods: IsStable, IsOccupied, Sit
  • Private Methods: CalculateStuffingVolume, CountNumberOfStaples

Example Two: Lawn Mower ...

, ( ), .

  • : GetFuelLevel, IsBladesSharp, TurnOn, TurnOff
  • : Combust .. , .

:

, , , ...

: . , . . ,

: .GetFuelLevel, ., ., .

uphosltry, , . , . , , . , Person Lawnmower.Combust(), .

+8

, , .

, ( ) . , ( , , , ), , - .

+4

- - encapsulation.

() . . ():

class Rectangle {
    private length;
    private width;

    public getPerimeter() {
        // return calculatePerimeterOld();
        return calculatePerimeterNew();
    }

    private calculatePerimeterOld() {
        // old variant
    }

    private calculatePerimeterNew() {
        // Here the perimeter is caltulated.
        // so: perimeter = 2 * (length + width)
        // or so: perimeter = 2 * (length) + 2 * (width)
        // or maybe so: perimeter = length + width + length + width - (0.5 * length) + 2 * 0.25 * length)
        return perimeter;
    }

}

, . . - , , , mehod public. , private, " ", , .

. , (-s) /, . () .

+2

-, , .

, , , .

, , .

  • Public functions and methods are those that you create for third-party interaction with your software.
  • Private functions and methods are those that you create for the interaction of your software with itself.

But, again, if it is a one-time website maintained by a single developer, these differences are less important.

+1
source

All Articles