12

I've come from a C++ background and am going all out C# in my current job and I've just been reading a lot of Q&A about what's the difference between public fields and properties and all the back and forth in variations and incarnations of this basic question (e.g. this SO post and all the related linked questions). All of those questions are addressed in terms of practical differences that take for granted the existence of a property system but I think it would be good to approach this subject in terms of what the designers of all the languages which decided to support properties in the first place were thinking (check out the list in the Wikipedia article here). How did OOP evolve from C++/Java to extend into what the Wikipedia article interestingly identifies as a middleground between methods and member data:

"That is, properties are intermediate between member code (methods) and member data (instance variables) of the class, and properties provide a higher level of encapsulation than public fields."

MSDN adds further background:

"Although properties are technically very similar to methods, they are quite different in terms of their usage scenarios. They should be seen as smart fields. They have the calling syntax of fields, and the flexibility of methods."

I'd like to know how it was arrived at that this intermediate level of encapsulation proved useful for programming in general. I'm assuming this concept was not present at the first incarnation of programming languages that expressed the OOP paradigm.

jxramos
  • 359
  • 1
  • 9
  • 9
    The bare language feature is just convenient syntactic sugar for getter and setter methods. Whether there are deeper reasons behind the interpretation and terminology, I do not know. –  Dec 23 '14 at 22:49
  • In a round of OO experts your question title can be provoking, and may distract from what you were really asking. Not that I take myself beeing an OO expert, I am just an "OO user" for several years. – Doc Brown Dec 24 '14 at 07:53
  • It's a syntactic nicety I've come to miss going from 'parameter-less methods' in Python to C++. `BMI = bob.weight/sq(bob.height)` reads nicer without `()` IMO. – OJFord Dec 24 '14 at 13:50
  • I think properties were in the original (non .net) Visual Basic, as a way to configure Active X (COM) object. The property grid in this tool probably had something to do with the adoption of properties in languages. Note that the original Visual Basic was not object oriented in many ways, but it had the capability to create something like classes. – Frank Hileman Dec 25 '14 at 00:06
  • Continuing: the property window was a way to configure objects without writing code. It was called RAD development. This link contains a screenshot of the VB6 properties window: http://www.microsoft.com/mspress/books/WW/sampchap/4068.aspx – Frank Hileman Dec 25 '14 at 00:16
  • 1
    Here's an update worth sharing I came across while learning more about ildasm and .NET IL stuff. This question started with the OO context but this whole property business may be more in line with what is called component oriented programming... – jxramos Apr 16 '15 at 00:41
  • 1
    _Csharp is the first **Component oriented language** in the market. A component 1. Should deliver **PME** (Property, Method and Events) model 2. Should be able set both design and run time attributes 3. Should be able to generate documentation preferably in XML_ [IL "The Language of CLR" - A Platform for Cross-Language](http://www.c-sharpcorner.com/UploadFile/nrsurapaneni/ILtheLangOfCLRbyNRS12222005040956AM/ILtheLangOfCLRbyNRS.aspx) – jxramos Apr 16 '15 at 00:42

7 Answers7

18

Well, I am not 100% sure, but I guess things are probably simpler than you expect. From the OO modeling schools of the 90's, there was a demand for modeling classes with encapsulated member attributes, and when implemented in languages like C++ or Java, this typically lead to code with lots of getters and setters, so a lot of "noise" code for a relatively simple requirement. Note that most of (probably all, did not check this) the languages listed in your linked Wikipedia article started to introduce "properties" of objects at the end of the 90's or later.

I guess that was the main reason language designers decided to add some syntactic sugar to reduce that noise. And though properties are surely no "core OO concept", they at least have something to do with object orientation. They do not show "an evolution of OOP" (as your question title assumes), but they support OO modeling at the programming language level to make the implementation easier.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565
  • It has nothing to do with object-oriented programming, except in the sense that a property is an abstraction of a field, and fields are part of object-oriented programming. But properties are not needed for object-oriented programming, as you correctly note. – Frank Hileman Dec 23 '14 at 23:22
  • 2
    @FrankHileman: "a property is an abstraction of a field, and fields are part of object-oriented programming" - well, that sounds to me like you agree the concept *has* actually at least *something* to do with OOP. And that's why you downvoted me? – Doc Brown Dec 23 '14 at 23:24
  • no, it was probably your bad attitude. Your answer is good. I upvoted it again. – Frank Hileman Dec 24 '14 at 00:22
  • 3
    lol. Can you blame him? He slipped off his toilet and hit his head on his sink. Anyway... The way I always saw it was that properties *aren't* an strictly on OO thing. They help with encapsulation and encapsulation helps with OO. – MetaFight Dec 24 '14 at 00:31
  • 1
    Ha! This is quite the introduction to programmers.stackexchange for me. Lol, a lot more heated than my equivalent experience in plain ol stackoverflow :-p Good way to mix up the day! – jxramos Dec 24 '14 at 00:35
  • @DocBrown definitely on to something regarding programming development use cases. I just edited the question to include some background from MSDN that suggests how to conceptualize properties. This also vindicates DeadMG's comment about identifying "a pattern in the usage of older languages and acted to optimize that common case." – jxramos Dec 24 '14 at 00:52
  • @FrankHileman: sorry you took this personally, maybe I just had a different understanding of what the OP was asking for. – Doc Brown Dec 24 '14 at 07:40
  • @MetaFight: thanks for the doctors analysis. One could argue that properties help with encapsulation. But it is not the property itself that does that (that is syntactic sugar). It is the get or set methods that do that. Those are methods, just like any others, so they add nothing new to object oriented programming. – Frank Hileman Dec 24 '14 at 21:30
  • @DocBrown it is I who should apologize. However the diagnosis above is incorrect (regarding toilet). – Frank Hileman Dec 24 '14 at 21:36
  • 3
    http://en.wikipedia.org/wiki/Emmett_Brown#Back_to_the_Future – MetaFight Dec 25 '14 at 05:54
11

You have it backwards (kind of). Lambda Calculus exists as pretty much the core formal basis for programming languages, and has been for decades. It has no fields.

To model mutable state, you need to make two abstractions. One represents setting some state, and another that retrieves that state (Chapter 13 in my version of TaPL for reference). Sound familiar? From a theoretical background, OO didn't evolve to have this stuff. OO read Programming Languages 101 and made a baby step forward.

From a practical perspective, there are two fairly clear motivations. You come from a C++ background, so what would need to happen if you had a public field - say... the text in a textbox. What happens when you want to change your design so that "whenever this textbox changes, do blah"? You get to kill that field, make a function or two and wire up that logic, since you can not trust developers to call "UpdateTextbox" themselves. This is a very breaking change to your api (and unfortunately still a breaking change in .NET's implementation of properties). This sort of behavior is all over the place in the Windows API. Since that's a big deal at Microsoft, C# likely wanted to make that less painful.

The other big motivation is Java Beans and their kin. A number of frameworks were built to use Java reflection to look for GetX and SetX pairs and effectively treat them like modern properties. But since they weren't actual language constructs, these frameworks were fragile and unweildy. If you typo'd a name, things would just break silently. If one got refactored, nothing moved the other side of the property. And doing all of the field/get/set boilerplate was verbose and tedious (even for Java!). Since C# was developed largely as "Java with lessons learned" that sort of pain was one of those lessons.

But the biggest thing is that the property concept has been successful. It's easy to understand, it's easy to use. These help adoption greatly, and as a tool, programmers have found that properties solve a subset of problems more cleanly than either functions or fields.

Telastyn
  • 108,850
  • 29
  • 239
  • 365
  • 7
    I downvoted you mostly for too much reference to irrelevant formal crap. Actual implementations of programming languages have much more serious things to consider than whether or not their model was included in lambda calculus. – DeadMG Dec 23 '14 at 23:41
  • 9
    @DeadMG - that is certainly true, but on the other hand programming language implementors are invariably going to be familiar with that _irrelevant formal crap_. To think that it did not impact their designs is naive. – Telastyn Dec 23 '14 at 23:43
  • 3
    This is definitely not "irrelevant formal crap." However, the lambda calculus may not have been considered much for early programming languages. If so, CPUs would probably be more oriented toward that mentality. – Frank Hileman Dec 24 '14 at 00:19
  • 3
    @FrankHileman - I'm pretty sure Lisp considered it... – Telastyn Dec 24 '14 at 00:22
  • 4
    @Telastyn - yes -- and Lisp was not supposed to be a programming language originally, remember? – Frank Hileman Dec 24 '14 at 00:24
  • +1, especially for the historic annotations. Don't know much about Java Beans. – Doc Brown Dec 24 '14 at 07:57
  • Good answer, it explains the exact practical reasons that led to the introduction of properties as a language-level construct. – Theodoros Chatzigiannakis Dec 24 '14 at 09:13
  • @FrankHileman [ML](http://en.m.wikipedia.org/wiki/ML_programming_language) is from 1973 and lives on today through a lineage of Standard ML, OCaml and F#. That's pretty early. – Doval Dec 25 '14 at 00:38
  • @Doval I am not saying that it had no influence, and these are very good influences. But we are not using the lisp-based architectures I remember that were for the "future", when we discussed them in the 80s. CPU designs seem distantly related to lambda calculus. – Frank Hileman Dec 25 '14 at 00:44
  • 2
    @FrankHileman Well, yes, but I don't see what that has to do with anything since the whole point of a high level language, regardless of its paradigm, is to move away from the details of the machine. The fact that the hardware doesn't provide direct support for lambda calculus is about as relevant as the hardware not providing support for objects. Nobody thinks in machine code except the people that actually write machine code for a living. – Doval Dec 25 '14 at 01:07
  • @Doval Lambda calculus was used as the basis for language, no doubt. But not all languages, and many popular languages were based on other ideas. C for example, was a way to abstract assembly language. – Frank Hileman Dec 27 '14 at 02:45
6

It's all about Encapsulation and the Uniform Access Principle.

An object should be able to respond to a message by either returning existing data or running a method, but the sender shouldn't be able to tell which is which. Or if you view this from the sender's side: the sender should be able to access existing data or run a method through a uniform interface.

There are several ways to achieve this:

  • get rid of data altogether, just have methods (Newspeak does this)

    • a less radical form of the above: get rid of data in the public interface, i.e. make data always private, in the public interface, only expose methods (Smalltalk, Ruby do this)
  • get rid of methods altogether, just have data (Self does this, "methods" are just Method objects assigned to instance variables, instance variables are looked up with virtual dispatch)

  • make no syntactic or semantic distinction between methods and data (Scala does this, accessing a field is syntactically indistinguishable from calling a method without an argument list (foo.bar), assigning to a field is syntactically indistinguishable from calling a specially named method (foo.bar = baz) is the same as foo.bar_=(baz) i.e. calling a method named foo_=, and read-only values can be overridden or implemented by a method without parameter list (i.e. val foo) in a superclass can be overridden (or an abstract val be implemented) in a subclass with a method def foo)

Java, however, doesn't follow the Uniform Access Principle. In Java, it is possible to distinguish between accessing data and running a method. foo.bar is different from foo.bar(). The reason for this is that fields and methods are semantically and syntactically distinct.

C# tries to fix this by adding properties to the language, basically methods that look like fields. However, method calls still look and feel different from field and property accesses. Fields and properties now have Uniform Access, but methods still don't.

So, this doesn't actually fix the problem: you cannot fix having two different ways to access things by adding a third way to access things! Even if that third way looks like one of the other two ways, you will still have (at least) two different ways. You can only fix it by either getting rid of all the different ways except one or get rid of the differences.

It's perfectly fine to have a language with methods, properties and fields, but all three should have uniform access.

Jörg W Mittag
  • 101,921
  • 24
  • 218
  • 318
  • 2
    Why do you (and others) think maintaining Uniform Access is so important? With a method you might want to give it parameters to change what it does or acts upon. With a field or property you do not have this ability, you generally just return data (although a property can be implemented as running a method instead of just exposing a private field). That seems intuitive to me, maybe just because I am used to it, but what would you gain in elegance or productivity by enforcing uniform access? Are you afraid you are leaking implementation details outside the class? – Mike Dec 24 '14 at 06:25
  • 1
    The UAP is about reserving the freedom to change implementation details without breaking the public interface. The usual example is adding logging. If I offer access through a method, I can trivially change the internals of the method to write to a log. With a public field, I can't add logging without first turning it into a method, which breaks all client code. If breaking changes cannot be risked, using methods is a must. Properties are the optimal compromise because they are full methods but look like fields. Adhering to the UAP improves encapsulation and reduces tight coupling. – amon Dec 24 '14 at 10:22
  • Lots of good answers to this question but I think this one hit the nail on the head by pulling out the more fundamental aspects of the nature of programming languages and elaborating about the relevant formal concept of UAP. Solid – jxramos Dec 29 '14 at 23:59
3

Properties have nothing to do with object-oriented programming, because properties are only syntactic sugar. Properties look like fields superficially, and in the .net world, it is recommended that they behave like fields in some ways, but they are not fields in any sense. Properties are syntactic sugar for one or two methods: one to get a value, and one to set a value. Either the set method or the get method may be omitted, but not both. There may be no field storing the value returned by the get method. Because they share a syntax with fields, and because they often use fields, people associate properties with fields.

Properties have advantages over fields:

  • In a property set method, before a property value is stored, the new value, or the state of the object, may be checked against a set of preconditions or invariants.
  • A property get method may exist for convenience, if retrieval of the property value can be logically considered equivalent to retrieval of a field value.
  • A property set method may perform other operations, such as notifying a parent object or listening objects of a change to a property value.

Because properties are the abstraction of fields, and for syntactic convenience, languages such as C# adopted the field syntax for properties.

Frank Hileman
  • 3,922
  • 16
  • 18
  • 2
    First line from the Wikipedia article. "A property, in some object-oriented programming languages, is a special sort of class member ...". So your first sentence is plain wrong. And the remaining part does not answer the question. – Doc Brown Dec 23 '14 at 22:54
  • 1
    @DocBrown: Interesting response. Many Wikipedia articles are clearly incorrect. I assume you are defending the author of this specific article? – Frank Hileman Dec 23 '14 at 22:55
  • No, I just thought the same when I read your answer (which is actually not an answer to the question). – Doc Brown Dec 23 '14 at 22:57
  • 1
    Not all features of object-oriented programming languages are related to object-oriented concepts. – Frank Hileman Dec 23 '14 at 22:57
  • 1
    That does not change the fact you are not answering the question. – Doc Brown Dec 23 '14 at 22:58
  • @DocBrown I await your (better) answer. – Frank Hileman Dec 23 '14 at 22:59
  • 3
    It should be noted that it's not just the setter that is optional. You can have setter only properties. – Telastyn Dec 23 '14 at 23:38
  • @Telastyn: good point. – Frank Hileman Dec 24 '14 at 00:15
  • I disagree with the first statement, everything else is reasonably well explained though. – Pharap Dec 24 '14 at 09:03
  • @Pharap: could you please explain how the syntactic sugar is related to object oriented programming. – Frank Hileman Dec 24 '14 at 21:26
  • @FrankHileman They facilitate the use of Information Hiding to protect attributes whilst maintaining the separation between things the object can do (methods) and information about the object (properties). Methods and properties are just one way of implementing the OO paradigm just as classes are only one way of implementing OO. – Pharap Dec 24 '14 at 21:54
  • @Pharap From the perspective of object oriented programming, properties are pairs of methods. I prefer the convenience of properties, but from an OO perspective, they add nothing over and above a pair of methods with a suitable naming convention. Other people believe properties are fundamentally non-object-oriented, because they are similar to fields. I don't agree with that either, for the same reason (they are simply methods). – Frank Hileman Dec 24 '14 at 22:00
  • @FrankHileman By the same logic you could argue that operators are just methods and add nothing to a language, and yet I'm sure you'd also agree `a = b + c` is a lot more comfortable than `a.set(add(b, c))`. – Pharap Dec 24 '14 at 22:17
  • @Pharap I agree that operators are just syntactic sugar and are not related to object oriented concepts as well. Few language features are relevant to object oriented programming. What is "comfortable" is a separate subject. – Frank Hileman Dec 24 '14 at 23:59
3

In .net specifically, properties originate from the old Visual Basic days which as it happens was not object oriented in the way we think about it today. It was largely build around the then-new COM system that superficially treated everything not necessarily as classes but in terms of components which would expose properties that could be accessed both in code but also in graphical editors. When VB and the newly created C# were merged into .net, VB gained a whole lot of OOP-features and they kept properties since removing them would be like a step backwards - imagine if the automatic code update tool they had in Visual Studio had been replacing all your properties with getters and setters and was breaking compatibility with all COM-libraries. It would only be logical to support them in all .net-languages so components can be used across the whole framework without interop issues or exposing the internal implementation.

niwax
  • 139
  • 1
  • I don't think you should ignore C#'s ancestry which came from Delphi and from before that, Object Pascal and Turbo Pascal with Objects. These were object-oriented and did have properties (though I can't remember whether OP had properties from TP5.5 or whether they were added; presumably they were continued into C# by Anders because they were pragmatically a good idea. – amaca Dec 30 '14 at 21:29
  • Very interesting that you happened to be the only one to hit upon the component aspect to this question. I just added a comment to my question linking to a site that listed properties as part of some property-method-event model that C# satisfies. I then searched my question's page again for "component" landing a few false positives but your answer I think actually overlaps with what I linked to. – jxramos Apr 16 '15 at 00:59
2

It's a matter of implementation versus implication. Properties were in OOP before C++ or Java hit the scene (they were there, with some roughness around the edges, in Simula, and they are fundamental to Smalltalk). Entities with properties are conceptually different from values with code attached. The get & set prefixes in some language conventions only serve to muddy the waters; they make you aware of the difference between fields and properties, assuming that fields may be accessed directly without get/set in a manner that is idiomatic to the language, and that's leaky.

The whole point of OOP is to treat things as if they were entities in the "real" world, not just as structs with some code mixed in. Another programmer should need to know very, very little about the way I have implemented things, and should not be at all concerned with which of the various values they are allowed to get and/or set are real and which are virtual. If you run across a vector of mine, you shouldn't need to know whether I'm storing angle and magnitude or real and imaginary components internal to the vector object. If I change the representation in V2.0 of my library, it shouldn't affect your code at all (though you may wish to take advantage of the cool new features). Similarly, there are properties an entity might have that depend on data external to the entity, but which are undoubtedly properties from a lexical standpoint. You ask people "how old are you", not "please perform the calculation that will reveal your age to me", even though you know that the data available to that "object" are date of birth (a private immutable member) and today's date (a public, auto-incrementing environmental property, dependent on time zone, daylight savings time, and the International Date Line). Age is a property, not a method, even though it takes some calculation to get there and cannot (except in toy computer representations of things with artificially-limited lifetimes) be stored as a field.

Rather than thinking of properties as the bastard child of fields and methods, it's far more satisfying to thing of methods as a specialized sort of property - things that your entities can do rather than things that they are. Otherwise you're not conceptually dealing with object/entities, you're dealing with data collections that happen to have code attached to them. The implementaions may be identical, but the implications are different.

It should be needless to say, however, that this abstraction comes at a cost. If a programmer using a class can't tell whether he or she is accessing data as it is stored or getting/setting values that need to be computed, then there will be a level at which the language is also necessarily uncertain (and therefore may require that everything requires code to intermediate between accessors/selectors and values). There is nothing conceptually wrong with "structs with code" - they can certainly be much more efficient - but they leak implementaion all over the place, and that's one of the things that OOP is supposed to eliminate.

Stan Rogers
  • 129
  • 3
  • I agree with some points and disagree with others, but the overall message is a good one: Some information about an object needs to be calculated but is still technically information that *is* rather than an action that can be *done*. – Pharap Dec 24 '14 at 09:22
0

Absolutely nothing whatsoever. Properties and OOP have nothing to do with each other. Properties are nothing more than syntactic sugar for function calls, and therefore have exactly the same OOP-attachment that function calls do- which is to say, none.

Wikipedia is completely incorrect, by the way. The getMember/setMember pattern you see in Java offers exactly the same advantages (and disadvantages) as properties in C#. And you can replicate this pattern even in C if you want to.

Properties in C# are nothing more than language-supported syntactic-sugar.

DeadMG
  • 36,794
  • 8
  • 70
  • 139
  • 3
    Have you ever seen the property concept in any programming language outside of a class or object context? I have not. – Doc Brown Dec 23 '14 at 23:14
  • Good comment, that's basically where I'm forming the association. Among the programming [paradigms](http://en.wikipedia.org/wiki/Programming_paradigm), its really only the Object Oriented one that I'm familiar with that manifests this concept. But I could easily be shortsighted on this one. – jxramos Dec 23 '14 at 23:17
  • 1
    @DocBrown: I've implemented it. Fact is, properties are pretty low-value targets for language authors, since their improvement over regular function calls is low. – DeadMG Dec 23 '14 at 23:25
  • 1
    OP is was asking about the *history* of properties as a concept in popular programming languages. And actually, in the historic sense there is a connection between properties and OOP. – Doc Brown Dec 23 '14 at 23:29
  • 1
    His question asks how OOP evolved. OOP did not evolve at all because of or due to properties. They do not enable or disable any fundamental change in the interface or any way that types can relate to each other or any such thing. – DeadMG Dec 23 '14 at 23:31
  • 1
    @DeadMG: yes that's true, but I understand the question differently - not how did "OOP (in general)" evolve by the concept of properties, but "what caused newer languages to include the property concept". – Doc Brown Dec 23 '14 at 23:36
  • 1
    @DocBrown: For the same reason they included every other feature: because they identified a pattern in the usage of older languages and acted to optimize that common case. – DeadMG Dec 23 '14 at 23:38
  • 1
    @DeadMG: exactly what I wrote in my answer. – Doc Brown Dec 23 '14 at 23:41
  • 1
    @DocBrown: Right, but that has absolutely nothing to do with OOP and this case has nothing to do with OOP either. – DeadMG Dec 23 '14 at 23:43
  • 1
    @DeadMG: no, but at least I try to answer the OP's question the way I understand it. – Doc Brown Dec 23 '14 at 23:45
  • From a reflection perspective alone, .NET properties offer clear advantages over Java style `Get`/`Set` independent (except by name) functions. You might not think they're _valuable_ but exactly the same? – Telastyn Dec 23 '14 at 23:45
  • 2
    Maybe I was a bit rash to ascribe this concept of properties to the OOP paradigm per se, but as a concept it certainly transcends individual languages and their features. Maybe I'm struggling to articulate the appropriate ontology between the two. I'm not suggesting through the question's title that properties are a fundamental feature/concept of [OOP](http://en.wikipedia.org/wiki/Object-oriented_programming#Fundamental_features_and_concepts) that makes or breaks the OOP formalism, and yet I do sense they only have a reality in this OOP space which is why I phrased the question as such. – jxramos Dec 24 '14 at 00:26
  • 4
    They are not just syntax sugar in C#, they exist in the assembly metadata as distinct members and you can do things with properties you can't with fields, such as databinding. – Andy Dec 24 '14 at 00:30
  • Technically you can emulate OOP in C if you want to (by implementing Vtables, thiscalls and the like), you can also emulate getters and setters. You cannot however emulate Properties because C does not support operator overloading. If you think otherwise, by all means write some C code demonstrating said properties. – Pharap Dec 24 '14 at 09:11
  • 1
    @Andy: The Java folks managed to databind to methods just fine. Not being able to data bind to fields or methods is just a limitation of that specific implementation and has nothing to do with anything in general. – DeadMG Dec 24 '14 at 10:22
  • @DeadMG Irrelevent; you can't databind fields in C#, and your answer isn't talking about java, its talking about C#, so your statement that "Properties in C# are nothing more than language-supported syntactic-sugar" is nonsense. – Andy Dec 24 '14 at 13:12
  • @Andy data-binding has nothing to do with object-oriented concepts either, as far as I can tell. The concept of properties pre-dates their adoption in object oriented languages. Consider the evolution of Borland Delphi and Visual Basic, and the authoring of COM components, to understand the origin of properties. – Frank Hileman Dec 25 '14 at 00:50
  • @FrankHileman What is so hard to understand that the statement that "Properties in C# are nothing more than language-supported syntactic-sugar" is wrong? Seriously, where did I say anything about OOP? I'm just refuting that one statement which is clearly wrong. – Andy Dec 25 '14 at 13:16
  • @Andy Properties are syntatic sugar. They generate metadata, but they have no meaning in and of themselves, except in that they combine two methods into one abstraction. – Frank Hileman Dec 27 '14 at 02:38