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

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.

Related

Class or interface for declaring global types?

What is the recommended (modern) approach for reusing types between different classes?
SAP does not recommend to collect constants in an interface, calling it a loosy way of declaring:
" anti-pattern
INTERFACE /dirty/common_constants.
CONSTANTS:
warning TYPE symsgty VALUE 'W',
transitional TYPE i VALUE 1,
error TYPE symsgty VALUE 'E',
persisted TYPE i VALUE 2.
ENDINTERFACE.
Does the same applies to types? What are the drawbacks or advantages I am not aware of?
Should I use use classes, interfaces for types or maybe type pools?
As the document you linked to says, you should not use an interface for constants because that way you are:
misleading people to the conclusion that constants collections could be "implemented".
Which is why they recommend to put constants into an ABSTRACT FINAL class.
ABSTRACT means that this class as itself can not be instantiated (like an interface) and FINAL that it can not be inherited from (unlike an interface). This clearly communicates to the user that this class only exists as a container for static things like CONSTANTS, CLASS-DATA, CLASS-METHODS and of course TYPES.
So the same argument can be used against interfaces which do nothing but serve as a container for types. When you create an INTERFACE for that sole purpose, then people might wonder how they are supposed to implement that interface. So you would put them into a CLASS instead.
Another alternative which is still worth considering IMO (especially if you consider to use any of those types in database tables) is to use the good old ABAP Dictionary. It was invented for exactly that purpose: To serve as a directory for global types.
Unfortunately it doesn't allow you to organize types into namespaces (not unless you are working for SAP or a SAP partner who is able and willing to go through the bureaucracy to register a worldwide unique namespace for every product). So you have to make sure that each type you create has a proper prefix so people know which application it belongs to. But there is a character limit for dictionary type names, so you have to keep them short.
Using a class as a container for the types of each application solves that problem. The class serves as a namespace, so your type names no longer need to be system-unique.

Is it correct to declare types/attributes in an interface from OOP point of view?

Is it correct to define a type within an interface? And what about an attribute?
Some programming languages only allow method signatures for an interface, but in ABAP I was considering doing something like the code below, even adding more attributes, and I'm not sure if the approach is a correct OOdesign:
INTERFACE zif_notif_note.
TYPES: BEGIN OF ty_note_id,
notif_num TYPE qmnum,
activity_key TYPE aknum,
END OF ty_note_id.
DATA: id TYPE ty_note_id READ-ONLY.
METHODS get_id
RETURNING VALUE(r_id) TYPE ty_note_id.
ENDINTERFACE.
What if I need to use this type as an input parameter for another class? Should I better define DDIC structure then?
To your first question: nothing speaks against defining a type in an interface.
To your second question...
You can do many things in ABAP OO that you cannot do in other object oriented languages like Java or C++. For example you can define a FINAL ABSTRACT CLASS which is nonsense, you can define static methods (CLASS-METHODS) in an interface which is in my opinion a heresy towards the object oriented programming.
I have never defined attributes unless they were CONSTANTS within an interface, because there is no reason for doing it. They will be automatically marked as PUBLIC which breaks in fact the encapsulation principle.
So the answer would be: It is possible but think twice before going that way because it might be breaking the encapsulation of the classes that implement the interface.

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.

What is the Difference Between Classes vs Protocols

