Agnes  Sauer

Agnes Sauer

1594923840

Principles, Patterns, and Practices

Table of contents

What is Infrastructure as Code

Key Principles

_- _Idempotency

_- _Immutability

Patterns and Practices

_- _Everything in Source Control

_- _Modularize and Version

_- _Documentation

_- _Testing

_- _Security and Complaince

_- _Automate Execution from a Shared Enviornment

_— _Infrastructure as Code Pipeline

_— _GitOps

Conclusion

Notes:

1. There is a certain level of Organizational maturity needed to use these Principles, Patterns, and Practices. This article is not focused on the cultural side of things but it is very important for the successful adoption of these.

2. Examples used in this article are using Terraform and AWS but these Principles, Patterns, and Practices are generic and can mostly be applied to other IaC tools like PulumiCloudFormation, etc. and Cloud Providers like GCP and Azure or even On-Premise.

What is Infrastructure as Code?

Infrastructure as Code (IaC) is an approach that takes proven coding techniques used by software systems and extends it to infrastructure. It is one of the key DevOps practices that enable teams to deliver infrastructure, and the software running on it, rapidly and reliably, at scale.

If you want to achieve Continuous Delivery for your applications, having a rapid and reliable, provisioning mechanism for your infrastructure is important.

In this article, we will go through various Principles, Patterns, and Practices that have helped me, and the organizations I have worked with, over the years.

Key Principles

Before we start talking about Patterns and Practices lets look at key principles for effective IaC.

Idempotency

Idempotency means no matter how many times you run your IaC and, what your starting state is, you will end up with the same end state. This simplifies the provisioning of Infrastructure and reduces the chances of inconsistent results.

Idempotency can be achieved by using a stateful tool with a declarative language, like Terraform, where you define the desired end state of infrastructure you want, and then it is Terraform’s job to get you to that end state. If it can’t get to the desired state it will fail.

In diagram #1 below as you can see that for a Non-Idempotent IaC if you run it twice it will provision 6 VMs instead of desired 3. In the case of Idempotent IaC, it only provisions the 3 VMs even if you run it multiple times thereby making it more reliable and consistent.

Image for post

Image for post

Diagram #1: Non-Idempotent vs Idempotent IaC

Immutability

Configuration drift is a huge problem with infrastructure. It occurs when over a period there are changes made to infrastructure that are not recorded, and your various environments drift from each other in ways that are not easily reproducible. This usually happens if you have a mutable infrastructure that lives for a long time. The system is more brittle in general for long-lived infrastructure since issues like a slow memory leak, disk out of space due to log accumulation, etc. might occur over a period. It also means that you won’t be provisioning the infrastructure as frequently as your applications or configuration and as a result won’t be confident in your ability to do so. These issues can be resolved by using immutable infrastructure.

Immutable infrastructure means instead of changing an existing infrastructure you replace it with new. By provisioning new infrastructure every time, you are making sure it is reproducible and doesn’t allow for configuration drift over time.

Immutable infrastructure also enables scalability when provisioning infrastructure on cloud environments. You can see in diagram #2 below that for mutable infrastructure v2 of application is deployed on the same servers as v1 but for immutable infrastructure, it provisions new VMs with v2 of application.

#devops #automation #terraform

What is GEEK

Buddha Community

Principles, Patterns, and Practices
Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Julie  Donnelly

Julie Donnelly

1602394680

S.O.L.I.D. Software Design Principles To Help You Become A Better Developer

S.O.L.I.D design principle comes from Object oriented programming guidelines. It is designed to develop software that can be easily maintained and extended; prevents code smells; easy to refractor; promotes agility and finally incorporates rapid + frequent changes quickly without bugs.

Generally, technical debt is the result of prioritising speedy delivery over perfect code. To keep it under control - use SOLID principles, during development.

Robert Martin, is credited with writing the SOLID principles and stated 4 major software issues if S.O.L.I.D is not followed diligently. They are :

Rigidity:

Implementing even a small change is difficult since it’s likely to translate into a cascade of changes.

Fragility:

Any change tends to break the software in many places, even in areas not conceptually related to the change.

Immobility:

We’re unable to reuse modules from other projects or within the same project because those modules have lots of dependencies.

Viscosity:

Difficult to implement new features the right way.

SOLID is a guideline and not a rule. It is important to understand the crux of it and incorporate it with a crisp judgement. There can be a case when only few principles out of all is required.

#typescript #javascript #solid-in-javascript #what-are-solid-principles #what-is-a-solid-principle #design-patterns #design-principles #object-oriented-design

Seamus  Quitzon

Seamus Quitzon

1601479980

Confused With Java Singleton Design Pattern? Have a Look at This Article.

What Is a Singleton Design Pattern?

  1. Singleton design pattern allows us to create only one instance of a class and make sure that there exists only one Object in JVM.
  2. Singleton class must have a public static method to get the instance of the class from anywhere in the application [from different classes, different packages, etc].
  3. Singleton class must have a private constructor to instantiate the object of the class.
  4. Singleton class must have a private static variable of the same class which is the only reference of the class[basically this variable will point to only Object of class].

Image for post

Singleton Design Pattern

All these different implementation methods lead to one goal that is having a single instance of a class at any given point of time in JVM. Let’s see different implementation approaches for the Singleton design pattern


1. Eager Initialization :

  1. This is the simplest implementation of the singleton design pattern class. In this method, the private static variable of the same class [reference] is assigned the object of class at the time of loading the class into the JVM memory.
  2. This type of implementation is applicable to the scenarios when we always want the instance of the class.

Let’s see the program to understand this …

