Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Sunday, March 2, 2008

OOPL Comparison

The following table shows some similarities and differences in features and the use of terms and concepts in Smalltalk, C++, and Java.

OO Concept/syntax

Smalltalk

C++

Java

Abstract class

Concept exists, no mechanism for enforcement

A class with a pure virtual function can't be instantiated

Classes may be declared abstract

Assignment operator

:=

=

=

Character constant

$c

'c'

'c'

Class

Class

Class

Class

Class method (corresponds to a message sent to the class rather than an instance)

Class method

Static function member

Class (or static) method

Class variable (data associated with the class, not an instance)

Class variable

Static data member

Class field

Comment

"Comment"

// Comment
/* Comment */

// Comment
/* Comment */
/** Javadoc Comment **/

Dynamic binding

Unrestricted

Only subclasses of the declared class

Subclasses of the declared class or implementations of the declared interface

Equality test (see also identity test)

=

==

equals()

Finalization of instances before deletion (e.g., to release operating system resources)

Some implementations support finalize method

Destructor function

finalize method is standard

Garbage collection (automatic memory management)

Garbage collection is standard

No garbage collection - programmer explicitly manages memory

Garbage collection is standard

Identity test (see also Equality test)

==

same as equality

==

Inheritance

Single inheritance only

Multiple inheritance

Single inheritance only

Initialization of instances

Override new method

Constructor function

Constructor function

Instance data or state

Instance variable

Data member

Instance field

Interface contract (specifies the public interface to classes that implement it)

No corresponding construct

No corresponding construct

Interface

Message

Message

Member function call

Method invocation

Message send syntax

anObject doIt

anObject.doIt() (direct)
pObject->doIt() (pointer)

anObject.doIt()

Method

Method

Member function

Method

Method argument syntax

methodName: argument (keyword method)

memberFunctionName(argument)

methodName(argument)

Method return

^ (caret)

return

return

Object (root of all classes)

Class Object

No corresponding class

Class Object

Operator overloading (an aspect of polymorphism; different operator behavior based on receiver type)

Any operator can be overloaded

Any operator can be overloaded

Only methods can be overloaded, not built-in operators such as +, - , *

Pointers

No explicit storage pointers

Explicit use of storage pointers and pointer arithmetic

No explicit storage pointers

Self (the object executing a method)

self

this (usually not written)

this (usually not written)

String constant

'string constant'

"string constant"

"string constant"

Subclass

Subclass

Derived class

Subclass

Superclass

Superclass

Base class

Superclass

Superclass method invocation

super

:: (scoping operator, more general than Smalltalk or Java capability)

super()


Friday, September 7, 2007

Polymorphism

Polymorphism means that the same thing can exist in two forms. This is an important characteristic of true object oriented design - which means that one could develop good OO design with data abstraction and inheritance, but the real power of object oriented design seems to surface when polymorphism is used.

In programming languages, polymorphism means that some code or operations or objects behave differently in different contexts.
For example, the + (plus) operator in C++:
4 + 5 <-- integer addition 3.14 + 2.0 <-- floating point addition s1 + "bar" <-- string concatenation!
In C++, that type of polymorphism is called overloading.


Polymorphism

  • Literal meaning - many forms
  • OOP meaning
    - Same method (message) but different behavior
    - Object determines which method gets executed
  • Function or Method Overloading
    - Similar message but different behavior
  • Abstract interfaces to class hierarchies
    - Define core data and behavior capabilities of a class family
    - All classes in the family support core capabilities
    - All objects in family respond to core methods (messages)

A classic example is how area is calculated on different shapes. We define an abstact base class shape and derive two classes - rectangle and circle from it. An area() method defined in the base class will have to be implemented differently in rectangle and circle, since it has to be calculated differently.

This is an example of polymorphic behavior, and in C++, this is implemented using virtual member functions. The area() member function is defined virtual in the base class, which signals to the compiler that this member function has to be invoked from the correct derived class at run time. This is indeed a run time decision, and which derived class member function is to be invoked depends on which derived class pointer has been assigned to the base class pointer. This also brings in the concept of late binding (run time binding), since the above association to the area member function can only be done at run time. The compiler will have to insert extra code to do the late binding, which adds in a little runtime overhead.


Types of Polymorphism:
C++ provides three different types of polymorphism.
Virtual functions
Function name overloading
Operator overloading

In addition to the above three types of polymorphism, there exist other kinds of polymorphism:
run-time
compile-time
ad-hoc polymorphism
parametric polymorphism


Other types of polymorphism defined:
run-time:
The run-time polymorphism is implemented with inheritance and virtual functions.
compile-time:
The compile-time polymorphism is implemented with templates.
ad-hoc polymorphism:
If the range of actual types that can be used is finite and the combinations must be individually specified prior to use, this is called ad-hoc polymorphism.
parametric polymorphism:
If all code is written without mention of any specific type and thus can be used transparently with any number of new types it is called parametric polymorphism.

