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

What is GEEK

Buddha Community

Why You Should Prefer Singleton Pattern over a Static Class
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

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

Yashi Tyagi

1617449307

CA Classes - Best CA Classes Online

Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.

check here : ca classes

#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Abdullah  Kozey

Abdullah Kozey

1620059220

Singleton vs. static classes in C#

When developing applications in .NET Core, you might often need a single, shared instance of a class. Typical use cases would be an instance of LogManager, StateManager, etc. You can either use a singleton class or a static class to achieve this. The decision on which to choose—singleton or static—depends on several factors. This article explains singleton classes and static classes and when we should we use one versus the other.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. You can download .NET 5.0 from here.

#c# #singleton #static classes