11

Should one use under any circumstances getters-setters of a class within the class?

Argiropoulos Stavros
  • 9,436
  • 11
  • 61
  • 79

4 Answers4

9

Getters setters are generally used from outside class from inside directly access the fields. The main advantage/purpose is encapsulation of getter setters,

If your getters setters has some logical code then use it.

for example :

public void setValue(int val){
  if(val > 100)
    this.val = 0;
  else
    this.val = val;
  }

Also see

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • @Geolez I don;t see PHP tag by OP, its the concept of OOP described here not specific to any language – jmj Jan 22 '11 at 10:53
5

Yes, getters and setters are useful. Because PHP doesn't support type hinting for simple types like int or string, you cannot force a value to be of the right type.

By using a setter, you always have the possibility to check the value that is set. When a value set to an int property isn't an int, you can choose to typecast it, or raise an error, instead of just accepting the wrong value.

That will make debugging and maintaining your application a lot easier. So it's a good idea to use getters and setters, even if they do not contain much logic other than these checks.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
2

@GolezTrol

There is no PHP badge on topic and you are wrong. What you are describing has nothing to do with setters. You can force type on parameter (in PHP) by using any method not only a setter.

You can write:

setX( X $x ){ ...}
setY( Y $y ){ ...}

or just:

  iAmMethodNotASetter( X $x, Y $y){

    //20lines of code here end then:

    $this->x = $x;
    $this->y = $y;
  }

Like you see I didn't need setters to enforce type in object properties.

And throwing error in setter after checking variable type is bad idea anyway. It is common error of programmers who transitioned from the language statically typed to dynamically type language.

Setters and geters are CONVENTION and they don't enforce anything! Today we usually use them for creation of Plain Old Java Objects. (POJO - in php word POPO) So it is just a convetion (standard) for creation of object that can by use between libraries or projects.

You can combine setters with type checking or whatever but it dosn't make them somthing more than they are.

About Encapsulation:

@org.life.java - Jigar Joshi

"The main advantage/purpose is encapsulation of getter setters, "

@Peter Alexander

"You're supposed to use the getters and setter almost everywhere, including inside "the class. If you don't, then you are potentially breaking encapsulation" "Getters and setters are encapsulation"

Wrong, wrong, wrong. Encapsulation has nothing to do with getters and setters and it is very common mistake. I know there is many articles repeated it over and over all upside down...
Getters and setters don't help encapsulation even worse, they may break encapsulation. They do so when you use them to get some data from object instead of asking object to do something for you with its own data.

Encapsulation == object is taking full responsibility for its data and dosn't give it's row data. And getter on private property is nothig more than making that property public in complicated fashion == braking encapsulation.

Chceck paragraph encapsulation: http://en.wikipedia.org/wiki/C%2B%2B or http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29 Not even one word about setters or getters...

smentek
  • 2,820
  • 1
  • 28
  • 32
  • From wiki: "[Encapsulation is] A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data." Getters and setters are the methods that are bundled into a class to operate on its data. Anyway, I gave you a -1 because you haven't answered the question and you only posted to harass the other answerers. Use comments for that. – Peter Alexander Jan 23 '11 at 11:38
  • +1.Although you are a bit edgy you are presenting an interesting point of view.I have to do a little more reading on this.thank you – Argiropoulos Stavros Jan 23 '11 at 23:08
  • I'm not wrong, wrong, wrong, only my answer might have been too specific for PHP. You are wrong, because you *cannot* enforce any type by using type hinting. Your 'X' hint will only work for classes and arrays, and in the case of an array there's still no hint of what should be *in* the array. Naturally you can do this with other methods too, but because you need the type checking code to be sure, you should always create a setter *and* always use that setter, even in methods within that class. But that's for PHP, most other languages are strong typed and don't need this for extra checks. – GolezTrol Jan 24 '11 at 06:56
  • And of course it is not a good idea to expose a private object of another object through a setter, but when it comes to more simple types this should hardly be a problem. I can expose an int through a setter in C++. And by making the setter virtual, I can decide for a descendant class to implement a different setter that doesn't even set the private variable. Now, sure you shouldn't create public setter for things you don't want to be set from the outside, but in a lot of cases it just makes sense. ... – GolezTrol Jan 24 '11 at 07:01
  • 1
    ... If I got a Person object, I'd like to set his age through a `setAge` method or an `Age` property. Is `setAge` a setter in this case? You can call it otherwise if you like, but I think it's just a matter of perception. If you feel safer by naming this function `setAgeByNotUsingSetter` then I think you're just fooling yourself. – GolezTrol Jan 24 '11 at 07:03
  • Besides, you're talking about my PHP answer, but I don't see any `encapsulation` tag in the question. :) – GolezTrol Jan 24 '11 at 07:04
1

You're supposed to use the getters and setter almost everywhere, including inside the class. If you don't, then you are potentially breaking encapsulation, and even worse, you could invalidate your invariants.

As a simple example in C++:

class BankAccount
{
public:
    void withdraw(int amount)
    {
        m_balance -= amount;
        m_withdrawals++;
    }

    void transfer(BankAcount& other, int amount)
    {
        m_balance -= amount;
        other.m_balance += amount;
    }

private:
    int m_balance;
    int m_withdrawals;
};

See the bug? transfer withdraws money, but it doesn't increment m_withdrawals. This could have been avoided if it simply called withdraw rather than manually decrementing the balance.

The same applies to getters and setters. For example, its quite common to have getters that lazily initialise their values. If another member function tries to access the uninitialised member directly then you're going to get a null pointer dereference.

Essentially, you should always try to use the getters and setters whenever they provide the functionality they want. The more low level things you do, the more low level bugs you are going to have. There's no point writing getters and setters if you aren't going to use them.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168