在类中使用 getter-setter

发布于 2024-10-13 08:11:35 字数 40 浏览 5 评论 0原文

在任何情况下都应该在类中使用类的 getter-setter 吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深海蓝天 2024-10-20 08:11:35

getters setters 一般用于从类外部直接访问字段。
主要优点/目的是 getter setter 的封装,

如果您的 getter setter 有一些逻辑代码,那么就使用它。

例如:

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

另请参阅

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

把梦留给海 2024-10-20 08:11:35

是的,getter 和 setter 很有用。由于 PHP 不支持简单类型(如 int 或 string)的类型提示,因此您无法强制值具有正确的类型。

通过使用设置器,您始终可以检查设置的值。当设置为 int 属性的值不是 int 时,您可以选择对其进行类型转换或引发错误,而不是仅仅接受错误的值。

这将使您的应用程序的调试和维护变得更加容易。因此,使用 getter 和 setter 是个好主意,即使它们除了这些检查之外不包含太多逻辑。

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.

半仙 2024-10-20 08:11:35

@GolezTrol

主题上没有 PHP 徽章,你错了。你所描述的与设置者无关。您可以使用任何方法强制输入参数(在 PHP 中),而不仅仅是 setter。

您可以写:

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

或只是:

  iAmMethodNotASetter( X $x, Y $y){

    //20lines of code here end then:

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

就像您所看到的,我不需要设置器来强制对象属性中的类型。

无论如何,在检查变量类型后在 setter 中抛出错误是个坏主意。这是从静态类型语言转换到动态类型语言的程序员的常见错误。

setter 和 getter 是约定,他们不会强制执行任何操作!
今天我们通常使用它们来创建普通的旧 Java 对象。 (POJO - 在 php 单词 POPO 中)所以它只是创建可以在库或项目之间使用的对象的约定(标准)。

您可以将 setter 与类型检查或其他任何方式结合起来,但这不会使它们变得更加复杂。

关于封装:

@org.life.java - Jigar Joshi

“主要优点/目的是
getter setter 的封装,“

@Peter Alexander

“你应该使用吸气剂
几乎到处都有二传手,
包括在“类”内。如果你
不,那么你有可能
破坏封装”“吸气剂和
setter 是封装”

错,错,错封装与 getter 和 setter 无关,这是很常见的错误。我知道有很多文章重复了这一点,整体颠倒了...
getter 和 setter 对封装没有帮助,更糟糕的是,它们可能会破坏封装。当您使用它们从对象获取一些数据而不是要求对象使用其自己的数据为您做某事时,它们就会这样做。

封装==对象对其数据承担全部责任,并且不提供其行数据。私有财产的 getter 只不过是以复杂的方式公开该财产 == 制动封装。

检查段落封装: http://en.wikipedia.org/wiki/C%2B%2B http://en.wikipedia.org/wiki/Encapsulation_%28computer_science% 29
甚至没有一个关于 setter 或 getter 的字......

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

夜雨飘雪 2024-10-20 08:11:35

您应该在几乎所有地方使用 getter 和 setter,包括在类内部。如果不这样做,那么您可能会破坏封装,更糟糕的是,您可能会使不变量无效。

作为 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;
};

看到错误了吗? transfer 提款,但不会增加 m_withdrawals。如果它只是调用withdraw而不是手动减少余额,这种情况是可以避免的。

这同样适用于 getter 和 setter。例如,吸气剂延迟初始化其值的情况很常见。如果另一个成员函数尝试直接访问未初始化的成员,那么您将得到空指针取消引用。

本质上,只要 getter 和 setter 提供了所需的功能,您就应该始终尝试使用它们。你做的低级事情越多,你遇到的低级错误就越多。如果您不打算使用 getter 和 setter,那么编写它们就没有意义。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文