I'm going through the docs because I am about to implement a protocol instead of a class (something I've never done before), and I'm curious as to the difference between the two.
Can someone give an example in plain words?
Thanks
A class serves as a blueprint for creating one or more objects based on specific implementation of that class.
A good analogy is a form for cutting out butter-cookies. The form‘s attributes (shape, size, height) define the cookies that you can cut out with it. You have only one form (class) but you can create many cookies (instances of that class, ie. objects) with it. All cookies are based on that particular form.
Similarily all objects that are instances of that class are identical in their attributes.
Classes = data and methods (special functions), all sophistically bundled together.
Classes define, what their inner content (data) is + what kind of work (methods) they can do.
The content is based on variables that hold various number types, strings, constants, and other more sophisiticated content + methods which are chunks of code that (when executed) perform some computational operations with various data.
All methods defined in class have their
Definition - that defines the name of the method + what (if any) data the methods takes in for processing and what (if any) data the methods spits out for processing by someone else. All methods defined in class also have Implementation – the actual code that provides the processing – it is the innerworkings of methods.. inside there is code that processes the data and also that is able to ask other methods for subprocessing data. So the class is a very noble type in programming.
If you understand the above, you will understand what a protocol is.
A protocol is a set of one or more method declarations and that set has a name and represents a protocol. I say declarations, because the methods that together are defined by a particular protocol, do not have any implementation code defined.. The only thing that exist is their names declared.
Look above - in class, you have always defined not only what methods the class has, but also how that work will be done. But methods in protocol do not have any implementation.
Lets have a real life analogy again, it helps. If you come to my house to live here for a week, you will need to adhere to my TidyUp protocol. The TidyUp protocol defines three methods - wash the dishes every day, clean the room, and ventilate fresh air. These three methods, I define them..are something you will do. But I absolutely do not care, how the implementation should look like, I just nominaly define the methods. You will implement them, ie.you define how the details of that work (those methods) will look like. I just say, adhere to my protocol and implement it as you see fit.
Finale – You can declare some class. You can separately also declare a protocol. And you can then declare, that this class, in addition to its own methods, will adopt or adhere to that protocol, ie. the class wil implement the protocol’s methods.
The plain words from The Objective-C Programming Language explain the purpose of protocols simply:
Protocols declare methods that can be implemented by any class.
Protocols are useful in at least three situations:
To declare methods that others are expected to implement
To declare the interface to an object while concealing its class
To capture similarities among classes that are not hierarchically related
So, protocols declare methods, but don't provide the implementation. A class that adopts a protocol is expected to implement the protocol's methods.
Delegation is a good example of why a protocol is useful. Consider, for example, the UITableViewDataSource protocol. Any class can adopt that protocol, and any class that does so can be used as the data source for a table. A table view doesn't care what kind of object is acting as its data source; it only cares that the object acting as data source implements a particular set of methods. You could use inheritance for this, but then all data source objects would have to be derived from a common base class (more specific than NSObject). Using the protocol instead lets the table count on being able to call methods like -tableView:willBeginEditingRowAtIndexPath: and -tableView:heightForRowAtIndexPath: without needing to know anything else about the data source.
A protocol is a lot like an interface in Java and other languages. Think of it as a contract that describes the interface other classes agree to implement. It can define a list of required and optional methods that an implementing class will implement. Unlike a class, it does not provide its own implementations of those methods.
the main difference between classes and protocols is that writing protocols is useful to implement delegate methods.
in example we've got class A and class B and we want to call a method in class A from the class B.
you can read a very valuable example of that in this article
http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
reading code is worth a thousand words ;-)
that helped me out the first time I had to use'em
Somewhat less difference than in other languages. An interface (equivalent to a Java/C++ class) defines the data layout of objects and may define some subset of their methods (including the possibility of defining the entire set, of course). A protocol defines a subset of methods only, with no data definition.
Of significance is that a interface can inherit from only one other interface (which can, of course, inherit from an interface which inherits from an interface which inherits ...), but an interface can implement any number of protocols. So two distinct interfaces with no common inheritance (other than NSObject) can both implement the same protocol and thus "certify" that they provide the same functions. (Though with Objective-C you can, with a few tricks, call methods of an interface that aren't externally declared in either the interface declaration or a protocol, so protocols are to a degree just "syntactic sugar" or some such.)
Protocol defines what a class could do, like a Interface in Java or c#
A class is the actual implementation that does the job.
Simple enough? :)

what is a member vs. a property

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