Software Design Principles

Software design principles represent a set of guidelines that helps us to avoid having a bad design.

The open –closed principle:

A module should be open for extension but closed for modification, can be extended, without requiring them to be modified. => able to change to module without changing source code, 2 ways:
a. Meyer’s Open/Closed Principle: the first principle, implementation of a class could only be modified to correct errors; new or changed features would require that a different class be created
b. Polymorphic Open/Closed Principle: the implementations can be changed and multiple implementations could be created and polymorphically substituted for each other.

The Liskov Substitution Principle

Subclasses should be substitutable for their base classes. Derived classes should be substitutable for their base classes. That is, a user of a base class should continue to function properly if a derivative of that base class is passed to it.

Dependency Inversion Principle

Depend upon Abstractions. Do not depend upon concretions, Dependency Inversion is the strategy of depending upon interfaces or abstract functions and classes, rather than upon concrete functions and classes.

The Interface Segregation Principle:

Many client specific interfaces are better than one general purpose interface. The essence of the principle is quite simple. If you have a class that has several clients, rather than loading the class with all the methods that the clients need, create specific interfaces for each client and multiply inherit them into the class.

Release Reuse Equivalency Principle

The unit of reuse is the unit of release. Effective reuse requires tracking of releases from a change control system. The package is the effective unit of reuse and release.

Common Reuse Principle

Classes that aren’t reused together should not be grouped together.

Stable Dependencies Principle

depend on the direction of stability

Information hiding and encapsulation

Information hiding is the principle of segregation of design decisions

Low coupling

Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other elements, Clear boundaries between tiers, program against interfaces, not classes.

High Cohesion

High Cohesion attempts to keep objects appropriately focused, manageable and understandable. High Cohesion is generally used in support of Low Coupling, High cohesion means that the responsibilities of a given element are strongly related and highly focused.

The Acyclic Dependencies Principle

The dependencies between packages must not form cycles.

Advertisements

Eliminate obsolete object references

Java is a garbage-collected language, your job as a programmer is “nullify” your reference

Consider the following simple stack implementation:

public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}

public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}

private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}

The program above has a “memory leak” can silently reduce the performance due to increased garbage collector activity or memory footprint => OutOfMemoryError

If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them.

The solution for this sort of problem is simple: null out references once they
become obsolete.

</pre>
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}

Another common source of memory leaks is caches. One you put object references into a cache, It’s easy to forget that’s is there and leave in the cache after it becomes irrelevant. The simple solution is using WeakHashMap, that the entries will be removed automatically after they become obsolete.

A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them
explicitly, they will accumulate unless you take some action. The best way to
ensure that callbacks are garbage collected promptly is to store only weak references
to them, for instance, by storing them only as keys in a WeakHashMap.

Consider a builder when faced with many constructor parameters

Static factories and constructors share a limitation: they do not scale well to large
numbers of optional parameters. Traditionally, programmers have used the telescoping constructor pattern or JavaBeans pattern

Telescoping constructor pattern

public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;
    public NutritionFacts(int servingSize, int servings) {
      this(servingSize, servings, 0);
    }
    public NutritionFacts(int servingSize, int servings,int calories) {
      this(servingSize, servings, calories, 0);
    }

    public NutritionFacts(int servingSize, int servings, int calories, int fat) {
      this(servingSize, servings, calories, fat, 0);
    }

    public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) {
       this(servingSize, servings, calories, fat, sodium, 0);
    }

    public NutritionFacts(int servingSize, int servings,
      int calories, int fat, int sodium, int carbohydrate) {
      this.servingSize = servingSize;
      this.servings = servings;
      this.calories = calories;
      this.fat = fat;
      this.sodium = sodium;
      this.carbohydrate = carbohydrate;
   }
}

The telescoping constructor pattern is hard to write client code when there are many parameters, and harder still to read it.

JavaBeans pattern

public class NutritionFacts {

   private int servingSize = -1;
   private int servings = -1;
   private int calories = 0;
   private int fat = 0;
   private int sodium = 0;
   private int carbohydrate = 0;
   public NutritionFacts() { }

   public void setServingSize(int val) {
       servingSize = val;
   }
   public void setServings(int val) {
      servings = val;
   }
   public void setCalories(int val) {
     calories = val;
   }

