what is a member vs. a property - oop

A friend who is new to OO programming asked me the difference between a Member and Property, and I was ashamed to admit that I couldn't give him a good answer. Since properties can also be objects themselves, I was left with a general description and list of exceptions.
Can somebody please lay out a good definition of when to consider something a member vs. a property? Maybe I'm bastardizing the concept, or is it just that a member is just the internal name I use, and the property is what's exposed to other objects?
I don't think that not knowing the answer to this question has affected the quality of my programming, and it's just a semantics point, but it still bothers me that I can't explain it to him.

A property is one kind of member. Others might be constructors, methods, fields, nested types, conversions, indexers etc - depending on the language/platform, of course. A lot of the time the exact meaning of terminology depends on the context.
To give a C#-specific definition, from the C# 3.0 spec, section 1.6.1:
The following table provides an overview of the kinds of members a class can contain.
(Rows for...)
Constants
Fields
Methods
Properties
Indexers
Events
Operators
Constructors
Destructors
Types
Note that that's members of a class. Different "things" have different kinds of members - in C#, an interface can't have a field as a member, for example.

Neither of the two terms has any defined meaning whatsoever in Object-Oriented Programming or Object-Oriented Design. Nor do they have any defined meaning in the overwhelming majority of programming languages.
Only a very small number of programming languages have a concept called property or member, and even fewer have both.
Some examples of languages that have either one of the two are C++ (which has members), ECMAScript (which has properties) and C# (which has both). However, these terms don't necessarily denote the same concepts in different programming languages. For example, the term "member" means roughly the same thing in C++ and C#, but the term "property" means completely different things in ECMAScript and C#. In fact, the term "property" in ECMAScript denotes roughly the same concept (ie. means roughly the same thing) as the term "member" in C++ and C#.
All this is just to say that those two terms mean exactly what the relevant specification for the programming language says they mean, no more and no less. (Insert gratuitous Lewis Carroll quote here.)

Properties is one kind of members.
In C#, for example, a class can have the following members:
Constructors
Destructors
Constants
Fields
Methods
Properties
Indexers
Operators
Events
Delegates
Classes
Interfaces
Structs
MSDN: C#: class

Members are just objects or primitive types belonging to a class.
Properties give you more power than members. It's like a simplified way to create getters and setters letting you make, for instance, public getters and private setters; and put whatever logic you want in the way it will be read or written to. They can be used as a way to expose members, being possible to change the reading and writing policy later more easily.
This applies to C#. Not sure if this is true for the other languages though.

A member (variable) is just some part of the object. A property is (I'll qualify this with "usually" - I'm not sure that it's a technically clear word that has unambiguous meaning across multiple languages) is a publicly accessible aspect of the object, e.g. through getter and setter methods.
So while (almost always) a property is a reacheable member variable, you can have a property that's not really part of the object state (not that this is good design):
public class Foo {
public String getJunk()
{ return "Junk";}
public void setJunk(String ignore){;}
}
}

Both properties and methods are members of an object. A property describes some aspect of the object while a method accesses or uses the owning object.
An example in pseudo-code:
Object Ball
Property color(some Value)
Method bounce(subroutine describing the movement of the Ball)
Where the ball is defined and given a color(property) while the method bounce is a subroutine that describes the how the ball will react on hitting another object.
Not all languages have properties, i.e. Java only has fields that must be accessed by getters and setters.

