• Home
  • Quick Bytes
  • Algorithms
  • Java
  • iOS
  • Android
  • Certifications
  • About Me

Lets Code Them Up!

  • Observer Pattern

    January 8th, 2023

    Observer pattern is one of the behavioral design patterns used in object oriented world of programming. 

    Definition – Observer pattern defines a one-to-many relationship between objects. When state of one object changes, all the dependent objects are notified and updated.

    There is a Subject interface and a ConcreteSubject that implements the Subject interface. There is an Observer interface and multiple observers implementing that interface. Observers use the Subject interface to register and unregister and also to get notified about the changes. Observer interface generally has one function that is called by the Subject whenever there is a state change.

     

    Observer Pattern

    One way to visualize this is the newspaper subscription in the real world. As soon as a newspaper is published, all the subscribers get the new copy. 

    In java, common example of observer pattern are Observer interface, EventListeners in awt and swing, Observable, JMS etc. 

    Best to use an example to understand this pattern. 

    Usecase – Let’s say there is a pantry containing items. And there are different shopping lists based on different stores we visit. As soon as any item in pantry finishes we want to add that item to all the shopping lists. 

    Visualizing Observer Pattern for Shopping list

    Pantry is our subject. KitchenPantry is concrete subject implementing the Pantry interface. SuperStoreList is our observer interface. CostcoList and WalmartList are our observer. Both observers can register using the attach method and deregister using the detach method. As soon as the item is removed from KitchenPantry, it will be added both the observer’s lists using the update method. KitchenPantry will use notify to call that update method. 

    public interface Pantry
    {
    
          public void attach(SuperStoreList list);
          public void detach(SuperStoreList list);
          public void notify();
    }
    
    public interface SuperStoreList 
    {
          public void update(String item);
    }
    
    public class KitchenPantry implements Pantry
    {
          private List<SuperStoreList> superStores;
          private String item;
    
          public KitchenPantry()
          {
                 superStores = new ArrayList<SuperStoreList>();
          }
          
          public void attach(SuperStoreList list)
          {
                  superStores.add(list);
          }
    
          public void attach(SuperStoreList list)
          {
                  superStores.remove(list);
          }
    
          public void notify(String item)
          {
                  for(SuperStoreList list: superStores)
                  {
                        list.update(item);
                  }
          }
    
          public void setItem(String item)
          {
                  this.item = item;
                  itemAdded();
          }
    
          public void itemAdded()
          {
                  notify(item);
          }
    
    
          public String getItem()
          {
                  return this.item;
          }
    
    }
    
    public class CostcoList implements SuperStoreList
    {
    
          private List<String> costcoList;
          private KitchenPantry kitchenPantry;
    
          CostcoList(KitchenPantry kitchenPantry)
          {
               costcoList = new ArrayList<String>();
               this.kitchenPantry = kitchenPantry;
               kitchenPantry.attach(this);
          }
    
          public void update(String item)
          {
               costcoList.add(item)
          }
    
          public void display()
          {
              System.out.println("Costco list : ");
              for(String item : costcoList)
              {
                   System.out.println(item);
              }
          }
    }
    
    public class WalmartList implements SuperStoreList
    {
    
          private List&lt;String> walmartList;
          private KitchenPantry kitchenPantry;
    
          CostcoList(KitchenPantry kitchenPantry)
          {
               walmartList = new ArrayList&lt;String>();
               this.kitchenPantry = kitchenPantry;
               kitchenPantry.attach(this);
          }
    
          public void update(String item)
          {
               walmartList.add(item)
          }
    
          public void display()
          {
              System.out.println("Walmart list : ");
              for(String item : walmartList)
              {
                   System.out.println(item);
              }
          }
    }
    
    public class App
    {
           public static void main(String[] args)
           {
                 KitchenPantry kitchenPantry = new KitchenPantry();
                 CostcoList costcoList = new CostcoList(kitchenPantry);
                 WalmartList walmartList = new WalmartList(kitchenPantry);
    
                 kitchenPantry.setItem("milk");
    
                 costcoList.display();
                 walmart.display();
    }
    

    Hope this helps. Thanks for stopping by. 

  • Clean Architecture – Chapter 1

    March 8th, 2021

    What is design? What is architecture? This chapter is based on these two questions. According to the author, both are the same. One cannot be present in place of the other.

    To illustrate their sameness, he uses the example of an architect who designs a home. The architecture of the home not only contains the overall layout of rooms and floors (software architecture – high level) but also the minute details like places for sockets, doors, pipes, etc. (software design – low level).

    The goal of software architecture is to minimize the human resources that are needed to build and maintain the required system.

    – Robert Marti, Clean Architecture

    When is a design good – If the effort needed to build a system is low and stays low throughout the development and maintenance, then only the design is good.

    The author gives example from a real company, whose initial development costs were low, but they became super high over the years. On further analysis, one could see number of lines of code not increasing, but cost per line of code increasing as number of developers increased over the years.

    Through his example, he wants to show the consequences of bad design. He explains that in the rush to deliver to market quickly, the developers do not take time to design right before coding, resulting in a system that gets complicated with the addition of new features over time, becoming more and more expensive. Thus spending more time on the development of new features later. Instead, if they had taken time to design right before starting the implementation, they would have spent more time in the beginning, but the overall same amount of time if we combine the time spent on new features later.

    Thanks for stopping by.

  • Clean Code Notes – Formatting

    January 12th, 2021

    Notes from the book Clean Code

    • Vertical Formatting – Files should be 200 lines to 500 lines long. Smaller files are easier to read than the longer ones.
    • Have spaces between different sections of code, improves readability.
    • The vertical distance between closely related concepts should be less.
    • Caller function should be above callee function and vertical distance between both should be minimum.
    • Horizontal Formatting – length of each line should be small, proper indentation, spaces at right places.

  • Clean Code Notes – Comments

    January 6th, 2021

    Notes from the book Clean Code

    • When comments are good –
      • legal comments
      • providing information eg – information about an abstract method.
      • explaining intent
      • clarifying some obscure argument or return value.
      • add warnings
      • for TODOs
      • java docs
    • When comments are bad –
      • any comment that makes you look at other parts of code to understand it’s meaning.
      • redundant comments, not required as the code itself is explanatory, might even confuse/mislead the reader. Unnecessary comments even obscure and reduce readability, eg, too many Javadoc comments.
      • journal comments
      • Javadoc comments before every method and variable are too much. Javadocs in nonpublic methods
      • Misleading comments
      • Position markers
      • the comment that could have been code.
      • Function headers
      • comments with too much information
  • Clean Code Notes – Functions

    January 5th, 2021

    Notes from the book Clean Code.

    • Functions should be small. They should max 20 lines long. An ideal function should be just 2-5 lines solving only one purpose.
    • The if/while/loop blocks should be one line long, which means they should enclose another function call.
    • A function should do only one thing. One level of abstraction per function. If a function does only those steps that decompose the name of the function, it is doing only one thing and it is at one level of abstraction.
    • The Stepdown Rule – Every function should be followed by another function which is the next level of abstraction. One should be able to read the functions top-down like reading a narrative.
    • The Switch Statement –
      • cannot be reduced in size.
      • violates the Single Responsibility Principle as there is more than one reason for it to change.
      • moreover, it can grow with the addition of new conditions.
      • A Solution is to bury the switch statement in the basement Abstract Factory and let no one see it. The factory will then use the switch statement to create appropriate instances of the derivatives of the object. [ Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes. ]
    • Use descriptive names. Don’t be shy of using long names.
    • Be consistent in names, use similar phrases, nouns, and verbs.
    • Try to limit arguments. Best is no argument, next best is one argument. Multiple arguments make reading functions difficult as well as testing them.
    • Monadic functions ( functions with one argument) should always return something.
    • Diads and Triads functions are difficult to read and grasp and should be avoided whenever possible.
    • Multiple arguments can be clubbed into objects, which can reduce arguments.
    • Have function names with verbs(intent) and keywords. eg assertEquals can be changed to assertExpectedEqualsActual, which can help remove the need to remember the ordering of arguments.
    • Avoid output arguments, if the function changes the state of something then let it change the state of its owning object.
    • Return exceptions instead of returning error codes.
      • With exceptions, one can separate the error path from the happy path
      • With error codes, there is usually a file maintaining that error codes, which can change any time, making the dependencies to change as well. With exceptions, we can avoid this.
    • The code inside try-catch blocks should be moved to separate functions of their own.
    • Dijkstra’s rule of structured programming – every function should have exactly one entry and one exit, ie no break/continue/goto, and a single return statement. With small functions, we can have multiple return statements and break/continue.
  • Find Numbers with Even Number of Digits

    August 14th, 2020

    Given an array nums of integers, return how many of them contain an even number of digits.

    Example 1:

    Input: nums = [12,345,2,6,7896]
    Output: 2
    

    Example 2:

    Input: nums = [555,901,482,1771]
    Output: 1 
    

    Solution

    1. Loop through Array
    2. Find number of digits in each number
    3. Increase counter by 1 if number of digits in the number is even
    /**
     * FindNumbersWithEvenNumberOfDigits.java
     * Purpose: Find Numbers with Even Number of Digits
     *
     * @author Megha Rastogi
     * @version 1.0 08/09/2020
     */
    class FindNumbersWithEvenNumberOfDigits {
    
        /**
         * Find Numbers with Even Number of Digits
         *
         * @param Array, nums
         * @return integer, numberOfEvenDigitNumbers
         */
        public int findNumbers(int[] nums) {
            
            // initialize the variable to store the count of
            // even digit numbers
            int numberOfEvenDigitNumbers = 0;
            
            // loop through the array and increase the counter
            // if number of digits are even
            for(int num: nums){
                if(numberOfDigits(num) % 2 == 0)
                    numberOfEvenDigitNumbers++;
            }
            
            //return the result
            return numberOfEvenDigitNumbers;
        }
        
        /**
         * Find number of digits in an integer
         *
         * @param integer, num
         * @return integer, numberOfDigits
         */
        public int numberOfDigits(int num){
            
            // initialize the counter to store number of digits
            int numberOfDigits = 0;
            
            // loop until number is greater than 0
            // Continuously divide num by 10
            // increase the numberOfDigits by 1
            while(num > 0){
                num /= 10;
                numberOfDigits++;
            }
            
            // return  the result
            return numberOfDigits;
        }
    }
    

    Source – Leetcode

    Code – FindNumbersWithEvenNumberOfDigits.java

←Previous Page
1 … 7 8 9 10 11 … 22
Next Page→

Proudly powered by WordPress

 

Loading Comments...