Java and JavaEE

Object-Oriented Principles

We have mentioned the basic concept of Object-Oriented, but it seem to be not enough for a good software since we still need somethings else – we need good design and architecture. What are them? Is there any hint for us to have  good design and architecture?

To answer these questions are not easy tasks. We may need to read thousands of papers and get much experience to know what are  the good software design and architecture, since they are not simple concepts. However, they are all come from the same base, that is Object-Oriented principle or we can call them design principles.

Why need OO principles?

Basic syntax of an OOP is not hard to learn, the issues is how we can enhance the program in order to leverage the advantages of OO. You may already learn something about Patterns such as GoF, they are reusable solutions. In fact, they are all come from basic OO principles. Fortunately, there are a few of them which are easy to follow.

Overview

Poor design and programming is everywhere, it make the OOP seems to be not a good stuff.
Two main issues are always come with OOP, they are coupling and cohesion.
coupling is the degree of dependencies between two modules(usually classes or components) and
cohesion is how diverse are the things inside a module.  Two main goals for better software are
  • highly cohesive modules.
  • Loosely coupled modules
Let us discuss a bit more on coupling and cohesion at first.

Coupling

Modules have to be realted in order to compete task or we can think they have to interact with each other, so they can provide functionalities to others, Modules relate with the followings way:
  • Invoke operations (function call)
  • Passing data
  • Defined in terms of each other

It is clear that coupling is needed but we should always keep them simple. Moreover, coupling should be a direct connection and  we should give enough flexibility to the coupling.

cohesion

It mean class should represent a single abstraction or it should address a single general responsibility. With the procedural programming practice, we often make a bad OO modules, that may lead the followings problems
  • Hard to understand
  • one-to-one relationship often exists, too many connection / dependencies.
  • Classes hard to change
  • Classes often need to modified.
  • Performance issue
The object-oriented principles are going to help us to write flexible and better code by achieving high cohesion and low coupling.

Common OO principles

Real-world problems can be fixed according sound principles.
Followings are some common OO principles :

 

Open-Closed Principle (OCP)

A module (class) should be open for extension but closed for modification"
(originally by Bertrand Meyer).
This principle describes that classes should be open for extending without requiring modification.  That is to extend the behaviour of a system when responding to changes by adding new code without modifying the existing code. Abstraction and also polymorphism by subtype are the keys to the Open Closed Principle.

Single-Responsibility Principle (SRP)

A class should have only one reason to change (originally from Martin).

It is a matter of cohesion. A responsibility is “a reason for change.” and axes of change. If the class has two responsibilities, they are coupled in the design, and so have to change together. Simple, yet hard to get right.
We often use delegation to achieve SRP.

Interface Segregation Principle (ISP)

Many client-specific interfaces are better than one general purpose interface. (Robert Martin)

If a class has several different usage, create separate (narrow) interfaces for each usage. It should be better than all usage share the same, large interface. Clients can be as small as possible and as coherent an interface as possible. large interfaces lead to inadvertent couplings and may add dependencies between classes.

Liskov Substitution Principle (LSP)

Subclasses should be substitutable for their base classes. (originally by Barbara Liskov)

A client of a base class instance should still work with the instance of a derived class instead. A derived class should have some kind of specialized behaviour, it should provide the same services as the superclass with some variety in the behaviour only. The contract of the base class must be honoured by the derived class.
If this principle is violated, the Open-Closed Principle will also to be violated too.

Dependency Inversion Principle (DIP)

Depend upon abstractions. Do not depend upon concrete implementations (originally defined by Robert Martin).

High level modules should not depend upon low-level modules. Both should depend upon abstractions.
Abstractions should not depend upon details. Details should depend upon abstractions. High level classes should contain the “business logic”, low-level classes should contain the details of the (current) implementation. Access instances using interfaces or abstract classes is a common way for dependency inversion.

Don’t Repeat Yourself(DIY)

DRY says that every piece of system knowledge should have one authoritative,  unambiguous representation (Andy Hunt and Dave Thomas)
It is a principle for general software development, so it may be the most fundamental one. The principle target to reduce the repetition or duplication of information, it is specially important to the modern muti-tier architecture such as JavaEE. It apples broadly on software development including database schema, testing and coding.  The violations of these principle are known as WET, which usually refer to " we enjoy typing", “We edit terribly" or “Write Everything Twice". Sometimes, we may use WET to solve a  particular problem or act as a temporary solution, but we should do it with a strong rationale.
As an experienced developer, we should know how to reduce the duplication of code by appropriate practice and proper abstraction. In short, we can reduce the rrepetition in process calls by automation and reduce the rrepetition in logic by abstraction.
The DRY principle provides fundamental guidance to software developers and let us have simpler, more maintainable, higher-quality applications. We should follow this principle with regard to structure, logic, process, and function in the development.