package com.vikram;

	public class EagerSingleton {
	    //Only object created when class is loaded and theInstance is private static var pointing to it.
	    private static EagerSingleton theInstance = new EagerSingleton();

	    //private constructor
	    private EagerSingleton(){

	    }
	    //public method to return single instance of class .
	    public static EagerSingleton getInstance(){
	        return theInstance;
	    }
	}

Eager Initialization

#desing-pattern #classloading #singleton-pattern #singleton-design-pattern #java-singleton-pattern

Joseph  Murray

Joseph Murray

1623924649

Overview Of Prototype Desing Pattern

What is Prototype Design pattern?

prototypes design pattern allows you to create objects by cloning an existing object instead of creating a new object from scratch. This pattern is used when the process of object creation is costly. when cloning, the newly copied object contains the same characteristics as its source object. After cloning, we can change the values of the new object’s properties as required. This pattern comes under a **creational **pattern.

For easier understanding, Assume that a database operation should be done in order to create an object. This database call is both time-consuming and costly. we need to create multiple objects. As a result, when we create a new object, each time a database call will occur, this will give a performance flop, right? As a result, initially, we create one object and clone it each time when we required a new object. This will cut down the database calls for each object creation.

#java-design-pattern #cloning #prototype-design-pattern #java #prototype-pattern #overview of prototype desing pattern

Why You Should Prefer Singleton Pattern over a Static Class

Introduction

After a long while, I had to create a singleton service while I’m developing a feature for the ABP Framework. Then I decided to write an article about that: Why and how should we use the singleton pattern over a static class?

OK, I agree that creating singleton class or static class, doesn’t matter, is not a good practice. However, in practical, it can be unavoidable in some points. So, which one we should prefer? While the article title already answers this question, I will explain details of this decision in this article.

While this article uses C# as the programming language, the principles can be applied in any object oriented language.

You can get the source code from my GitHub samples repository.

Using Dependency Injection?

Then you are lucky and you are doing a good thing, you can use the singleton lifetime.

ASP.NET Core allows you to register a class with the singleton lifetime. Assuming that you’ve a MyCache class and you want to register it with the singleton lifetime. Write this inside the ConfigureServices method of your Startup class and that’s all:

services.AddSingleton<MyCache>();

You still need to care about multi-threading, you shouldn’t inject transient/scoped services into your singleton service (see my dependency injection best practices guide for more), but you don’t need to manually implement the singleton pattern. ASP.NET Core Dependency Injection system handles it. Whenever you need to the MyCache service, just inject it like any other service.

However, there can be some reasons to manually implement the singleton pattern even if you use the dependency injection:

  • ASP.NET Core Dependency Injection system doesn’t allow to use services until the service registration phase completes. If you need to use your service before or inside the ConfigureServices then you can not get benefit of the dependency injection.
  • You can’t inject a service from a static context where you don’t have access to the IServiceProvider. For example, dependency injection may not be usable in an extension method.

Singleton Pattern vs Static Class

There are two main reasons that you should prefer singleton pattern over a static class. I will introduce briefly, then I will explain them in the next sections by details.

Testability

Singletons are well testable while a static class may not;

  • If your class stores state (data), running multiple tests might effect each other, so writing test will be harder.
  • Static classes are hard or impossible to mock. So, if you are testing a class depends on the static class, mocking may not be an easy option.

Extensibility

  • It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service.
  • It is not possible to write an extension method to a static class while it is possible for a singleton object.

The Solution Overview

I created a solution that implements two caching services, one with the singleton pattern, the other one is a static class. I also created unit tests for both of the services:

Image for post

You can get the source code from my GitHub samples repository. The rest of the article will be based on this solution.

Implementing a Singleton Service

Let’s see a simple caching class that is implemented via the singleton pattern:

public class SingletonCache
{
    public static SingletonCache Instance { get; protected set; } = new SingletonCache();
​
    private readonly IDictionary<string, object> _cacheDictionary;

    protected internal SingletonCache()
    {
        _cacheDictionary = new Dictionary<string, object>();
    }
​
    public virtual void Add(string key, object value)
    {
        lock (_cacheDictionary)
        {
            _cacheDictionary[key] = value;
        }
    }
​
    public virtual object GetOrNull(string key)
    {
        lock (_cacheDictionary)
        {
            if (_cacheDictionary.TryGetValue(key, out object value))
            {
                return value;
            }
​
            return null;
        }
    }
​
    public virtual object GetOrAdd(string key, Func<object> factory)
    {
        lock (_cacheDictionary)
        {
            var value = GetOrNull(key);
            if (value != null)
            {
                return value;
            }
​
            value = factory();
            Add(key, value);
​
            return value;
        }
    }
​
    public virtual void Clear()
    {
        lock (_cacheDictionary)
        {
            _cacheDictionary.Clear();
        }
    }
​
    public virtual bool Remove(string key)
    {
        lock (_cacheDictionary)
        {
            return _cacheDictionary.Remove(key);
        }
    }
​
    public virtual int GetCount()
    {
        lock (_cacheDictionary)
        {
            return _cacheDictionary.Count;
        }
    }
}
  • The static Instance property is the object that should be used by other classes, like SingletonCache.Instance.Add(...) to add a new item to the cache.
  • I marked the setter as protected set to make it settable/replaceable only by a derived class.
  • The _cacheDictionary is not static because the object (Instance) is already static.
  • I declared protected internal for the constructor because;
  • protected makes possible to inherit from this class.
  • internal makes possible to create an instance of this class from the same assembly or an allowed assembly. I allowed to the SingletonVsStatic.SingletonLib.Tests project, so it can create an instance to test it (I used InternalsVisibleTo attribute in the Properties/AssemblyInfo.cs of the SingletonVsStatic.SingletonLib project to make it possible).
  • I make all methods virtual, so a derived class can override.

#aspnetcore #csharp #singleton-pattern #design-patterns #best-practices #programming-c