Private vs Protected 34

Posted by Uncle Bob Sun, 21 Jan 2007 13:28:58 GMT

Someone on comp.object recently asked why anyone would make a field private since privacy ruins extensibility.

I recently read an article on comp.object that asked the following question:

While I can see that the ‘private’ modifier has its uses, I’m puzzled as to why it’s advocated so much given that one of the strong points of OO is extensibility.

I responded with:

The Open-Closed Principle of OOD (See article) says that objects should be open for extension but closed for modification. In other words, you should be able to change what a module does without changing the module. Extensibility, in OO, is best achieved when you keep the code you are extending safe from modification.

How do you protect a module from the forces that would try to modify it? One technique is to keep the variables that module depends upon private. If a variable is not private, then it is open to be used in a way that the module that owns that variable does not intend. Indeed, using a variable in an unintended way is the only reason to make the variable public or protected. But when you use a variable in an unintended way you likely force modifications into the owner. If, on the other hand, all the variables of a module are private, then no modification can be caused through unintended useage.

Privacy does not preclude extensibility. You can create public or protected accessor methods that: 1) provide extenders access to certain variables, and 2) ensure that the extenders don’t use the variable in an unintended way.

For example, given a variable v used by a module m, such that v should never be negative. If you make v public or protected someone could set it to a negative number breaking the code in m and possibly forcing mofidication to m. However, if v is private but is accessible through getV and setV methods; and if the setV method throws an exception if you pass it a negative number, then m is safe, and extenders are forced to follow the rules that m expects.

To be fair, while I am a big proponent of keeping variables private, I have also come to rely much more on my unit tests to enforce the appropriate use of variables. When the code enjoys 90+% unit test coverage those tests will uncover and prevent variable misuse. This softens the need for the compiler to enforce privacy. This is not to say that you should not make your variables private, you should. It is to say that if you use TDD, the cost/benefit ratio changes, and you may find that you can soften access to some variables.

Comments

Leave a response

  1. Avatar
    belugabob 1 day later:

    “When the code enjoys 90+% unit test coverage those tests will uncover and prevent variable misuse.”

    ...providing, of course, that you’re not shipping your code as an API, in which case you can’t predict what the users of the API will do.

  2. Avatar
    eirikm 3 days later:

    Funny thing then that Eiffel doesn’t have a ‘private’ modifier (not the last time I checked, that is). AFAIK, The Open-Closed Principle was first mentioned in Object-Oriented Software Construction by Dr. Bertrand Meyer, who incidentally is the designer of Eiffel.

  3. Avatar
    Eiffel over 3 years later:

    Eiffel doesn’t have a “private” modifier because all Eiffel fields are “private”: http://en.wikipedia.org/wiki/Eiffel_(programming_language)#Scoping

  4. Avatar
    Ray Cruz over 4 years later:

    At the very first, I’d choose to give thanks to you for this informative article. Second, I had prefer to doubt wherever I can find lot more information related to your article. I arrived here via Bing & can’t distinguish any linked up web websites along this matter. How do I subscribe for your web blog? I’d prefer to stick to your updates as they come along! I’d a query to interrogate but I forgotten what it absolutely was… anyways, thanx. Author of how to cook beef tenderloin

    XoX, Ray Cruz
  5. Avatar
    bag manufacturer over 4 years later:

    ul, but also very bizarre. If you aren’t careful you can get algorithms that work

  6. Avatar
    prada sneakers over 4 years later:

    Then the researchers measured the way muscle groups came down with and even done getting a dynamometer, a tool in which actions pressure, twisting, energy and additionally speed. Shortened staple fibers indicate a good high-heel wearer’s achilles tendon would certainly generate less force compared to a flat-shoe individual wearing, nevertheless muscle tissue conducted similarly both in groupings.

  7. Avatar
    prada sneakers cheap over 4 years later:

    The uk’s The city of manchester Metropolitan School also that Higher educatoin institutions for Vienna. This may get the reason why numerous ladies fully feel rigidity in their calf muscles should they get rid of their pumps. The particular conclusions are posted inside July issue of the Academic journal for Experimental Biology.

  8. Avatar
    Regim Hotelier over 4 years later:

    I’m in the process of learning oop and classes in c++ and one thing I’m trying to grasp is when you write a class when it Protected preferred over using private? Can someone explain this to me, I just cannot understand why one would be better than the other, and why not just use private?

    Thanks for any info.

  9. Avatar
    virtuemart templates over 4 years later:

    when you write a class when it Protected preferred over using private? Can someone explain this to me, I just cannot understand why one would be better than the other, and why not just use private virtuemart templates

  10. Avatar
    Electronic Book Readers over 4 years later:

    I used to be on the lookout for essential information on this subject.

  11. Avatar
    Pandora over 4 years later:

    I built a castle in the swamp and it sunk. I built a second castle and it sunk too. I built a third castle and it burned down and then sunk.

  12. Avatar
    iPad video converter for Mac over 4 years later:

    When I come to here, I think I am in the right place. the web gives me a lot of infomation, it is very informative. I think lots of people can learn much here. I will come to here again. Thanks.

  13. Avatar
    bag manufactures over 4 years later:

    Nice blog ! I like your article and i will definitely look again…....................................... regards: http://www.viaam.com

  14. Avatar
    Silicone Molding over 4 years later:

    Intertech Machinery Inc. provides the most precise Plastic Injection Mold and Rubber Molds from Taiwan. With applying excellent unscrewing device in molds, Intertech is also very professional for making flip top Cap Molds in the world.

  15. Avatar
    hermes replica watches over 4 years later:

    Ferriero said.Why Would Anyone ???? ?? Anyone Want to Kill Kate?20/20 Investigation: Scandal hermes kelly bag blueprint Scandal Inside the Peace Corps By BRIAN hermes h bracelet chalk BRIAN ROSS and ANNA SCHECTERJan. 10, 2011 hermes wallet 2011 — Kate Puzey was a beloved replica hermes scarves beloved Peace Corps volunteer in the African knockoff hermes scarves African country of Benin when she was grace kelly hermes bag was brutally murdered.Her parents and the people hermes h bracelet black people in the village where she served hermes leather bracelet served still ask,

  16. Avatar
    Criminal Check over 4 years later:

    It is to say that if you use TDD, the cost/benefit ratio changes, and you may find that you can soften access to some variables.

  17. Avatar
    Low Carb Meals over 4 years later:

    I must tell you that your post is totally cool I fantastically like your theme! Right now I have a lot of spare time to read your website because of which I added it to my bookmarks.

  18. Avatar
    Criminal Records over 4 years later:

    To be fair, while I am a big proponent of keeping variables private, I have also come to rely much more on my unit tests to enforce the appropriate use of variables. When the code enjoys 90+% unit test coverage those tests will uncover and prevent variable misuse. This softens the need for the compiler to enforce privacy. This is not to say that you should not make your variables private, you should.

  19. Avatar
    Tenant Screening over 4 years later:

    If a variable is not private, then it is open to be used in a way that the module that owns that variable does not intend. Indeed, using a variable in an unintended way is the only reason to make the variable public or protected.

  20. Avatar
    dswehfhh over 4 years later:

    We are the professional t-shirts manufacturer. t-shirts supplier. t-shirts factory, custom t-shirts.

  21. Avatar
    <a href="http://www.voien.com/">ipad bag</a> over 4 years later:

    Follow ipad bag the detail tips below, you can increase the laptop battery life of a year or more. Game Controllers first thing you should care about the USB Gadgets END!

  22. Avatar
    Jake over 4 years later:

    Another informative post. I am impressed by it. Thanks. roof venice

  23. Avatar
    jeans for sale over 4 years later:

    truereligionjeans.com

    jeans for sale

  24. Avatar
    okey oyunu oyna over 4 years later:

    “Privacy does not preclude extensibility. You can create public or protected accessor methods that: 1) provide extenders access to certain variables, and 2) ensure that the extenders don’t use the variable in an unintended way “

    i agree with it …

    Dünyan?n en büyük online okey oyunu bu sitede sizleri bekliyor. Gerçek ki?ilerle sohbet ederek Okey Oyunu Oyna ve internette online oyun oynaman?n zevkini ç?kar

  25. Avatar
    mac cosmetics over 4 years later:

    I’ll just comment here.

  26. Avatar
    christian louboutin shoes on sale over 4 years later:

    Your essay is good except for the spelling.

  27. Avatar
    beats by dr dre headphones over 4 years later:

    I found that his foot odors never bring us to death.I never regret buying these beats by dr dre studio for him. These beats by dr dre solo are just the same as selling in the franchise store.Or even better.

  28. Avatar
    Cookies Gift over 4 years later:

    hmm ,i’m not sure if this is what i’m looking for but anyway this is interresting and could be useful some day,thanks for taking time to write such cool stuff

  29. Avatar
    cartier bangle over 5 years later:

    http://www.alijewelry.com/burberry-earring-c-10.html"> Burberry Earring ,
    http://www.alijewelry.com/burberry-bangle-c-11.html"> Burberry Bangle ,
    http://www.alijewelry.com/bvlgari-earring-c-12.html"> Bvlgari Earring ,

  30. Avatar
    beats by dre store over 5 years later:

    provide extenders access to certain variables, and 2) ensure that the extenders don’t use the variable in an unintended way cheap beats by dre beats by dre store

  31. Avatar
    Tips For Bowling over 5 years later:

    General Pickett, finding the battle broken while the enemy was still reinforcing, called the troops off.

  32. Avatar
    alwadifa 2012 over 5 years later:

    Nice post keep up next times

  33. Avatar
    christian louboutin over 5 years later:

    The professional design make you foot more comfortable. Even more tantalizing,this pattern make your legs look as long as you can,it will make you looked more attractive.Moveover,it has reasonable price.If you are a popular woman,do not miss it.

    Technical details of Christian Louboutin Velours Scrunch Suede Boots Coffee:

    Color: Coffee
    Material: Suede
    4(100mm) heel
    Signature red sole x

    Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Tall Boots, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.

  34. Avatar
    louboutin sales over 5 years later:

    Private vs Protected 33 hoo,good article!!I like the post!5

Comments