开发者

Why sets things to private? I'm not going to go crazy and mess with random variables

I don't think I'm understanding why setting something to private other than "you should just do it". If I had a vending machine class and it has a variable that says how many coins it has in the machine which is useless to everything else, why should I set it to private? It's not like I'm going to get high and in another class write vending开发者_如何学JAVAMachine.coins = 99999.


Using private has a few good points - I use it heavily unless I really need a property or method to be written to & read from multiple places.

  1. Tidyness - It's extremely easy to see what properties are only being changed within the current class, and which methods are only being called from within the current class.
  2. Read-only - Properties can be made read-only using private properties with a public getter.
  3. You can make special use of properties that are private with getters and setters.

Really, using private for me gives me a great overview of my application. I can easily work out what variables can be mingled with from outside of the class and which are only changed within the class.

Personally when I try to visualise my application, I see each class as a circle. Each circle has a branch that represents a property or method connecting to all of the other circles that have access to it. Now when you think about this visual, it's going to be a huge tangled mess if everything is public.

I approach my OOP like this; instead of only making a property or method private when it really needs to be private, I only make a property or method public if it really needs to be accessed throughout the application. I give the strictest level of access to everything. ie internal for stuff that's in the same package, protected for things that will only be changed from extending classes, private for stuff that's only touched within the class it's defined. I also make heavy use of a private property with a getter defined, so that I can immediately tell that a property will only be changed within the class it's contained, but is accessed in other areas.


That's probably true, but the point in OOP is to separate responsibilities and to keep data together with the corresponding methods. For very small and one man projects this might not be necessary, but in big projects where you reuse objects from other people you will sometimes not know which fields you should modify and which should not be messed with. That's why in OOP you define only the interface public and all internal stuff private. That also allows you to change the internal implementation later without breaking your program.

Have a look: http://simple.wikipedia.org/wiki/OOP

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