   public void setFat(int val) {
     fat = val;
   }
   public void setSodium(int val) {
     sodium = val;
   }

   public void setCarbohydrate(int val) {
     carbohydrate = val;
   }
}

JavaBean may be in an inconsistent state partway through its construction
Consider builder pattern as a alternative

// Builder Pattern
public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;
    public static class Builder {
       private final int servingSize;
       private final int servings;
       private int calories = 0;
       private int fat = 0;
       private int carbohydrate = 0;
       private int sodium = 0;
     public Builder(int servingSize, int servings) {
       this.servingSize = servingSize;
       this.servings = servings;
     }
     public Builder calories(int val)
     { calories = val; return this; }
     public Builder fat(int val)
     { fat = val; return this; }
     public Builder carbohydrate(int val)
     { carbohydrate = val; return this; }
     public Builder sodium(int val)
    { sodium = val; return this; }
    public NutritionFacts build() {
        return new NutritionFacts(this);
    }
   }
   private NutritionFacts(Builder builder) {
     servingSize = builder.servingSize;
     servings = builder.servings;
     calories = builder.calories;
     fat = builder.fat;
     sodium = builder.sodium;
     carbohydrate = builder.carbohydrate;
  }
}

Builder pattern is much easier to read and understand what is going on. The pattern gives you the impression that you can use named optional parameters.

How to use

</pre>
<pre>NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();

Happy creating objects !

How To Set Up Icinga 2 on Windows Server

Because Icinga 2 does not support Windows server, we need to install Virtual Box with Ubuntu (or any  Linux distributions)

Install Icinga 2 Server

On Ubuntu virtual machine, open terminal

sudo su
sudo apt-get update
sudo apt-get upgrade

1

Now add the Icinga repository:

sudo add-apt-repository ppa:formorer/icinga
sudo apt-get update

icinga2

sudo apt-get install icinga2

icinga3

Install Data Output Module

sudo apt-get update

sudo apt-get install mysql-server icinga2-ido-mysql

#Database configuration select Yes

sudo icinga2-enable-feature ido-mysql

sudo systemctl restart icinga2

icinga4

icinga5

icinga6

icinga7

Enable ido-mysq module and restart Icinga 2

icinga2 feature enable ido-mysql

icinga8

Install Icinga2 nagious plugin

Icinga2 will collect the service information based on the monitoring plugins. Here we’re installing nagios plugins for this function.

apt-get install nagios-plugins

icinga9

Install Icinga2 Web module

apt-get install icingaweb2

icinga10

Once this is installed, we can call this URL in browser to “http://localhost//icingaweb2/setup“.

Step 1 Create token

icinga11

The initial setup page come up with a message to authenticate our Icingaweb user and create a token to proceed with the configuration.

sudo addgroup --system icingaweb2;

usermod -a -G icingaweb2 www-data;

icingacli setup config directory --group icingaweb2;

icingacli setup token create;

icinga12

icinga13

icinga14

icinga15

Step 2: Select the Modules

After providing the token, it’ll move to the next section for selecting the modules. We can choose the preferred modules to proceed to the next step.

icinga16

Step 3 : Verifying the PHP settings

icinga17

open /etc/php/7.0/apache2.0/php.ini

set date.timezone = Europe/Zurich (for example)

restart apache2.0

sudo service apache2 restart

 

Step 5: Authenticating Methods

 

icnga18

icinga18

Step 7  Create Icinga Web administration users to manage the interface

icinga19

icinga20

icinga21

Step 6: Review all chosen settings

icinga34

Step 7: Configure Monitoring Module

icinga23

configure with  IDO module

icinga24

icinga25

icinga26

icinga27

Review Monitoring Configuration

icinga28

icinga31

icinga30

Icinga 2 configuration

icinga2 node wizard

#Please specify this is satellite set up (y/N): n

#Please specify the common name(CN): icinga2-master

systemctl restart icinga2

icinga29

Windows firewall, VirtualBox network mode and port forwarding settings

VirtualBox network settings

choose setting, in Network, choose NAT

icinga35

Configure Port forwarding

We forward  2 ports 5656 and 8000 from the host to virtual machine. Port 5656 is used for client, and port 8000 is used for web monitoring tools

icinga36