Favor composition over inheritance

Because inheritance exposes a subclass to details of its parent’s implementation, it’s often said that ‘inheritance breaks encapsulation‘". (Gang of Four)
The principle state that the favour way to create thing is composition rather than inheritance. Using inheritance is simple with OOP but  constructing a complex hierarchy of inheritance do not allows the software to extend easily.  Although the overuse of inheritance in OOD is common and understandable,  favor composition over inheritance is a design principle that gives the design higher flexibility, giving business-domain classes and more stable business domain in the long-term. In other words, HAS-A can be better than an IS-A relationship.
The implementation of composition is often not as simple as inheritance, It typically begins with the creation of various interfaces.
 

Delegation principle

Using prototypical objects to implement shared behavior in object-oriented systems – Henry Lieberman
This principle state that it unnecessary to accomplish all the task in one module, delegates the task to an associated helper whenever possible.  The principle help us create a programs with flexibility and it  often given as the way to composition. However, there are always some confusion with delegation, the concept of delegation is not just a method forwarding in object collaboration.

Java and OO principles

The original Java APIs have implement many principles mentioned above, you can just enjoy the benefits by using Java as OOP. By using suitable principle you can create a better program with high cohesion and low coupling. One of the best way to implement corresponding principle is the pattern. However, apply a suitable principle to a particular problem is not a straightforward and easy thing, and there are always some trade-off.
We will use Java as an example to learn more for those principles.
Peter

Object-Oriented for Java

Java is an object-oriented proamming(OOP) Lanaguage, concept of OO is  imporatant for all Java progarmmer. It is useful to learn some basic principles in order to write a better program. Followings are questions that related to the OOP to help one who want to understand Java.

  • What is Object-Oriented technologies?
  • Why should we use OO in software development?
  • How Java acts as an OOP?
  • How can we adopt the OO in an effective way?
  • Is there any guideline for us during the OO software development?

In this arcticle, we will discuss some answers of above.

Object-Oriented technologies

In computer science, object-oriented is a software engineering concept, as the name suggested it refer to things with “objects".  “Object" can be a variable, function or even  a data structure. An object usually have a location in memory that have a value and referenced by an identifier. There are many related development with object-oriented concept and technologies, such as Object-oriented analysis and design, Object-oriented modeling, Object-oriented Programming(OOP), Object-oriented language and etc. OOP is actually a programming model that utilize object-oriented concept. With OOP, programs are organized by object and data, that is  the major different from tradition programming which focus on action and logic.

Why OO?

Let see why using  object-oriented in modern software development. We often use the  “divide and conquer" strategy to solve the difficult problem, it is also a basic technique for us to cope with the complexity of the reality. With this strategy, we break the problem into smaller and manageable pieces in a certain way, then we apply the specified solution to each piece.  This breakdown process can be refered to decomposition. However, the way of decomposition was a problem, we used technique of functional decomposition to solve problems in software development, the general procedure are as followings:

  • Break problem down into steps(procedure) or sub-problems
  • Find out or build program code to deal with each sub-problem, solutions are often come with the past experience or pre-built things.

Functional decomposition break down the complexity of the software into small pieces so that we can build the software in an easier and more formal way. It is the more straightforward way for software development, it just like a job break into different steps which carry out a series of task performed. It is also the most general way of our thinking model, that is why we usually decompose things into hierarchical structure only for simplicity.

The functional decomposition itself is not a problem, it does fit when the situation is simple, stationary and ready-made system; however the world tend to have much more changes during these decades. This traditional programming methodologies, named as procedural programming, bring a series of problems in software development. some of them are listed below.

  • Control and coordination can only be centered in the main method, data is separated from the function.
  • Any changes may cause big impacts.
  • Logic may be distributed within the programe as a side effect of the decomposition.
  • Data changes may affect many parts in the program, cascade of changes many be occurred.

Although problems did exist in the old software system, the technology limitations cover all other difficulties in software development during 90’s – 00’s, so software Modeling is quite deflect with the reality. The over-simplified or defective information system model also created issues on the software system. Software system became fragile, viscous, rigid, opaque and immobile. Moreover the software code was always complex and containing many unnecessary repetition.

