Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good reason to use a public property / field?

One of the important parts of object-oriented programming is encapsulation, but public properties / fields tend to break this encapsulation. Under what circumstances does a public property or field actually make sense?

Note: I only use the term 'property' or 'field' because terminology varies between languages. In general, I mean a variable that belongs to an object that can be accessed and set from outside the object.

like image 963
NT3RP Avatar asked Jul 07 '11 13:07

NT3RP


People also ask

Why we use properties instead of public variables?

Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation. Save this answer.

When should you use properties?

Consider using a property if the member represents a logical attribute of the type. Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

Can a field be public?

Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.

Should properties be public or private C#?

Conclusion. In almost all cases, fields should be private. Not just non-public, but private. With automatic properties in C# 3, there's basically no cost in readability or the amount of code involved to use a property instead of a field.


1 Answers

Yes, there are sometimes good reasons. Information hiding is usually desirable. But there are some occasional exceptions.

For example, public fields are reasonable and useful for:

  • A C++ pimpl - a struct/class holding the private implementation of another class. Its fields may be declared public syntatically, but are typically accessible only within one source file, by the class holding the pimpl.
  • Constant fields. For example, Joshua Bloch writes in Effective Java: "Classes are permitted to expose constants via public static final fields."
  • Structs used for communication between C and C++.
  • Types which represent only data, whose representation is unlikely to change. For example, javax.vecmath.Point3d, which represents an {x,y,z} coordinate.
like image 194
Andy Thomas Avatar answered Oct 20 '22 15:10

Andy Thomas