Configure Windows firewall

Open windows firewall, new inbound rule and choose type of rule is program

win1.jpg

Choose the program path

win2

choose allow theconnection

win3

win4

Give it a name

win5

Add a new Host

Create ticket for new host

create new ticket for business-icinga2-client (*)


icinga2 pki ticket --cn business-icinga2-client

client1

Install Client

Download icniga 2 client http://packages.icinga.org/windows/

client2

client3

client4

client5

client6.jpg

Configure Windows client

client instance name: business-icinga-client

ticket generated in (*)

server instance name: icinga2-master

host: ip server that host icinga 2

client7.jpg

client8.jpg

 

client9

restart icinga2 service


net start incinga2

Update Master configuration

Check business-icnga-client in the node list


icnga2 node list

master1


icnga2 node update-config

master2

verify configuration


icinga2 daemon -C

master3


systemctl reload icinga2

Open browser, http://82.195.230.21:8000/icingaweb2/,

master4

Consider static factory methods instead of constructor

The advantages of static factory method

  • Unlike constructor, static factory methods have name
  • Not required to create a new object each time they’ve invoked
  • They can return an object of any sub type of their return type
  • The class of the object returned by a static factory method need not even exist at the time the class containing the method is written. Such flexible static factory methods form the basis of service provider frameworks, such as the Java Database Connectivity API (JDBC).

The Disadvantage

  • The main disadvantage of providing only static factory methods is that
    classes without public or protected constructors cannot be subclassed.
  • Factory methods are not readily distinguishable from other static methods. You can avoid this by drawing attention to static factories in classes or interface comment, Some common names for factory methods are valueOf, of, getInstance, newInstance, getType, newTyp Continue reading

Session State

This post talks about the differences between business and system transactions underlie much of the debate over stateless versus stateful sessions

Statelessness

Stateless means there is no record of previous interactions and each interaction request has to be handled based entirely on information that comes with it. To be more understandable, that means an object not doesn’t retain state between request.

Stateful means server keeps track a list of objects and this list must persist between requests.

The statefull server are cost of resources. If we want to track a user’s requests with a
stateful server object, we must have one server object per user. But 90 percent of the time they are just sitting around doing nothing.  The point is that, if we have no state between method calls, it doesn’t matter which object services the request, but if we do store state we need to always get the same object. Statelessness allows us to pool our objects so that we need fewer objects to handle more users. So, statelessness also fits in well with the Web since HTTP is a stateless protocol.

The problem is that many client interactions are inherently stateful. The good news is that we can use a stateless server to implement a stateful session;

Session State

Session state is within a business transaction, which means that it’s separated from other sessions and their business transactions. Session state is distinct from record data, which is the long-term persistent data held in the database and visible to all sessions. Session state needs to be committed to become record data.

Not all data held by the session counts as session state. The session may cache some data that doesn’t really need to be stored between requests but is stored to improve performance. Since you can lose the cache without losing correct behavior, this is different from session state.

Store Session State

Client Session State (CSS) stores the data on the client. There are several ways to do this: encoding data in a URL for a Web presentation, using cookies, serializing the data into some hidden field on a Web form, and holding the data in objects on a rich client. Small data, encrypt data. Using CSS State for data that is pretty small, because CSS implies that with every requests, you have to transfer all data the server uses for it. And you need to worry about security and integrity.

Server Session State there’s a mechanism for storing the session state somewhere more durable as a serialized object. The object can be stored on the application server’s local file system, or it can be placed in a shared data source. This could be a simple database table with a session ID as a key and a serialized object as a value. Usually the Server Session State is the easiest on development resources, particularly if you don’t have to persist the session state between requests. A Good implementations of Server Session State should allow you to do clean session state after the period of time(automatic timeout operation).

Database Session State is also server-side storage, but it involves breaking up the data into tables and fields and storing it in the database much as you would store more lasting data. Since session data is isolated, you have to work hard to isolate the session data between users.

You can use a mix of two or three of them to store different parts of the session state. This usually makes things more complicated, however, as you’re never sure which part of the state goes in what part of the system. When doing this, you should keep at least a session identifier in Client Session State  even if the rest of the state is held using the other patterns.

Reference: Pattern of Enterprise Application,  Martin Fowler Continue reading