属性和封装

发布于 2024-09-02 16:02:40 字数 177 浏览 5 评论 0原文

以下是有关在课堂上使用属性的问题。

我一直在使用公共属性而不是公开公开成员变量。大多数人认为这种方法有助于封装。但是,我不明白将其设为属性所带来的封装优势。

许多人不知道使用属性的真正原因。他们只是将其作为编码标准的一部分。

有人可以清楚地解释属性如何比公共成员变量更好以及它如何改进封装吗?

Following is a question regarding using properties in class.

I have been using public properties instead of exposing member variables publically. Majority advise that this approach helps encapsulation. However, I don’t understand the encapsulation advantage by making it a property.

many people donot know the real reason for using properties. They just do it as part of coding standard.

Can someone clearly explain how a property is better than public member variable and how it improves encapsulation?

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

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

发布评论

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

评论(4

云柯 2024-09-09 16:02:40

封装有助于使调用类免受更改。

假设您有一个简单的类来模拟汽车发动机(因为所有面向对象的示例都应该涉及汽车类比:))。您可能有一个像这样的简单字段:

private bool engineRunning;

简单地将此字段公开或提供 IsEngineRunning() getter 似乎没有任何不同。

现在假设您使您的类变得更加复杂,您想要删除该字段并将其替换为:

private bool ignitionOn;
private bool starterWasActivated;

现在,如果您有很多类访问旧的 engineRunning 字段,您必须去更改它们(糟糕的时候) )。

相反,如果您一开始是:,那么

public bool IsEngineRunning()
{
    return this.engineRunning;
}

您现在可以将其更改为:,

public bool IsEngineRunning()
{
    return ignitionOn && starterWasActivated;
}

并且类的接口保持不变(美好时光)。

Encapsulation helps by insulating calling classes from changes.

Let's imagine you have a simple class that models a car engine (cause all OO examples should involve a car analogy :) ). You may have a simple field like this:

private bool engineRunning;

Simply making this field public or providing an IsEngineRunning() getter doesn't appear to be any different.

Now suppose you make your class more sophisticated, you want to remove that field and replace it with:

private bool ignitionOn;
private bool starterWasActivated;

Now if you have lots of classes accessing the old engineRunning field you have to go and change them all (bad times).

If instead you had started with:

public bool IsEngineRunning()
{
    return this.engineRunning;
}

you could now change it to :

public bool IsEngineRunning()
{
    return ignitionOn && starterWasActivated;
}

and the class's interface remains the same (good times).

如果没有你 2024-09-09 16:02:40

最好公开属性而不是成员变量,因为这将使您能够在设置或获取成员变量的值时进行各种检查。

假设你有一个成员变量:

private int id;

并且你有一个公共属性:

public int ID
{
    get 
    { 
       // do something before returning
    }
    set 
    {
      // do some checking here may be limits or other kind of checking
    }
}

Its better to expose properties instead of member variables, because that would enable you to do all kinds of checking when setting or getting the value of the member variable.

suppose u have a member variable:

private int id;

and you have a public property:

public int ID
{
    get 
    { 
       // do something before returning
    }
    set 
    {
      // do some checking here may be limits or other kind of checking
    }
}
随风而去 2024-09-09 16:02:40

我会长话短说。 Properties=flexibility

1 属性对于创建您不想一直保留在类中的成员或现有成员的聚合/函数非常有用。

例如。可以根据生日输出age,canSwim可以根据hasLimbs &&生成;浮点

2 在处理具有现有数据库的系统中的意外更改 [有人预测过所有客户端的请求吗?] 时,将成员公开为属性会很有帮助。

例如。当用户超过 18 岁并缓存以提高性能时,isAllowed 为 true。客户希望在美国运行服务,如果缓存为 false,则可以返回 false,并且仅当缓存为 true 时才检查年龄

I'll make it short. Properties=flexibility

1 Properties are useful for creating members that You don't want to hold in a class all the time or that are aggregations/functions of existing members.

Eg. age can be output based on birthdate, canSwim can be generated from hasLimbs && floats

2 Exposing members as properties can be helpful when dealing with unexpected changes [did anybody ever predict all client's requests?] in systems with an existing database.

Eg. isAllowed is true when user is over 18yr and is cached for performance. Client wants to run the service in the US and You can return false if false is chached and check age only when cache is true

红焚 2024-09-09 16:02:40

一些想法:

  • 您可以更改数据的内部表示,而不会影响调用类。

    例如(之前)

    public boolean isActive() {
        返回 this.is_active;
    }
    

    (之后)

    public boolean isActive() {
        返回 this.is_active && this.approved && this.beforeDeadline;
    }
    

    如果您的代码被其他人使用(即您的代码是第三方代码),这一点尤其重要。在某种程度上,你的接口/API 必须保持稳定。小的更改不应影响使用它的其他代码。

  • 您可以进行更复杂的操作。考虑一个变量is_active。也许改变这个变量的值也会影响对象的其他属性。如果将访问封装在方法中,则可以在该方法中处理此问题,而调用者不必关心。

    例如

    public void setActive(boolean active) {
        this.is_active = 活跃;
        this.startTimeout();
        this.updateOtherInformation();
    }
    

    因此,它强制执行一系列特定的操作。您依赖调用者正确执行此操作的事实。您的对象将始终处于正确的状态。

Some thoughts:

  • You can change the internal representation of your data without affecting calling classes.

    E.g. (before)

    public boolean isActive() {
        return this.is_active;
    }
    

    (after)

    public boolean isActive() {
        return this.is_active && this.approved && this.beforeDeadline;
    }
    

    This is especially important if your code is used by others (i.e. your code is 3rd-party). To a certain degree your interface/API has to remain stable. Small changes should not affect the code of other code that uses it.

  • You can have more complex operations. Consider a variable is_active. Maybe changing the value of this variable also effects other properties of the object. If you encapsulate the access in a method, you can take care of this inside this method and the caller does not have to care.

    E.g.

    public void setActive(boolean active) {
        this.is_active = active;
        this.startTimeout();
        this.updateOtherInformation();
    }
    

    It therefore enforces a certain series of actions. You do not have rely on the fact that the caller executes this actions properly. Your object will always be in a correct state.

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