In general, there are two main categories of Polymorphism namely
Ad Hoc Polymorphism
Pure Polymorphism


Overloading concepts fall under the category of Ad Hoc Polymorphism and Virtual methods. Templates or parametric classes fall under the category of Pure Polymorphism.

Persistence

One of the most critical tasks that applications have to perform is to save and restore data. Whether it be a word processing application that saves documents to disk, a utility that remembers its configuration for next time, or a game that sets aside world domination for the night, the ability to store data and later retrieve it is a vital one. Without it, software would be little more effective that the typewriter - users would have to re-type the data to make further modifications once the application exits.

Therefore, an object that has the ability to store and remember values is often said to have persistence. For Example, the ability of your car radio to remember your list of favorite stations is often referred to as persistence.

It also can be defined as the property of an object by which its existence transcends time(i.e., the object continues to exist after its creator ceases to exists) and/or space (i.e., the object's locations moves from the address space in which it was created).

Hierarchy

In computer science's object-oriented programming, the mapped relationships of sub- and superclasses is known as a hierarchy. This can be visualized as an upside-down tree (or perhaps a pyramid), the top of which is known as the root.

The issue is more complicated with languages that support multiple inheritance, where hierarchy can be any directed acyclic graph.

Aggregation or Composition relationships in object-oriented design also form a hierarchy, composition hierarchy.

In object-oriented programming, a class is a template that defines the state and behavior common to objects of a certain kind. A class can be defined in terms of other classes. For example, a truck and a racing car are both examples of a car. Another example is a letter and a digit being both a single character that can be drawn on the screen.

In the latter example, the following terminology is used:


  • The letter class is a subclass of the character class; (alternative names: child class and derived class)

  • The character class is immediate superclass (or parent class) of the letter class;

  • The letter class extends the character class.
The third formulation expresses that a subclass inherits state (instance variables) and behavior (methods) from its superclass(es). Letters and digits share the state (name, font, size, position) and behavior (draw, resize, ...) defined for single characters.

The purpose of a subclass is to extend existing state and behavior: a letter has a case (upper and lower case, say stored in the instance variable letterCase) and methods for changing the case (toUpperCase, toLowerCase) in addition to the state that it already has as a character.

However, a digit does not have a case, so the methods toUpperCase, toLowerCase do not belong on the common level of the Character class. There are methods that are special to the digit class. For instance, a digit may be constructed from an integer value between 0 and 9, and conversely, the integer value of a digit may be the result of say the intValue method.

In graphical terms, the above character example may look as follows:



The classes form a class hierarchy, or inheritance tree, which can be as deep as needed. For example, the letter class can have on its turn the subclasses vowel and consonant.




When a message is sent to an object, it is passed up the inheritance tree starting from the class of the receiving object until a definition is found for the method. This process is called upcasting. For instance, the method toString() is defined in the Object class. So every class automatically has this method.

In graphical terms, the inheritance tree and the message handling may look as follows:



A hierarchy is useful if there are several classes which are fundamentally similar to each other. In C++, a "base class" is a synonym for superclass and"derived class" is a synonym for subclass.


Messaging

"The process by which an object sends data to another object or asks the other object to invoke a method." Also known to some programming languages as interfacing.

The object's interface consists of a set of commands, each command performing a specific action. An object asks another object to perform an action by sending it a message. The requesting (sending) object is referred to as sender and the receiving object is referred to as receiver.




Control is given to the receiving object until it completes the command; control then returns to the sending object.

For example, a School object asks the Student object for its name by sending it a message asking for its name. The receiving Student object returns the name back to the sending object.



A message can also contain information the sending objects needs to pass to the reveiving object, called the argument in the message. A receiving object always returns a value back to the sending object. This returned value may or may not be useful to the sending object.

For example, the School object now wants to change the student's name. It does this by sending the Student object a message to set its name to a new name. The new address is passed as an argument in the message. In this case, the School object does not care about the return value from the message.



It is very common that a message will cause other messages to be sent, either to itself or to other objects, in order to complete its task. This is called sequential operation. Control will not return to the original sending object untill all other messages have been completed.

For example, in the following diagram, Object A sends a message to Object B. For Object B to process that message it sends a message to Object C.Likewise, Object C sends a mesage to Object D. Object D returns to Object C who then returns to Object B who returns to Object A. Control does not return to Object A until all the other messages have completed.



How do receiving objects interpret messages from the senders? How are the messages processed?
Each message has code that associated with it. When an object receives a message, code is excercuted. In other words, these messages determine an object's behavior and the code determines how the object carries out each message. The code that is associated with each message is called a method. The message name is also called the method name due to its close association with the method.
When an object receives a message, it determines what method is being requested and passes control to the method. An object has as many methods as it it takes to perform its designed actions.
Refer to the following diagram, name, name:, address and name:address are method names for the Student object. When the Student object receive the name message, the name message passes control to the name method defined in Student.

Fundamental Concepts - OOP

Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.


Class
A class defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do or methods or features). For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark (behavior). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained. Collectively, the properties and methods defined by a class are called members.


