Whats the point of accessing private variables thr

2019-03-25 16:42发布

In classes, variables are often made private for encapsulation, and to limit the variables to a certain scope allow better error control and fewer bugs. This makes sense, as the fewer places a variable can be accessed the fewer places a bug can occur with that variable.

However, I always see variables made private, and then a getter and setter function used to retrieve that value (sometimes even a pointer to that variable!). For example int a is private to prevent public access, but then getA() and setA() allow direct access to them.

So don't getter functions and setter functions defy the point of it being private? I mean private variables with accessor function are the same as public variables, only the code to access them changes. (object.variable vs object.getVariable())

Is there a reason people make variables private with accessor functions? Are there any advantages when compared to making it public?

I am talking about programming in general, but mostly in C languages (i.e. C, C++, C#, Obj-C).

6条回答
萌系小妹纸
2楼-- · 2019-03-25 17:05

Because if you change the internal representation of that variable or want to do more when it's set or retrieved, it won't break all the other classes that use it (and if it's a library, you don't have to change your API).

It also means you can easily set a breakpoint to see when it gets used (although most languages/debuggers have data breakpoints of some sort).

查看更多
3楼-- · 2019-03-25 17:05

Why was encapsulation required? Why was oop required? Wasnt C programming language capable of doing what we do today? Ask this to yourslef. Or if you have worked on huge systems having millions of lines of code. And all you used was public variables of a crucial data structure accessible from every module of the program.

查看更多
别忘想泡老子
4楼-- · 2019-03-25 17:19

I had the same question in mind when I started learning Object oriented programming because in most of the books they just make variable private and add public methods (Getter/Setters) to access them, So I was thinking if I can access that variable by methods that are public then what is point to make that variable private.

I get answer When I start implementing actual business Application.

Let's consider a class student which contain Student name, roll no, marks of 3 subjects

Class Student {

   private  int rollno;
    private int java_marks;
    private int cpp_marks;
    private int unix_marks;
    private int percentage;


    public int getJava_marks() {
        return java_marks;
    }
    public void setJava_marks(int java_marks) {
        if (java_marks > 100) {
            System.out.println("Marks value should be less than 100");
            //throw exception
        }
        this.java_marks = java_marks;
    }
    public int getCpp_marks() {
        return cpp_marks;
    }
    public void setCpp_marks(int cpp_marks) {
        if (cpp_marks > 100) {
            System.out.println("Marks value should be less than 100");
            //throw exception
        }
        this.cpp_marks = cpp_marks;
    }
    public int getUnix_marks() {

        return unix_marks;
    }
    public void setUnix_marks(int unix_marks) {
        if (unix_marks > 100) {
            System.out.println("Marks value should be less than 100");
            //throw exception
        }
        this.unix_marks = unix_marks;
    }
    public int getPercentage() {
        this.percentage = (this.cpp_marks + this.unix_marks + this.java_marks) /3;
        return percentage;
    }

    public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }

} 

Here make private variables because of 2 reasons

  1. Validation: if a user provides invalid value to marks then student object should not create with invalid data and throw appropriate error/Exception. In the case of marks as public varibles user can set any value to them , So I added validation/Security to ensure severy student object created is having correct data.

  2. Security In the case of percentage, user cannot set his own percentage. percentage is calculated and set internally. Here I do not Provide setter method for the percentage so User can only get/read percentage value by getter method.

This leads to security in abstraction that is only limited(read only) access to class variable.

查看更多
太酷不给撩
5楼-- · 2019-03-25 17:21

The key word and tag here is "encapsulation". You're hiding the details of a, while still making it usable. I like the reasons already listed, there are many more. Here's another, you're debugging, and you find a has an incorrect value. If a is public, you'd have to check every place a is accessed. If a is private with a setter method, you know the only place a could have changed is in a call to setA() - would be a great place to put a breakpoint ;)

查看更多
叼着烟拽天下
6楼-- · 2019-03-25 17:28

Maybe you will want to add some checks to the next version of the library (or to do something when someone read the value), and if the variable will be public in the current version, upgrade the library version will cost a lot of work.

查看更多
smile是对你的礼貌
7楼-- · 2019-03-25 17:28

Class defines the behavior and the members are the state of the object...so having a setter and a getter defines the encapsulation behavior of the class of letting others find/change the objects state.

In other terms the difference is something like letting your neighbour come into your house and take what he wants(making all the object in class public)....or making sure that the neighbour comes asks me on what he wants and I give him(having a getter/setter....)

查看更多
登录 后发表回答