为什么不使用公共成员函数 [英] Why Not Use Public Member Functions

查看:125
本文介绍了为什么不使用公共成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我使类成员函数公开,它被
其他客户端应用程序使用,
函数的实现细节将永远不会暴露给客户端。为什么要使成员函数保护或私有?

Even if I make class member functions public and it is consumed by other client applications, implementation details of functions will never get exposed to client. Why make member functions protected or private?

例如,如果我的类是Math,使用public function sum(int,int b)暴露给客户端而不是实现。

For example, if my class is Math, with public function sum(int, int b) then only interface/declaration part will be exposed to client and not implementation.

public class Math
{
      public int sum(int, int b)
      {
               //Implementation
      }
}


public class Client
{
         Math objMath = new Math();
         objMath.Sum(4,10);//It will not display implementation inside sum than why to avoid
}


推荐答案

你的方法(和类型)越public,它们暴露的代码越多。这增加了其他代码(甚至您公司控制下的代码)将根据该代码以现在的方式开始开始的机会...这限制了稍后更改实现的灵活性。

The more public your methods (and types) are, the more code they're exposed to. That increases the chance that other code (even code under your company's control) will start depending on that code working the way it currently does... which limits the flexibility to change the implementation later.

为了给出一个具体的例子,我正在开发一个名为 Noda时间。现在我们还没有第一次公开发布,但是我最近一直在对各种内部类型进行修改 - 包括相当大地改变类型层次结构,甚至删除方法。如果那些是公共类型或公共方法(如果我们已经到了v1.0),那么我们可以破坏依赖于具体实现的代码。

To give a concrete example, I'm working on an open source project called Noda Time. Now admittedly we haven't had our first public release yet, but I've recently been making a load of changes to various internal types - including changing the type hierarchies fairly significantly, and even removing methods. If those had been public types or public methods (and if we'd already gone to v1.0) then we could have broken code which depended on that specific implementation.

通过隐藏您并不了解的一切,对客户有用,您会为自己购买很多弹性。在你的公共API中加入大量的思想是非常重要的,因为这很难在以后改变 - 但是如果你保留了很多内部实现,你可以重构你的内容使它更优雅,更灵活,或者更快...所有没有破坏任何代码,取决于你的库。

By hiding everything you don't know to be useful to clients, you buy yourself a lot of flexibility. It's incredibly important to put a lot of thought into your public API, because that's really hard to change later - but if you've kept a lot of your implementation internal, you can refactor to your heart's content to make it more elegant, more flexible, or perhaps faster... all without breaking any of the code depending on your library.

显然一些事情需要暴露 - 至少在类库中 - 但是你应该小心你暴露了多少,除非你乐意打破所有的调用者以后(或永远与你做的每一个决定永远)。

Obviously some things need to be exposed - at least in class libraries - but you should be careful just how much you expose, unless you're happy to break all callers later on (or live with every decision you make, forever).

这篇关于为什么不使用公共成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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