Object
A particular instance of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur. In programmer jargon, the object Lassie is an instance of the Dog class. The set of values of the attributes of a particular object is called its state.The object consists of state and the behaviour that's defined in the object's class.


Method
An object's abilities. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat(). Within the program, using a method should only affect one particular object; all Dogs can bark, but you need one particular dog to do the barking.


Message passing
"The process by which an object sends data to another object or asks the other object to invoke a method." Also known to some programming languages as interfacing


Inheritance
"Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high-pitched by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "is-a" relationship: Lassie is a Collie. A Collie is a Dog. Thus, Lassie inherits the members of both Collies and Dogs.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well.



Encapsulation
Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allows one to specify which classes may access any member.



Abstraction
Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets.Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.



Polymorphism
Polymorphism allows you to treat derived class members just like their parent class's members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a Bark. However, if a Pig is commanded to speak(), this may elicit an Oink. They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.



Not all of the above concepts are to be found in all object-oriented programming languages, and so object-oriented programming that uses classes is called sometimes class-based programming. In particular, prototype-based programming does not typically use classes. As a result, a significantly different yet analogous terminology is used to define the concepts of object and instance, although there are no objects in these languages.

Tuesday, September 4, 2007

Abstraction

"An abstraction denotes the essential characteristics of an
object that distinguish it from all other kinds of object and thus
provide crisply defined conceptual boundaries, relative to the
perspective of the viewer."

-- [Booch, 1991]



"[A] simplified description, or specification, of a system that
emphasizes some of the system's details or properties while
suppressing others. A good abstraction is one that emphasizes
details that are significant to the reader or user and suppress
details that are, at least for the moment, immaterial or
diversionary."

-- [Shaw, 1984]


Abstraction, as a process, denotes the extracting of the essential
details aboutan item, or a group of items,while ignoring the
inessential details.

Abstraction, as an entity,
denotes a model, a view, or some other focused representation for
an actual item. Abstraction is most often used as a complexity
mastering technique.


Abstraction
refers to the act of representing essential features
without including the background details or explanations.
Classes use the concept of abstraction and are defined as a
list of abstract attributes.

Example:

An electrician and an interior decorator will look at the same building each in two different ways. The decorator will probably view the building primarily as a series of rooms. However, the electrician will view it as a series of walls and floors. Walls are in both their views, but serve a different purpose, have a different priority, and relate in different ways.

Thus, the "abstraction" used by the decorator may be rooms which are composed/comprised of walls and floors/ceilings. But the electrician's view may have the walls be the primary abstraction, with room information incidental, perhaps only to locate the proper wall when walking around.

Further, in the electrician's view, walls are a complex 3D structure with their own little world inside, while the interior decorator may view them mostly as 2D flat panels. Both have walls in their mental abstractions, but view and relate them differently.





Object Oriented Typing

The concept of type is more or less important in a language, depending on whether the language is strongly or weakly (or not at all) typed.

In strongly typed languages, the compiler prevents you from mixing different kinds of data together. This is limiting, but can be very helpful when you want to avoid putting a string, say, into the floating point value for the altitude of an airplane’s automatic pilot.

In OO languuages, type is a synonym for class, at least as a first cut. In fact, class and type are quite distinct. A more nuanced understanding of type is one of the things that distinguishes a shallow from a deep understanding of OO design and programming.

Type defines the properties and behaviors shared by all objects of the same type (class).

OO languages can run the range of un-typed, weakly typed, or strongly typed.

The advantage of strongly typed languages is that the compiler can detect when an object is being sent a message to which it does not respond. This can prevent run-time errors. The other advantages of strong typing are:

  • earlier detection of errors speeds development
  • better optimized code from compiler
  • no run-time penalty for determining type

The disadvantages of strong typing are:

  • loss of some flexibility
  • more difficult to define collections of heterogenous objects

C++ maintains strong class typing. An object may only be sent a message containing a method that is defined in the object’s class, or in any of the classes that this object inherits from. The compiler checks that you obey this.
Objective C support strong typing, but it also allows for weak typing. A special type, id, can be used for object handles. An id can be a handle to any class of object, thus it has no typing information, and the compiler can’t check if you are sending proper messages. This is done instead at run-time.

Monday, September 3, 2007

Program Execution

The topology of a structure program is inherently different than the topology of an OO program. Modules are nested into a calling tree, as shown below:



By contrast, the topology of an OO program is inherently less ordered. Objects cluster together by those which communicate most frequently. Inter-cluster messages exist, but are less common than intra-cluster messages. Notice how much like a computer network this topology looks.

Object Model

The object model has many facets. Here are the ones you’ll eventually have to understand to be mature OO developers. Note that these aren’t “OO” concepts. There is however a way of thinking about and understanding them in an OO context.

Abstraction, Encapsulation, Identity, Modularity, Hierarchy, Typing, Concurrency, Persistence
This is initially a scary, rather monstrous task. We’ll take them iteratively, in keeping with our OO development methodology.