Public Variables - Are they really that bad?




I get this thought every now and then - should Public Variables be avoided in all situations?  I was recently writing a quick prototype application, and had a few "data objects" which I noticed myself spending alot of time writing get/set properties.  I then proceded to get rid of them all, and revert to just simple public variables. 

There was something about this that annoyed me, because I think back to my years at university and it was constantly drummed into us "never have public variables, always use gettter/setter methods (in java) or properties (in .NET)".  Even though this thought kept popping up, I stuck with it, and having the raw public variables worked well for my prototype, and took alot of bloat out of the code.

However - even after building the successful prototype - I still feel uneasy about using them.  I treated that prototype as an experiment with public variables, and even in that small case, I started seeing signs where not encapsulating your object data properly could lead to problems where clients of your objects could accidently change your objects state without you (your object) knowing about it or having control over it.

The great thing about this though is that Microsoft addressed this concern in .NET 3 and now we have the best of both worlds with Automatic Properties.  Keeps your code clean, but gives you the power of encapsulation.

But...is there still a place for the public variable?  I'm not convinced either way. 



 del.icio.us  Stumbleupon  Technorati  Digg 

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this entry.
Comments

  • 28 November 2008, 2:52 PM Dutt wrote:
    I have gone though your article. But I could not see any specific advantage by using global variables. Could you explain in detail, where you have found the big advantage of global variables.
    Reply to this
  • 28 November 2008, 3:25 PM mattcalla wrote:
    The only real benefit I've found is that its less code to write, and therefore keeps class with large amounts of variables more concise and more readable.  But like I said I don't think we should all start using public variables now, I'm just questioning whether there is room for them in some situations.

    Reply to this
Leave a comment

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.