Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to declaring a private property with a getter and setter?

I am reviewing another developer's code and he has written a lot of code for class level variables that is similar to the following:

    /// <summary>
    /// how often to check for messages
    /// </summary>
    private int CheckForMessagesMilliSeconds { get; set; }

    /// <summary>
    /// application path
    /// </summary>
    private string AppPath { get; set; }

Doesn't coding this way add unnecessary overhead since the variable is private?

Am I not considering a situation where this pattern of coding is required for private variables?

like image 630
AmoebaMan17 Avatar asked Apr 13 '10 17:04

AmoebaMan17


People also ask

What is the benefit of using properties with getters and setters?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.

Should getters and setters be public or private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

What will happen if setters and getters are made private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

Is it important to always define setters and getters for all the private variables?

It is not necessary to write getter or setter for all private variables. It is just a good practice. But without any public function you can not access the private data(variable) of the class.


1 Answers

That's like saying private methods aren't beneficial since they add unnecessary overhead and no one outside the class is going to use them.

Properties give you one point of contact between a variable and the rest of your code. In the future, you might want to add error checking or update some other value whenever the variable changes, and properties will let you do that.

like image 170
MikeP Avatar answered Sep 29 '22 11:09

MikeP