Category: Software Architecture

Software Architecture : Package by Features or Package by Layers?

 

Why the package structure is more important?

The directory structure (i would prefer to say it as the package structure) of the application is more important because, it helps to structure the code in more logical and readable manner. In addition, it helps the developer to navigate though the code with more readable and understandable way.

In proper package may lead to series of scalability, maintainability and readability issues.

Continue reading “Software Architecture : Package by Features or Package by Layers?”

Observer Pattern in Java

 

The observer pattern has ben categorized as a behavioral software design pattern. In Observer Pattern there is a subject and it will maintain a list of observers as dependents.

The object which is being watched is called the subject. The objects which are watching the state changes are called observers.The relationship between subject and observers is one to many.  In other words, a subject can have many number of observers.  Whenever the subject (the state of the subject) is changed, the list of related dependents will be notified.

 

 

observer pattern.png

 

 

Real world use-cases for Implementing Observer Pattern

If you start to think for real world situations where we can implement the observer pattern, you will be ended up with many number of (even uncountable) use cases. Here i am going to point two sample scenarios for giving you some understanding of the use of observer pattern.

  • Online Store : Customer is interested in buying a product (lets say wrist watch) online and found that the product is out of stock. In this case, the customer (observer) can subscribe for the product (Subject) for getting the notification when the stock is available. The product (subject) will maintain a list of customers (observers) to be notified when the product is available.
  • Flight Schedule : Passengers may be interested of getting the information about the changes of the flight schedules. In such case, the passengers (observers) can subscribe for a flight schedule (subject) and they will receive the update if the schedule is changed.

 

Implementation with Java

The sample implementation of Observer pattern can be shown as follows. please see the below sample classes.

Subject.java

 

ObserverA.java

The implementation of ObserverB and ObserverC are same as above classes. Please refer the source code for more details.

 

MainApplication.java 

 

You can notice that ObserverA and ObserverB has been subscribed for the Subject. The ObserverC has not subscribed for any subject and it remains as unsubscribed.  The status of the subject has been changed three times. Therefore theoretically. each  observers should get notified whenever the state of the object is changed and here it should be three times.

Lets run the application and see the output.

 

Source Code and How to Run

The full source code of the implementation of the observer pattern can be found at GitHub. Click here to download.

The implementation has been made as a Spring Boot CLI (command line) project. Therefore the project can be build and run with following command.

mvn spring-boot:run

 

After running the above program, you will get the following output.

Screen Shot 2018-03-06 at 12.49.44 AM.png

 

Here you can see that ObserverC does not get the notification because, it is not subscribed for the Subject.

 

Coupling Observer with Subject (Is it required or not ?)

In some of the implementation for the Observer Pattern available in the Internet, you might have seen that the Observers are tightly coupled with Subject. This happens when the Observer keeps a reference to the Subject (Observer maintain a member variable that refer to the Subject). This introduces and additional and unnecessary coupling between Subject and Observers. Those implementations are poor implementations of the Observer Pattern.

The Subject maintains a list of Observers who are interested about the subject. Therefore Subject can notifies the observers about the state changes when they happen. There is no valid point of maintaining a reference from observer to Subject as there is no communication happens from Observer to Subject.

If the Observer wants to know about the Subject, then it can be received as a parameter of the method which is used/invoked by the Subject to notify the observers about the state changes.

In a proper software design , the coupling should be low and cohesion should be high.

 

Observer Pattern with SOLID Design Principles

Observer Pattern follows the Open Closed Principle” of the SOLID Design Principles.  Open closed principle states that  “the class should be opened for extension and closed for modification.  This means that the it should be able to extend the class without changing the source code of the class. Therefore, It should be possible to add Observers for the Subject without changing the source code of the Subject class.

 

Are Observer Pattern and Publisher-Subscriber Pattern are same?

The majority of the developers are having a misunderstanding that Observer Pattern and Publisher-Subscriber Pattern are same. No! They are NOT.  The reason behind this misunderstanding is that they thinks that Subject as Publishers and Observers as Subscribers. Therefore they thinks that publisher-subscriber pattern and observer pattern are same. Publisher-Subscriber pattern is a kind of variation of the Observer Pattern. 

 

Click here if you want to look at the Publisher-Subscriber Pattern 

 

The differences between Publisher-Subscriber and Observer pattern can be shown in the following  diagram.

pub-subVsObserver.jpeg

 

Lets summarize the differences between Publisher-Subscriber pattern and Observer pattern as follows.

  • In the Observer pattern, Subject maintains a list of Observers and therefore Subjects aware of how to notify observers when there is a state change occurs. Whereas, in Publisher/Subscriber, publishers and subscribers don’t need to know each other. They simply communicate with the help of middle layer message broker (or message queue).
  • In Publisher/Subscriber pattern, components are completely decoupled with compared to Observer pattern (In Observer pattern, Subject and Observers are loosely coupled).
  • Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).
  • Observer pattern need to be implemented in a single application address space. It will be implemented within the single application.  On the other hand, Publisher/Subscriber pattern is more of a cross application pattern. Publisher and Subscriber may resides in two different applications. each of them will communicate over message broker or message queue.

 

Despite of the differences between these patterns, some might say that Publisher-Subscriber pattern is a variation of Observer pattern because of the conceptual similarity between them.

 

References:-

https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c

Publisher-Subscriber Pattern

 

How Publisher-Subscriber Pattern works?

In Publisher-Subscriber pattern, the publisher sends the messages and subscriber receives the messages. But both publisher and subscriber do not know about each other. That means the publisher does not know about the subscribers and  subscribers does not know about the publishers.  Both of them communicated through a middle layer known as message broker (message broker will have the knowledge of both publisher and subscribers).

e.g:-  Sending and Receiving messages using RabbitMQ message broker can be identified as a real world example of Publisher-Subscriber pattern.

The message broker will accept the messages from publisher and filter them based on some criteria and will do the required steps for delivering them to the right subscriber(s).  The message will be filtered based on different criteria depending on the underlying messaging broker implementation.  e.g:- In RabbitMQ, there will be different exchanges as Direct, Topic, FanOut and HeaderClick here if you want to see my articles on RabbitMQ message broker.

 

publisher-subscriber.gif

 

Are Publisher-Subscriber pattern and Observer Pattern same?

First of all i want to emphasize that Publisher-Subscriber Pattern is NOT the Observer Pattern. They are two different design patterns with some similar behaviors.

The  Subject in the Observer Pattern looks like the Publisher and the Observer can totally be related to a Subscriber of the Publisher-Subscriber Pattern. The Subject notify the Observers as how the Publisher generally notify its subscribers. That’s why most of the Design Pattern books or articles use ‘Publisher-Subscriber‘ notion to explain Observer Design Pattern. But there is another popular Pattern called ‘Publisher-Subscriber’ and it is conceptually very similar to the Observer pattern. In this article, we are going to learn about the Publisher-Subscriber Pattern.

Click here if you want to look at the Observer Pattern

 

The differences between Publisher-Subscriber and Observer pattern can be shown in the following  diagram.

pub-subVsObserver.jpeg

 

 

Lets summarize the differences between Publisher-Subscriber pattern and Observer pattern as follows.

  • In the Observer pattern, Subject maintains a list of Observers and therefore Subjects aware of how to notify observers when there is a state change occurs. Whereas, in Publisher/Subscriber, publishers and subscribers don’t need to know each other. They simply communicate with the help of middle layer message broker (or message queue).
  • In Publisher/Subscriber pattern, components are completely decoupled with compared to Observer pattern (In Observer pattern, Subject and Observers are loosely coupled).
  • Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).
  • Observer pattern need to be implemented in a single application address space. It will be implemented within the single application.  On the other hand, Publisher/Subscriber pattern is more of a cross application pattern. Publisher and Subscriber may resides in two different applications. each of them communicate over message broker or message queue.

 

Despite of the differences between these patterns, some might say that Publisher-Subscriber pattern is a variation of Observer pattern because of the conceptual similarity between them.

 

References:-

https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c

 

 

 

Layered (N-Tier) Architecture

 

If you need to learn about N-Tier  or Layered Architecture, you can find an ample of resources through google. So i am not expecting  to repeat the same traditional approach here.  The purpose of this article is to simply  discuss the each layer/tier  of N-Tier architecture with their purposes.

The most common architecture pattern is the layered architecture pattern. This is also known as the n-tier architecture pattern.

Components within the layered architecture pattern are organized into horizontal layers, each layer performing a specific role within the application (e.g., presentation logic or business logic). Although the layered architecture pattern does not specify the number and types of layers that must exist in the pattern, most layered architectures consist of four standard layers:

  • Presentation layer (known as view layer)
  • Application layer (known as controller layer)
  • Domain layer  (known as service layer)
  • Persistence layer (known as DAO layer)

The smaller applications may have only three layers, whereas larger and more complex business applications may contain five or more layers.Each layer of the layered architecture pattern has a specific role and responsibility within the application.

For example, a presentation layer would be responsible for handling all user interface and browser communication logic, whereas a business layer would be responsible for executing specific business rules associated with the request.

One of the powerful features of the layered architecture pattern is the separation of concerns among components. Components within a specific layer deal only with logic that pertains to that layer. For example, components in the presentation layer deal only with presentation logic, whereas components residing in the business layer deal only with business logic.

Lets look at what will be the responsibility of each layer and what will be containing inside that. 

 

Package by Features (1)

 

Presentation Layer

This is known as the presentation tier or view tier. This is the starting point of Layer where the end user interact with the application. This layer will contain the classes and components required to present/handle the UI (User interfaces) for the end users. typically JSP files, Filters, classes used to render UI components. In addition, this will have the components and classes to receive the user requests and sending responses back to the end users.

 

Application Layer

This is where the request validation and flow control will happen.  When user requests for a particular business operation, it will application later before going to the service/domain layer. In application layer, it will validate the user request to verify whether the request contain the enough information to handle the requested business operation. if it contains the required information, then it will be directed to the relevant business service reside in the domain/service layer.Otherwise, you will be notified about invalidity of the request (for the requested operation) through the presentation layer. So this will be the layer where your application business logics are controlled. (it decides whether to invoke the relevant servicer or not)This layer will not contain any business logic or domain specific services and it contains only the flow control and request validation logics.

 

Domain Layer

This is commonly known as the service layer. This contains all the domain specific business logic including service classes for business services , domain entities (domain classes) so on…

 

Persistence Layer

This is known as database layer or DAO layer. This contains the classes and components required to handle database related operations. Simply this contains the Repository classes, DAO classes and other classes that contains data access logic (HQL/SQL statements). All the Database related operations should be handled within this layer.

 

What is the Layers of Isolation?

The layers of isolation concept means that changes made in one layer of the architecture generally don’t impact or affect components in other layers: the change is isolated to the components within that layer, and possibly another associated layer (such as a persistence layer containing SQL). If you allow the presentation layer direct access to the persistence layer, then changes made to SQL within the  persistence layer would impact both the business layer and the presentation layer, thereby producing a very tightly coupled application with lots of interdependencies between components. This type of architecture then becomes very hard and expensive to change.

The layers of isolation concept also means that each layer is independent of the other layers, thereby having little or no knowledge of the inner workings of other layers in the architecture. To understand the power and importance of this concept, consider a large refactor‐ ing effort to convert the presentation framework from JSP (Java Server Pages) to JSF (Java Server Faces). Assuming that the contracts (e.g., model) used between the presentation layer and the business layer remain the same, the business layer is not affected by the refactoring and remains completely independent of the type of user- interface framework used by the presentation layer.

 

Final Observation

“Layered Architecture gives us nothing apart from a guideline on how to organize the source code.”

 

Benefits of a Layered Architecture

  • Simplicity – the concept is very easy to learn and visible in the project at first glance.
  • Consistent across different projects – the layers and so the overall code organization is pretty much the same in every layered project.
  • Guaranteed separation of concerns – just the concerns that have a layer and to the point that you stick to the rules of Layered Architecture, but it’s very easy with the code organization it implies.

 

Drawbacks of a Layered Architecture

  • No built-in scalability – Client does not request the layers, but request features. when the project grows with number of features, you need to find a key to organizing it further by yourself. The principles of Layered Architecture won’t help you.
  • Hidden use cases – you can’t really say what a project is doing by simply looking at the code organization. You need to at least read the class names and, unfortunately, sometimes even the implementation.
  • Low cohesion and high coupling – classes that contribute to common scenarios and business concepts are far from each other because the project is organized around separating technical concerns.Therefore the cohesion is low. In addition, each layer is tightly depend on the other layer and this increases high coupling.

 

References : 

https://dzone.com/articles/package-by-feature-is-demanded

http://www.oreilly.com/programming/free/software-architecture-patterns.csp