开发者

Why Not Use Public Member Functions

开发者 https://www.devze.com 2023-04-06 03:20 出处:网络
Even if I make class member functions public and it is consumed by other client a开发者_如何学运维pplications, implementation details of

Even if I make class member functions public and it is consumed by other client a开发者_如何学运维pplications, implementation details of functions will never get exposed to client. Why make member functions protected or private?

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
}


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.

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.

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


There's nothing wrong with public member functions- they're quite essential, although the necessity of an object in your case is more than somewhat dubious. However, protected/private functions are for when you need to re-use some code that shouldn't be part of the public interface.


Because some methods may be part of internal implementation, and not of public interface. For example, some private method can change state of object to invalid one, but it is only used as intermediate step in some other public method. Definetely you don't want it to be called by client.

0

精彩评论

暂无评论...
验证码 换一张
取 消