Object-Oriented technologies came to solve problems mentioned; they focus on how to deal with complexity and changes. OOP can promote code reuse and decrease code maintenance effort. OO improve software development by building “Modules", modules encapsulate data to maintain integrity and give a control for data access. Furthermore, with OO we can encapsulating operations on data so that functionalities are bound to data. In short, modules in OO define operation, data and responsibilities.

Object Oriented programming(OOP) is programming which is oriented around objects, thus taking advantages of

  • Encapsulation,
  • Polymorphism, and
  • Inheritance

Basic OOP Concepts

Some basic OOP concepts are necessary for Java programming, they are as followings

Objects

An object is a unique programming entity that has attributes to describe it (somethings similar to  Adjectives in English), methods to get/set attribute values (somethings similar to Verbs in English). That is to say, an object have its own data(sometimes refer to “state") and identity, data structure and behavior (what action can be performed). In OO, objects are “physical", they are the basic run-time entities and occupy memory space in the computer system.
Object = state + behavior

Attributes

An object’s data, also named as properties, are stored in attributes. Attributes provide a way to describe an object. In OOP, programmers can read property values, change properties, and assign values in an object.

Methods

Methods provide a way to access or even manipulate object’s data stored in their attributes. Method is the Java term for subroutine, C/C++ calls “function".

Events

Interaction is an important aspect in the OOP, events are so defined as a record of interaction which are usually changes in the environment.

Abstraction

The concept of simplification is called abstraction in OO.  By abstraction programmers can focus on the “big picture” only and ignore some of the specific details regarding the internal structure or behavior of an object.

Classes

In OOP, we use a programming structure called a class to implement abstraction, it represents a blueprint of an object. A class contains properties and methods to show the internal structure and behavior.  A class can be treated as a set of objects that share common structure and behavior, in here the word “set" is something like “set" in modern mathematics. Classes provide a defination of attributes and methods, and usually provide the implementation of methods. In Java, classes usually contain constructors that allow initializing attributes at creation time, that is the assginment of value to the attribute.

Instantiation

The object of a class is called an instance of that class and the process of creation is called instantiation. In Java, a special method called a constructor is used to create an instance of an object. There is no de-constructor or destroyer in Java.

Encapsulation

Encapsulation is the idea about information hiding and isolation, it is closely related to the concept of Abstraction. Data and the ways to get at that data are wrapped in a single package, that is a class. With encapsulation data and code are bound together so that there is no external interference and misuse. Java use class as a basic unit of encapsulation.

Inheritance

One of the major aspects of OOP. Inheritance allows creating new classes from extending the existing class. A child class inherits its properties and attributes from parents, with the ability to overriding. The main advantage for inheritance is that an object need not define all its characteristics explicitly. Java only supports single inheritance for simplicity.

Polymorphism

It is the ability to create things, variable, function or even object that more than one form. Polymorphism let us describe how to write methods to do some general purpose function. Different objects might perform polymorphic methods differently in run-time. Polymorphism involves concept of type.  A variable can be assigned to different types of objects while different method implementations can have for different types.

Association

The relationship of the objects or classes are known as association, an association contains the semantic meaning of roles that each class play, multiplicity and the direction of the relationship.

Interface

A computer system is actually a collection of different parts, the part need to communication or interact with others in order to compete tasks. For instance, an operating system may interface with pieces of hardware. An interface is the place of interaction with software, hardware or peripheral devices conceptually. The implemenation of the interface may be in different format even it a differtent level in a computer system.  In OO, object need to interact with each other via method.

In object-oriented languages, “interface" is often used to define an abstract type that contains no data but methods to define the behaviour. So, an interface is a type definition. A class having all the methods corresponding to that interface is said to implement that interface. Furthermore, a class can implement multiple interfaces, and hence can be of different types at the same time.

Althrough using an interface in the interaction is not a must. A key principle of design is to prohibit access to all resources by default, allowing access only through well-defined entry points, i.e. interfaces. By using interafce, the type of the object to be exchanged in the interaction can be defined in terms of an interface instead of a specific class, the code developed can be more generic and reusable as long no changes have been occur with the interfeace( the defination).

Java as an OOP

Java is a well-developed object-oriented programming language, it follows a strict object programming model. Most of the object-oriented features are almost transparent to the programmer, so almost no additional effort  needed in software development to adopt OO when using Java. However, Using Java alone is not enough for building a good software,  we also need a good software design. In order to have a good software design, we have to perform the followings

  • Apply Object-Oriented principle appropriately.
  • Develop a suitable architecture and software model.
  • Apply software patterns.
  • Using a suitable development methodology
  • Adopt corresponding best practices.

we will have discuss on those mentioned above.