Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of making separate public functions for getting/setting a private value?

Let me just preface this by saying that I know this is probably a newbie quesion, I tried searching for it and I can't find a proper anwser for it (probbably asking it wrong).

So usually when I want to use another value outisde of its class, I just make it public and access it lik.

Yet often I see other code use private values in their class and then make separate functions for getting and setting the value like so:

private bool fooBar;

public void SetFooBar(bool boolean)
{
   fooBar = boolean;
}

public bool GetFooBar()
{
   return fooBar;
}

Excuse my ignorance but what exactly is the point of it? They both do essentially the same thing (by my newbie logic atleast). I know that private variables are useful in that it ensures you can't break the functionality of a program by modifying them elsewhere in the code, but you're modifying them elsewhere in the code anyway, so what gives? Why do I see people do this?

like image 440
Mathue24 Avatar asked Dec 07 '22 12:12

Mathue24


1 Answers

  1. Because directly modifying the state of an object is a no-no in OOP
  2. Because you can't put fields into an interface (and once you get far enough, you usually end up accessing most other objects through interfaces)
  3. Because it allows additional logic (like raising events) when another object wants to interact with the field
  4. Because certain things (like WPF bindings) only work with properties, not fields

  5. Because you may want to change how the value is retrieved/stored (not just in-memory) later

(Note that in C# you usually do this as a property, not methods, like public bool Foo {get; set;})

like image 192
BradleyDotNET Avatar answered Dec 10 '22 01:12

BradleyDotNET