Design Patterns Examples in Java – Builder Design Pattern

Builder design pattern

Builder design pattern

Have you ever created an object that has over 20 fields ?, have you ever tried to create this object using it’s constructor with several lines of code ? Have you ever needed to create an object without knowing its exact number of fields ? no worries, meet the Builder design pattern. 

Builder design pattern is an awesome pattern that eases the construction of complex objects.

Read moreDesign Patterns Examples in Java – Builder Design Pattern

Design Patterns Examples in Java – Factory Pattern

Creational Design Patterns

Factory Pattern

In part one of this series of design patterns articles we introduced design patterns, here we start with the first category of design patterns, as GOF describes , creational design patterns and the first one of them, is Factory Pattern .  

As the name describes, creational design patterns are about creating objects. They deal with objects creation mechanisms, trying to create objects in a way suitable to the situation. Creating objects using the basic form ( the new keyword in Java ) sometimes creates undesired designs like hard coded values, long constructors, and other complex situations. Creational design patterns tries to solve these problems in the best possible way.   

Read moreDesign Patterns Examples in Java – Factory Pattern

Design Patterns Examples in Java – Introduction

Design Patterns

Introduction

This article represents an introduction to the world of design patterns. 

In my collection of design patterns articles, I try to introduce them from a different, more practical angle, than other articles I found online.

Most articles try to explain design patterns in an abstract way, and give approximate examples of them hoping they can be understood. I, on the other side, find it difficult to understand them that way. I prefer to have a real code example of each design pattern. So, let’s get started ! 

Read moreDesign Patterns Examples in Java – Introduction

Transaction Isolation levels, examples in Java with MySQL

Isolation levels

Introduction

Before we demonstrate Isolation levels, we must define transactions and what ACID model is. Isolation levels are one of ACID model properties, Isolation.

A Transaction represents a collection of operations executed sequentially as one single operation. Consider the well know example of money transfer between two bank accounts of Alice and Bon. Money transfer involves the following operations: 

  1. Read Alice’s account, by issuing a select statement, to check if Alice has X-amount or more for the transfer. 
  2. Read Bob’s account, by issuing a select statement, to check if Bob’s account can receive money. 
  3. Decrease Alice’s account by X-amount of money. 
  4. Increase Bob’s account by X-amount of money. 

In RDBMS for a unit of work to qualify as transaction it must comply to ACID model. So, what is ACID model ?

Read moreTransaction Isolation levels, examples in Java with MySQL

User stories INVEST model, do you really invest ?

User stories INVEST model,

User stories describe software functionalities that are valuable to either a user or purchaser of that software. In other words, they describe what the user can do with the software.

User stories also allow business guys (product owners, stake holders, business analysts ) to describe what functionalities the software has to cover. At the same time they allow the developers to analyze, decide on how-to, and estimate time for development. 

Almost every software project nowadays is developed in an agile development style. Depending on the team, each has its approach to be agile, sometimes they are truly agile more often they are not. 

The two main groups that participate in project development are the tech guys (developers) and business guys. Sadly,more than often, they don’t speak the same language, though they have one goal, the success of the project in hand. User stories help the communication between the two.

One of the most common problems I observe, when working on projects, is misunderstanding the INVEST model of user stories. Failing to craft user stories following the INVEST model has many consequences. Delivering a wrong functionality, duplicating the work by two or more developers, blocking one developer during development, etc … are all examples of such consequences. But what makes a good user story?

User stories have a common form that they follow, though it is not mandatory. 

As (user)/(admin)/(someone who will user the software) I want to be able to (some action), so that (the outcome value) 

Example: 

As a user I want to be able to store photo, so that I can view it later. 

The INVEST model of user stories. 

The INVEST model stands for (I)ndependent (N)egotiable (V)aluable (E)stimatable (S)mall (T)estable. 

Independent 

A story is independent when its implementation doesn’t depend on other stories. Consider the following stories: 

As a user I want to filter books by name 

As a user I want to filter books by ISBN  

The first story depends, and duplicates, the second story, the path to implement the first story is pretty much similar, if not the same, to the second story. 

Dependencies between stories lead to prioritization and planing problems, efforts duplication during development, and difficulties during merging codes. 

