How would a private function work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How would a private function work?

I'm at the unit describing how public functions access private attributes within a class. What would the functionality of a private method be in the same class? I get the possibility that this may be further in the curriculum. If this is the case, please specify. In this as in any answer case, thank you for your instruction.

8th Oct 2018, 9:27 AM
Robert Groff
Robert Groff - avatar
3 Answers
+ 2
The function of a private function of a class((function of a class)= method) is that it is only accessable within the class itself. So you cannot access it directly from another class. To access these private variables you can make getters and setters. That are methods in the class to access the private variable of the class. In these getters and setters you can validate/test the input. The Single Responsibility Principle is what I usually have in mind: https://en.wikipedia.org/wiki/Single_responsibility_principle
8th Oct 2018, 9:48 AM
Willem Roos
+ 1
As I understand it, private access modifier indicates that the member (methods or attributes etc.) is only accessible/usable from within the scope where the member was declared, in a class in this case. So a private method can't be invoked from outside the class, unlike public methods. Functionality speaking I think private methods are used for processing data which are supposed to be hidden, the process (how it is done) or what values affecting the outcome should not be exposed, nor should the process be allowed to be executed deliberately from outside the class, the outcome of the process however, can be exposed, through a public member that is. Hth, cmiiw
8th Oct 2018, 10:04 AM
Ipang
+ 1
Robert Groff class are building blocks for build types then they would be used for make more complex types... This create a problem: like everything, types class can be updated also but what happen to code that use they (client code)? In this context, code mainly consist of two parts: interface and implementation. Interface is the part of code that client code can see (usually in classes are all public methods/props), implementation is the code that client has NOT need to know/worry about (usually private parts). Why this difference? Well, imagine thay you have some type that do some complex calculation and return they to client throught own interface. Now, suppose after sometime that you want implement some caching for optimize calculations. If, doing this, you dont change the interface (the public part), your client code can keep untouched. Obliviously your implementation have to change but because client have to dont worry about it (in coding terms), it HAVE NOT need to change own code
8th Oct 2018, 1:03 PM
KrOW
KrOW - avatar