我正在使用“受保护”而不是“私人”,因为有一天我可能需要延长我的课程,这很糟糕吗?

发布于 2024-10-16 17:46:00 字数 172 浏览 4 评论 0原文

我注意到我的代码中有一个模式。我通常选择 protected,而不是 private 作为类中“隐藏”方法和字段的默认访问标签。我这样做主要是因为它为类的用户隐藏了类功能的细节,同时仍然为将来的扩展留下了空间。这种编码“策略”有什么缺点吗?

谢谢
通努兹

I have noticed a pattern in my code. I usually choose protected, rather than private, as default access label for "hidden" methods and fields in my classes. I mainly do this because it hides the details about the class functioning for users of the class, while still leaving space for extension in the future. Is there any drawback in this coding "policy"?

Thank you
Tunnuz

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

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

发布评论

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

评论(3

一场春暖 2024-10-23 17:46:00

一般来说,永远不要做某事,因为有一天你可能不得不实施或做 yadayada(这只会让生活变得复杂和痛苦,恕我直言……)。如果您有一个只能在其类中使用的方法,那么请将其设为私有。如果您必须通过继承来扩展它,请重新考虑可能需要从下面访问哪些函数。通常我无论如何都会为我的超类抽象方法,所以无论如何我都必须考虑何时何地需要什么。

忽略我所说的关于私有方法的一个很好的理由是,如果你想测试你的内部函数,即在单元测试中。在 C# 中,您可以允许另一个项目从外部查看您受保护的方法,以便您可以针对它们编写测试。

Generally speaking never make something because some day you might be having to implement or do yadayada (it just makes life complicated and miserable Imho..). If you have a method that should only be used within its class, then make it private. If you ever have to extend it by inheritance than reconsider which functions might have to accessed from bellow. Usually I anyway abstract methods to my superclass so then I anyway have to do the thinking of what will be needed when and where..

A good reason why to ignore what I said about private methods, is if you want to test your internal functions i.e. in a unit test. In C# you can allow another project to see your protected methods from externally so you can write tests against them.

篱下浅笙歌 2024-10-23 17:46:00

由于封装的原因,您应该选择 private 。在这个问题上我确实更喜欢保守的方法,我更喜欢私有访问修饰符,如果我确实期望一些扩展,那么我选择受保护的访问修饰符。选择 protected 修饰符而不是 private 并不是一个好习惯。

You should choose private , because of encapsulation. I do prefer conservative approach on this subject, I prefer private access modifier, if I do expect some extension then I choose protected access modifier. It is not good practice to choose protected modifier instead of private.

書生途 2024-10-23 17:46:00

我不认为有什么缺点。

  • 私有变量是仅对其所属类可见的变量。
  • 受保护变量是仅对其所属类及其任何子类可见的变量。

所以你的代码一切都应该没问题。这没有什么“不好”的。如果您可能扩展您的类,则受保护的属性绝对是正确的。

I don't think there's a drawback.

  • Private variables, are variables that are visible only to the class to which they belong.
  • Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.

So everything should be ok with your code. There's nothing "bad" about that. If you probably extend your class, the protected property will be definately right.

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