本地使用私有字段 x 属性的最佳实践 [英] Best Practice on local use of Private Field x Property

查看:58
本文介绍了本地使用私有字段 x 属性的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在一个类中有一个私有字段并将该字段暴露在一个公共属性上时,我应该在类内部使用哪个字段?

When inside a class you have a private fiels and expose that field on a public property, which one should I use from inside the class?

下面是我试图找出的一个例子.应该操纵私有字段 _Counter 还是属性计数器?

Below you is an example on what I am trying to find out. Should manioulate the Private Field _Counter or the Property Counter?

公开课测试

Private _Counter As Integer

Public Property Counter() As Integer
    Get
        Return _Counter
    End Get
    Set(ByVal value As Integer)
        _Counter = value
    End Set
End Property

Private Sub Dosomething()

    'What is the best practice?
    'Direct access to private field or property?

    'On SET
    _Counter += 1
    'OR
    Me.Counter += 1

    'On Get
    Console.WriteLine(_Counter)
    Console.WriteLine(Me.Counter)

End Sub

结束课程

在此先感谢您的帮助.教育

Thanks in advance for the help. Edu

推荐答案

在我看来,在内部使用公共访问器是过度封装:它使代码变得模糊.使用这种方法,否则简单的操作会调用可能包含更复杂逻辑的访问器,因此更难分析操作的代码.

In my opinion, using a public accessor internally is over-encapsulation: it blurs the code. With such an approach, otherwise simple operations invoke accessors that may contain more complex logic, so it's harder to analyze the code of the operations.

在我的编程经验中,我很少遇到它会有很大帮助的情况.相反,我更喜欢直接访问字段,并且只有在确实需要时,才通过创建一个私有访问器来抽象访问,公共访问器和其他函数都可以使用它.理由是,如果您需要在公共访问器中附加一些特殊逻辑,则内部访问的逻辑可能不一样.

In my programming experience, I've rarely had a situation when it would help much. Instead, I prefer to access fields directly, and only if it's really needed, to abstract the access by creating a private accessor, which can be used by both the public accessor and other functions. The rationale is that if you need to attach some special logic in the public accessor, chances are that the logic may not be the same for internal access.

另请注意,大多数现代 IDE(如 Eclipse)允许立即查看对私有字段的所有引用,并重构代码以使用函数而不是直接访问.

Note also that most modern IDEs (like Eclipse) allow to see immediately all references to a private field, and to refactor the code to use a function instead of a direct access.

这篇关于本地使用私有字段 x 属性的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