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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With