Whats the point of accessing private variables through getter and setter (accessor) functions?

允我心安 提交于 2019-12-03 12:13:12

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 ;)

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).

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.

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.

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....)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!