Properties are a way to expose fields, where fields are the actual variables. For example (C#):
class Foo {
private int field;
public int Property {
get { return field; }
set { field = value; }
}
}

from PHP manual:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization.

Member is a generic term (likely originated in C++, but also defined in Java) used to denote a component of a class. Property is a broad concept used to denote a particular characteristic of a class which, once the class is instantiated, will help define the object's state.
The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concepts of state and behaviour:
The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.
Behaviour is how an object acts and reacts, in terms of its state changes and message passing (methods); the outwardly visible and testable activity of an object.
So, the behaviour of an object depends on the available operations and its state (properties and their current values). Note that OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:
The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.
An operation upon an object, defined as part of the declaration of a class. The terms message (Smalltalk), method (many OO languages), member function (C++), and operation are usually interchangeable.
But the notation introduced by the author is precise:
An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.
An operation denotes some service provided by the class. Operations (...) are distinguished from attributes by appending parentheses or by providing the operation's complete signature, composed of return class, name, and formal arguments (if any): R N(Arguments)
In summary, you can think of members as everything that composes the class, and properties as the members (attributes) that collectively define the structure of the class, plus its relationships to other classes. When the class is instantiated, values are assigned to its properties in order to define the object's state.
Cheers

Related

Can we not use the term object while defining encapsulation in OOP?

I have read a definition of encapsulation which stated that "Encapsulation is the wrapping of data and functions into a single unit called class" .My question is that can we not use the term object instead of class in the definition because at last objects are created using the classes and objects only encapsulate data and functions inside them?
I don't have a problem with replacing "class" with "object" in the example sentence. It remains valid in class-based OOP languages while being more appropriate for prototype-based OOP languages. Classes are just a type system for OOP after all and not as fundamentally essential as encapsulation is.
I would, however, want to improve that sentence to make it clear that data and functions aren't "wrapped" in the same way. Data must be hidden and only be accessible to methods of an object.
The more important question to consider is why encapsulation is essential to true oop. Objects are to hide their attributes and inner workings, and present an interface for use by other objects. oop begins to break down when this encapsulation is broken. Code becomes harder to maintain if everyone has their hands on everyone else’s data. Consider setters and getters and all the ways we tend to break encapsulation. True object thinking is not primarily about classes and polymorphism. It is definitely about encapsulation and interfacing between objects.
Not every class has objects.
We can have static classes that have no objects.
If the definition were changed to use the word "object", these classes would not be covered. With "class", both static and non static classes are covered.
Even if a class is not static, it could have static data and functionality, again the term class is more appropriate.
Other classes may be abstract and therefore have no objects, they may still provide some encapsulation.
Template classes could also be though of as being capable of encapsulation even though there will be no objects of the template itself - only objects of "concrete" classes with specific types provided for the templates type parameters.
Also, the word "single" becomes a bit confusing if we apply it to objects since we can have multiple object of a class.
Cid's comment offers an additional reason for "class" over "object".
I assume you have a rough idea of what encapsulation is? So you are asking why couldn't the definition bee rephrased to
Encapsulation is the wrapping of data and functions into a single unit called an object.
Because encapsulation has nothing to do with objects at all. You can create some class called Car and it has some fields like engine, seats, steeringWheel and some methods applyBrakes, openWindow as well as some private members. Now you can say that the class encapsulates the inner workings of a car into a single unit - the Car class.
See? I didn't say anything about objects. Car objects are really just a bunch of references in memory pointing to other Engine, Seat and SteeringWheel objects.
In my opinion, "data" is the problematic term. Classes encapsulate attributes and methods that work on these attributes together. "data" suggests actual data and not meta data. That is probably why you thought of objects instead of classes.
Other than that, I would not replace class with object here, because it leaves out the important feature that all objects from one class have the same methods. With object, one could interpret that each object has its own set of functions.

What is the difference between subtyping and inheritance in OO programming?

I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
What is the difference between subtyping and inheritance in object-oriented programming?
In addition to the answers already given, here's a link to an article I think is relevant.
Excerpts:
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front, delete-front, insert-rear and delete-rear. If we use just insert-rear and delete-front we get a normal queue. On the other hand, if we use just insert-front and delete-front, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack and Queue inherit from Deque. On the other hand, neither Stack nor Queue are subtypes of Deque since they do not support all the functions provided by Deque. In fact, in this case, Deque is a subtype of both Stack and Queue!
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
A relative unfortunately died and left you his bookstore.
You can now read all the books there, sell them, you can look at his accounts, his customer list, etc. This is inheritance - you have everything the relative had. Inheritance is a form of code reuse.
You can also re-open the book store yourself, taking on all of the relative's roles and responsibilities, even though you add some changes of your own - this is subtyping - you are now a bookstore owner, just like your relative used to be.
Subtyping is a key component of OOP - you have an object of one type but which fulfills the interface of another type, so it can be used anywhere the other object could have been used.
In the languages you listed in your question - C++, Java and C# - the two are (almost) always used together, and thus the only way to inherit from something is to subtype it and vice versa. But other languages don't necessarily fuse the two concepts.
Inheritance is about gaining attributes (and/or functionality) of super types. For example:
class Base {
//interface with included definitions
}
class Derived inherits Base {
//Add some additional functionality.
//Reuse Base without having to explicitly forward
//the functions in Base
}
Here, a Derived cannot be used where a Base is expected, but is able to act similarly to a Base, while adding behaviour or changing some aspect of Bases behaviour. Typically, Base would be a small helper class that provides both an interface and an implementation for some commonly desired functionality.
Subtype-polymorphism is about implementing an interface, and so being able to substitute different implementations of that interface at run-time:
class Interface {
//some abstract interface, no definitions included
}
class Implementation implements Interface {
//provide all the operations
//required by the interface
}
Here, an Implementation can be used wherever an Interface is required, and different implementations can be substituted at run-time. The purpose is to allow code that uses Interface to be more widely useful.
Your confusion is justified. Java, C#, and C++ all conflate these two ideas into a single class hierarchy. However, the two concepts are not identical, and there do exist languages which separate the two.
If you inherit privately in C++, you get inheritance without subtyping. That is, given:
class Derived : Base // note the missing public before Base
You cannot write:
Base * p = new Derived(); // type error
Because Derived is not a subtype of Base. You merely inherited the implementation, not the type.
Subtyping doesn't have to be implemented via inheritance. Some subtyping that is not inheritance:
Ocaml's variant
Rust's lifetime anotation
Clean's uniqueness types
Go's interface
in a simple word: subtyping and inheritance both are polymorphism, (inheritance is a dynamic polymorphism - overriding). Actually, inheritance is subclassing, it means in inheritance there is no warranty to ensure capability of the subclass with the superclass (make sure subclass do not discard superclass behavior), but subtyping(such as implementing an interface and ... ), ensure the class does not discard the expected behavior.

Why does "Design Patterns" say 'two objects of the same type only need to share part of their interfaces'?

On page 13 in the GoF book there is a statement:
Two objects of the same type need only share parts of their interfaces.
I am not sure I understand this sentence.
EDIT: full quote might indeed help to understand that
A type is a name used to denote a particular interface. We speak of an
object as having the type "Window" if it accepts all requests for the
operations defined in the interface named "Window." An object may have
many types, and widely different objects can share a type. Part of an
object's interface may be characterized by one type, and other parts
by other types. Two objects of the same type need only share parts of
their interfaces. Interfaces can contain other interfaces as subsets.
In their language, an objects interface is the the entire public contract of the object (Don't think language implementation here).
The set of all signatures defined by an object is called the interface
to the object.
A type is more like what you would think of as a declared interface....
A type is a name used to denote a particular interface.
Imagine:
public class Foo : IBar, IBaz {}
public class Fuz : IBar, IBuz {}
A Foo and a Fuz are both IBar "types" but they only share that aspect of their respective interfaces.
a more full quote is:
A type is a name used to denote a particular interface. We speak of an
object as having the type "Window" if it accepts all requests for the
operations defined in the interface named "Window." An object may
have many types, and widely different objects can share a type. Part
of an object's interface may be characterized by one type, and other
parts by other types. Two objects of the same type need only share
parts of their interfaces. Interfaces can contain other interfaces as
subsets.
and pretty clearly, i think, this is talking about multiple inheritance. for example you might have TextWindow and MenuWindow that both subclass Window along with other classes. both objects can be considered, in the sense they are using, to have "type" Window, and they will both implement the operations associated with that type - they will both have Window's methods. but TextWindow may also subclass TextEditor while MenuWindow does not, so their total set of methods (what they mean by "interface") are not the same, even though the Window part overlaps.
http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf
I don't know what it means as I don't have the book. But an interface is the method signatures of the class, combined with the public variables. As a subtype of a particular type, is also a type of its parent class, it can have methods that it parent does not have, hence it only shares some of the interface of the parent. I have no idea if that is actually what it was talking about though.

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.
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.
Short answer: never.
Actually, if you use an object for simply storing data, but the object itself does no logic, and you never mean to derive from this object, then it is OK to have public fields. Sometimes I do things like this in C++:
struct A {
int a;
float b;
string c;
A():a(0),b(0.0) {}
A(int a_, float b_, string c_):a(a_),b(b_),c(c_) {}
};
But other than having initializing constructors, it is nothing more than a C struct. If your class does anything more than this, than you should never use public (or even protected) fields.
As for properties, it depends on what language you use. For example, in Delphi, the main purpose of properties is to provide public interfaces to fields, and can provide getters/setters to them, while still working syntactically like a variable.
Is there a good reason to use a public
property / field?
No.
Public members are always dangerous. You may not need any control now, but once you expose them, you lose any possibility of having control later. If you have gettes/setters right away you have room for adding control later.
Ps:
Depending on the language you use, properties and fields may mean different things.
C# properties are actually a way to both achieve encapsulation and at the same time not being very verbose.
There is a bad reason: by directly accessing the datum you avoid pushing a method call onto the stack, for what that's worth.
In many languages this is also achievable by inlining the accessor method/s.
If the purpose of the object is to hold data in its fields, then yes. It would also make sense to have methods on the object which are (a) purely functional (in that they do not change the state of the object, or anything else); or (b) which manipulate the state of the object, and the point is that they manipulate the state in a particular way.
The kind of things that you should avoid are (c) methods that do things to other objects based on the state of the object (and certainly if there are assumptions about what is a "valid" state).

Is there any static language in which a class is an object?

There are quite a few dynamically typed object oriented languages in which a class itself is an object. Smalltalk, and Python for example. Is there any statically typed language in which a class is an object?
EDIT:
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
In a lot of statically typed languages, like JAVA, a class is an object with its own methods.
For example, in Java, the object that represents the "String" class is accessible as "String.class" and then you can invoke methods on this class as "String.class.getFields()", "getMethods()", getConstructor()", "cast(obj)", etc. You can see in the API documentation all the methods of the "Class" class.
Nevertheless, given that the language is statically typed, you cannot dynamically modify a class.
In other words, you are not going to find a method called "class.addField()" in the Class class. The more you can do is "extend" the class (if it is not final) by inheritance.
In yet other words, the a "Class" object is read-only.
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
As any other object, you can pass them to methods and return them from methods (they are just regular objects, but that expose only "read" methods). Example (I omit generics for clearness):
public Class myMethod(Class someClassObject) {
System.out.println(someClassObject.getCanonicalName());
Class anotherClass = String.class;
return anotherClass ;
}
I don't fully agree with #edutesoy answer.
First-class means that an implicit constructs is reified as an explicit construct that can be passed around like any object. Classes in Java are not "first-class", they are mirrors where you can inspect some properties but are not the the object itself.
That you can not change the structure of the class at run-time is fine, e.g. add fields, change method body or signature, and that under this perspective it's partly "read-only" is ok.
But let's consider static fields. I guess everybody agrees that unless final static fields are mutable, just like instance fields. In Smalltalk, these are just fields defined on the class itself, rather than on instances of the class. Also, in Smalltalk, class-side methods are polymorphic just like any other method, and :
aClass field: aValue.
might resolve differently depending on the class that is passed. This is not possible in Java ; a static field or method must be referenced via its type. This also means that it does not allow overriding static methods (read the link for more details) as would be the case if they were truely first class.
The fact that reflection is possible in Java doesn't make classes "first-class"--you can only pass a representation of the class around. And to come back to the original question: I don't know of any statically typed language with first-class classes (but my knowledge is limited, maybe one exists).
EDIT
Actually, now I remember it exists StrongTalk (http://www.strongtalk.org/) which is Smalltalk with static typing. The typing issues are discussed in this paper: Strongtalk: Typechecking Smalltalk in a Production Environment
From Oleg Kiselyov and Ralph Lammel's "Haskell's overlooked object system" (emphasis mine),
Not only OOHaskell provides the conventional OO idioms; we have also
language-engineered several features that are either bleeding-edge or unattainable
in mainstream OO languages: for example, first-class classes and class closures; statically type-checked collection classes with bounded polymorphism of implicit collection arguments; multiple inheritance with user-controlled sharing; safe co-variant
argument subtyping.
Well, the benefits of that are reduced in an early-bound language. However, Java reflection objects for classes would basically be what you are asking for.
Why, incidentally, do you want this? Is it more than idle curiousity?
Take a look at the concept of homoiconicity which refers to the extant that a language can refer to its own structures. Also take a look at this post by Eric Lippert.