Understanding Recursion

Recursion is a concept not a data structure or an algorithm but a way we solve a problem.

It is just a way of breaking down a problem into sub problem and each of those problems is broken into more and more sub problem until we reach the base case.

To understand recursion lets imagine we want to count the number of male children in an extended family. In a single family(Super family) there could be other families i.e children of the family have their own children

Recursion enables us to perform the same method that calculates the number of male children in a family on the childrenâ€™s family

Let us see how it works

1. Define a class to represent a Child with properties, sex and family
1. Define a Class to represent Family with list of children as property
1. Write your method as follows;
• Check if there are no longer children in the family return 0 . This implies we have gone through all the children in family. This represents the base case.
• Declare a variable to hold the number of male children in the families
• Loop through all the children in the family and check which of the child is a male child, then increment counter by one
• Check if the child has his/her own family then call the method on the family

To use our method, define a list of children in a super family. Then define a list of children for one of the child in the super family.

Please note that every recursion must have a base case i.e the stopping point, otherwise the method will continue to call itself, like an infinite loop. in our above example the base is reached when we have a family without any children, in this case the children is null.

In conclusion, understanding how recursion works is a vital step towards understanding algorithms, become a better problem solver and ultimately a better programmer.

Strategy Design Pattern

Strategy design pattern is one of the behavioral design pattern.

Definition: The strategy design pattern defines a family of algorithms, encapsulates each one (makes it an internal property) and makes them interchangeable. Strategy makes the algorithm vary independently from the clients that use.

This implies that the client can determine which algorithm to use by passing it as a parameter

Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.

For our example, Imaging a travel company that has different means/strategy for transporting their customers to a location e.g to Abuja

First of all we will create the interface for our strategy pattern example in our case to transport customers

Now we create the different concrete strategy for transporting customers,which include by air, by bus etc for brevity we are only going to implement the by bus strategy

The client(orderconfirmed) can now determine the means of transportation at run time

Below is the UML diagram of the strategy design pattern