Many times I have been forced to delete my code or my colleagues code because our code was 90% the same and the only thing we really needed was to parameterize some methods and refactor some classes. For each story you are writing, ask yourself if developers would block each other. if so, this two stories are highly dependent and they should be made as one. If merging these two stories seems to be impossible for some reason (like the business analyst, or any author of user stories, thinks he is the chosen one and his stories are prefect) it is highly recommended for those two stories to be linked and implemented by one developer. 

Recently me and my colleagues were working on the following “user stories”:

Fetch vacation from X system to our application.

User should see fetched vacations in his calendar.  

Apart from the fact that the first “story” looks like anything but a user story, they depend on each other. And here is what happened. 

I implemented a service that fetches these vacations from X system and saves them to our database. We implemented saving these vacations by a Repository interface, for some reason I needed to have not only save method but fetch method, here is what happened :

When the time to merge our ‘stories’ came, we had to remove one of the repositories and it`s implementations, than refactor the remaining one. This added extra effort to our original work, which also made our original estimation of stories wrong, in the eyes of project manager and product owner. One of us implemented a repository that we later deleted. Apart from the fact that we needed additional work to finish our task, I was a bit disappointed, and demotivated when I had to delete the code I’ve written with passion and covered by tests. The team should pay extra attention to avoid user stories coupling. 

Sometime, however, it is tricky to decouple user stories. If this is the case, in order to avoid code merge conflicts, it is advisable one developer to implement all dependent user stories. 

 

 

Valuable 

Stories must be valued by users, software purchaser, or some 3rd party software. When writing user stories it is important to ask the question what value it adds for the mentioned groups. 

Consider a bookstore application and the following story: 

Users should store books in MySQL DB.  

Now, what value does this story, for the users,  have ?, no value ! First, the user, most probably, won’t know what MySQL DB is. Second, even if he knows, there is no value in  merely storing books in some storage engine that is MySQL? What the user actually values (needs) is probably to be able to retrieve a stored book and explore it or download it. The story can be written as:

User should be able download a stored book.

or

User should be able to explore a stored book.  

These two stories in them self include storing the book. 

In general, avoid stories that only developers value like: 

A connection pool should be used to connect to DB. 

Sl4j logger should be replaced.

MySQL database should be used  

At the end of the day, developers should add value to the software that solves users problems not developers problem ! 

Estimatable

Developers should be able to give time estimation for the story, or at least take a guess. A couple of reasons developers may be unable to do so. 

Lack of domain knowledge. Domain knowledge is gathered from users and domain experts thus developers should sit and question. 

Lack of technical knowledge. 

System can authenticate users using their social profiles. 

If none of the team members has ever done that before, the team should split the story into two, a spike and the actual story.Spikes represent small exploratory and research actions for gathering some technical knowledge. Developers give spikes maximum amount of time called (time-box). After the spike developers should be able to give an estimation.

The story is too big. In this case, the team should split the story into smaller stories, without introducing dependency between stories, or at least try not to.    

Small 

Small may be not the so proper, in my opinion, I prefer the term moderate. If they are, developers will find them hard to use in planing and estimation. 

Big stories fall into two categories, compound stories and complex stories. Consider the following story, as an example of the first type. 

User can create a personal profile. 

A story for a social media application. Creating a personal profile can include adding personal information, adding a photo, connecting the profile to other social media, verification via email, SMS, and so on. 

An example of complex is a story that, for some reason, developers find it hard to implemented. Introducing new technologies and adding new algorithms to the projects are an example of complex stories.

User can update his membership by paying with credit card. 

Maybe none of the team members have ever implemented credit card payments.This is a complex story, that the team needs to split into spike and implementation. In our case one or two team members can start a spike to learn how to implement payment via credit cards. 

Sometimes things go to opposite direction. Stories become too small. Too small that developers don’t even want to estimate them or even write them down. One of the teams I was working with created stories so small that I was taking more time to go back and forth to Jira than doing real job.

Stories like:

User can add his birth date.

User can add his name.

User can add his hobbies.

 Are very small and they actually fall under one user story. 

Use can add personal information to his profile. 

The most problematic issue when creating small user stories is that usually they are dependent. More frightening is distributing these stories among the team. There for sure, will be more work to resolve code merges conflicts than to implement each story.

 

Testable

Stories must be testable. Otherwise how can developers tell that they have done the job right?! Untestable stories commonly come from non-functional requirements.

User should find the software easy to use.

User should find the software fast to use.  

Easy and fast are relative, what I find easy and fast may not be the same for you.  Instead, one can reform stories to:

90% of the new users should be able to find how to do “something work” without any previous tutorial. 

The UI should respond in no more than 1 second 99% of the time. 

 

Writing user stories is not complex neither easy task to do. But at the end one should try to come as close as possible to the INVEST model. It is not always possible but at least try it. 

I rarely spot well written user stories. However, what scares me the most is the fact that , most often, worst stories are written by people with at least two titles in front of their names. 

When writing user stories ask these questions: 

User stories INVEST model
User stories INVEST model

 

References: UserStories Applied 

Deep Working Philosophies, Choose The One Suites You.

Deep Working Philosophies, Choose The One Suites You.

Deep Working Philosophies

Deep working philosophies define different approaches for different achievements depending on your availability to disconnect. Here are four types of deep working philosophies as defined in the book “Deep Work, Rules for Focused Success in a Distracted World” by Cal Newport.

 

The Monastic Philosophy 

Completely, or almost completely, disconnect from the word. The monastic philosophy of deep working is based on the idea of minimizing as much as possible of shallow obligations. People who practice this type of deep working are generally hard to find or connect with in some way. They are also characterized with well defined high valued and complex professions. Researchers, novelists, and scientists are examples of such people. They do one thing exceptionally well and focus only on it. They are hard to replace kind of people.

By default they are in a mode of disconnection from the outer world. For example they spend 5-6 days a week doing what they do best, without a distraction.   

 

The Bimodal Philosophy. 

When you can’t completely disconnect yourself from the out side world. This philosophy emphasizes on dividing the time between completely deep working and shallow activities. The division is strictly defined. The division can happen on multiple scales, scale of week, scale of month,or scale of year. For example, on scale of week one can dedicate 3 days a week completely disconnected and focused on his work. On scale of month, dedicating the first two weeks of work can do the job. During deep working period the worker acts monastically as if he practices the monastic philosophy. However, he is completely shallow in the rest of the time. A worker that practices this philosophy attempts to reach maximum cognitive intensity, in contrast of rhythmic philosophy. This is why the minimum unite of work is one day.  

 

The Rhythmic Philosophy (The chain method). 

The idea behind this deep working philosophy is to maintain a chain of a deep working sessions. The deep working chain can be monthly, weekly, or daily. For example, you conduct deep working every day from 5:00 – 7:00 AM. The most important thing here is trying not to break the chain. This method is widely adopted by body builders and other sportsmen, not only thinker workers. 

Rhythmic deep working makes it easy to start deep working as it turns it to a regular habit. The goal in other words is to generate a rhythm for deep working, this rhythm eliminates the need to invest energy in deciding if and when to go deep. When something becomes a habit it becomes more pleasant and easy to do, enjoyable when it has been done. 

This philosophy is a good fit for people who have a full-time job and can’t disconnect for a couple of days as in the bimodal philosophy. This philosophy provides an interesting contrast to the bimodal philosophy. It maybe fails to achieve the deepest, most intense, levels of concentration and deep thinking as in the day-long concentration sessions. By the time your brain goes in its deepest thinking you’ll have to finish the session. You simply don’t have all day long. 

 

The Journalist Philosophy. 

This method can be summarized as: work whenever you find some time. At first, this philosophy can look very easy to conduct. You don’t setup any schedule, or try to create an unbreakable chain of deep working sessions. Just work when you get a chance. The facts are opposite.  Switching to deep working in a short period of time is not an easy task. One has to be trained to shift between deep working and regular state of mind. This philosophy is not suitable for deep working novice. With practice, being confident in what you do, and considering the fact the conducted work is important you can start implement this method.

Let me give some examples. A meeting is rescheduled, now some space of two hours is opened, grab you laptop, books, whatever tools you need to let your mind dive deep. If you are a father and your children are sleeping or doing something that frees you from babysitting them this is another chance to deep work.

Depending on what your job is, what you try to achieve, and your current experience in going deep, pick the philosophy that suits you best. You can also be creative and craft your own philosophy. The goal at the end of the day is to do the job the best way It can be done ! 

 

Trees – Simple Operations and Traversal.

Trees

This article is a simple summary of most frequently performed operations over tree data structure. As an enterprise Java developer I don’t usually deal with traverse or other calculations with trees, There are already well designed and tested libraries to do the job. However, interviewers usually like to ask these questions and give you task or two – to be done on paper- that involves these operations.

For basic definitions of trees check my previous article. 

 

Trees Nodes
Tree Nodes

 

This factory creates the simple tree in the picture: 

Find the high of tree.

Pre-order tree traversal

Traversing a tree means visiting its node, to find if some value exists in that tree.

Pre-order traversing means do something with the current node (visit the node),display the value of it for example , traverse the left sub-tree then the right sub-tree recursively.

Algorithm: 

  • Display the data part of the root (or current node).
  • Traverse the left subtree by recursively calling the pre-order function.
  • Traverse the right subtree by recursively calling the pre-order function.

Post-order

The root node is visited last. First left subtree is traversed, then right subtree and finally root.

Algorithm: 

  • Traverse the left subtree by recursively calling the post-order function.
  • Traverse the right subtree by recursively calling the post-order function.
  • Display the data part of the root (or current node).

Outcome: 7 > 0 > 5 > 8 > 7 > 1 > 3 > 5 >

In-order

Algorithm:

  • Traverse the left subtree by recursively calling the in-order function.
  • Display the data part of the root (or current node).
  • Traverse the right subtree by recursively calling the in-order function. 

Outcome: 8 > 7 > 5 > 0 > 7 > 5 > 3 > 1 >

Graph Algorithms – Definitions.

Grapths Algorithms

This post represents a brief introduction to graph algorithms. When study I usually use to use paper and write a summary for what I read to better understand, analyze, and memorize what I am studying. 

Instead of using paper, this time, I decided to use my nice little blog as someone else can benefit from it. Reference of the definitions and books are provided at the end of this post. 

My mind, on the other hand, better works by visualizing things so I’ve done my best to draw pictures of the definitions mentioned in this post. 

1- Graph: graph G = (V, E) consists of a set of vertices, V, and a set of edges, E.

  •  Each edge is a pair (v, w), where v, w ∈ V. Edges are sometimes referred to as arcs.

Graph

  • There are two type of graphs, directed and undirected

directed graph

  •  Directed graphs are called digraphs. 
  • Vertex w is adjacent to v if and only if (v, w) ∈ E. In other words if the w and v are connected with only one edge. The edge E is consisted of w and v.

adjacent

  • In an undirected graph E is represented either by (v,w) or (w,v), the direction is both ways, it is undirected right ? 

different edge

  • In a directed graph (v,w) is a different edge than (w,v).
  • An edge can have a weight or sometimes called cost. In a geographical  map this can represent the distance between two points, for example. 

fifth -Weight

2- Path: A path in a graph is a sequence of vertices w 1 , w 2 , w 3 , . . . , w N such that (w i , w i+1 ) ∈ E for 1 ≤ i < N. 

  • The length of such a path is the number of edges on the path, which is equal to N − 1 
  • There is always a path from every vertex to itself and its length is 0, this is intuitive.
  • loop, this represents an edge (v, v) i.e a path from a vertex to itself.  

Path

  • A simple path is a path such that all vertices are distinct, except that the first and last could be the same. (wiki definition: a simple path is a path in a graph which does not have repeating vertices)   

simple path

3- Cycle: A cycle in a directed graph is a path of length at least 1 such that w 1 = w N ; this cycle is simple if the path is simple. In other, more intuitive words a cycle is a path that ends at the same vertex that it started from. 

a cycle

  • The is no cycles in an undirected graph, why is that? well because very edge is considered as a a cycle as it has both way from v -> w and from w->v. 

No cycles in directed graphs

  • A directed graph is acyclic if it has no cycles 

acyclic if it has no cycles

  • A directed acyclic graph is sometimes referred to by its abbreviation, DAG 

4- Some more points :  

  • An undirected graph is connected if there is a path from every vertex to every other vertex. 
  • A directed graph which is connected (there is a path from every vertex to every other vertex) is called strongly connected.
  • If a directed graph is not strongly connected (there is NO a path from every vertex to every other vertex), but the underlying graph the one without direction to the arcs or in other words the same graph after removing directions of edges is connected, then the graph is said to be weakly connected. In other words, a directed graph is called weakly connected if replacing all of its directed edges with undirected edges produces a connected (undirected) graph. 
  • A complete graph is a graph in which there is an edge between every pair of vertices 

5- References: