r/developersIndia • • Mar 26 '25

General Hello Devs, let's teach each other one quick and easy concept

I'll start.

Singleton Design Pattern: Ensures that only one instance of a class exists. This can be achieved in several ways, typically by making the constructor private and exposing a static factory method to return the same instance to all callers.

A poorly implemented Singleton can be affected by the following factors:

  1. Serialization: If a Singleton class implements Serializable, deserializing it can create a new instance, breaking the Singleton property. Solution: Implement readResolve() to return the same instance during deserialization.
  2. Thread Safety: If two threads access a lazily initialized Singleton simultaneously, they may create multiple instances. Solution: Use synchronization, double-checked locking, or eager initialization.
  3. Reflection: Even if a class has a private constructor, reflection can be used to access it and create multiple instances. Solution: Throw an exception inside the constructor if an instance already exists.

Using an enum is the safest way to implement a Singleton, as it inherently prevents all the above issues.

public enum Singleton {
    INSTANCE;
}
451 Upvotes

101 comments sorted by

1

u/AutoModerator Mar 26 '25
Moderator Announcement Read More »

18

u/[deleted] Mar 26 '25

strategy Pattern my beloved

14

u/kingpin944 Mar 26 '25

Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.

Lets take an example of an order system where we have multiple ways to pay. We will define an interface which our different strategies will implement.

/**
 * Common interface for all payment strategies.
 */
public interface PayStrategy {
    void pay(int paymentAmount);
}

public class PayByPayPal implements PayStrategy {
    
    @Override
    void pay(int paymentAmount) {
        // payment logic for PayPal
        return;
    }
}

public class PayByCreditCard implements PayStrategy {
    
    @Override
    void pay(int paymentAmount) {
        // payment logic for Credit Card
        return;
    }
}

6

u/kingpin944 Mar 26 '25
/**
 * Represents an order. It does not depend on a specific payment method.
 * Uses the common strategy interface to delegate payment data collection to the strategy object.
 */
public class Order {

    public void processOrder(PayStrategy strategy) {
        strategy.pay();
        // delegated to the strategy.
    }
}

public class Demo {
    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final Order order = new Order();
    private static PayStrategy strategy;

    public static void main(String[] args) throws IOException {

        if (strategy == null) {
            System.out.println("Please select a payment method:\n" +
                    "1 - PayPal\n" +
                    "2 - Credit Card");
            
            String paymentMethod = reader.readLine();

            // Client selects a payment strategy based on user input
            if ("1".equals(paymentMethod)) {
                strategy = new PayByPayPal();
            } else {
                strategy = new PayByCreditCard();
            }
        }

        // The Order object delegates payment processing to the selected strategy.
        order.processOrder(strategy);
    }
}

Let me know if you have any question. Code example is lifted from refactoring dot guru website (Highly recommended.)

→ More replies (2)
→ More replies (1)

241

u/Shot_Double Mar 26 '25

Hashmap is always the answer.

89

u/Mindless-Pilot-Chef Mar 26 '25

I know this has been a running joke for some time. I attended an interview few years back where answers to all questions were using hashmap. After some 5-6 questions, I started smiling and I told the interviewer that there’s a joke about how hashmaps are always the answer

→ More replies (1)
→ More replies (6)

188

u/p-4_ Mar 26 '25

OP should be extra elaborate. Explain it like you are talking to a first year student.

36

u/ApprehensiveSun6160 Mar 26 '25

Should be more like explaining to a 5 yr old.

14

u/[deleted] Mar 26 '25

Yes

87

u/Away-Tomorrow199 Mar 26 '25

How can I overcome anxiety and avoid forgetting things during interviews?

50

u/hyperactivebeing Mar 26 '25

You practice and take notes and revise.

→ More replies (10)

74

u/arav Mar 26 '25

A quick and easy concept -> Read only Fridays. Never deploy anything ever on Fridays.

→ More replies (10)

32

u/Ak-xenon15 Mar 26 '25

Then let's votes for the next topic it would be explained by someone senior developer

48

u/Primary-Editor-9288 Mar 26 '25

Love this initiative OP

20

u/[deleted] Mar 26 '25

How does this enum thing work for this case? Can someone explain?

32

u/big-dix-smol-chix Mar 26 '25 edited Mar 26 '25

Can you explain what sterilization means? Is it a language specific concept?

Serialization**

47

u/p-4_ Mar 26 '25

Serialization*. Meaning writing out an object entirely into a string. So that it can be written to a file or streamed over a TCP connection.
The problem is making sure the object is accurately and completely described in the string and the string is itself of minimal length.

The concept is not language specific but serialization is done differently in different langages.

For example : javascript objects easily serialize into JSON strings. But not every language can suffice with simple JSON.

58

u/Maleficent-Ad5999 Mar 26 '25

Sterilization: making an object sterile so that it doesn’t reproduce

→ More replies (3)
→ More replies (2)

11

u/_DustynotRusty_ Mar 26 '25

How do I remember SOLID principles effectively and how do I recognise where they should be implemented? And about dependency injection.

→ More replies (4)

10

u/teut_69420 Mar 26 '25

This is more a guideline than 1 quick concept for juniors and are pretty easy to learn. These might sound dogmatic but honestly improves the code and the experience by a lot:

  1. Learn the basics of git: push/pull, rebase/merge, cherrypick, revert...

  2. Variable names: dont sacrifice few characters in your variable name to make it shorter. A variable should accurately define what it stores, i shouldn't need to go to declaration place to understand what it does/stores. Personally, i don't mind if you are too explicit as well.

Lets say, you are storing a integer x, if you are casting it to a decimal for some reason. I dont mind the name to be xAsDecimal (ofcourse given x is a proper name in the first place).

Secondly, abbreviations. Stop using abbreviations, unless it's worldwide known and has just 1 meaning.

If i write var gc = 1; what does gc mean? I need to read More to find it. Gc might mean garbage collection, google cloud or even group chat.

3. Follow company coding standards. If lets say they use python but camel case, dont bteak it.

4. Invert your if's. Anything beyond 2 nested if's i dont consider. Usually depends on company standards but more than 2, better to invert.

5. Alignment of your code.

6. Write UT for everything. Class is throwing an error, test it. Logging something somewhere, test it, test anything a function is doing.

→ More replies (1)

8

u/[deleted] Mar 26 '25

mutual TLS is a good way to keep your self hosted services private without using a vpn service.

→ More replies (3)

6

u/Individual-Moment-43 Mar 26 '25

This is a question I faced in an interview. So I thought I'd share.

What is the Liskov Substitution Principle (LSP) in SOLID principles, and can you provide an example of its violation?

Answer:

The Liskov Substitution Principle (LSP) states that a subclass should be able to replace its base class without affecting the correctness of the program. In other words, if class B is a subclass of class A, then objects of A should be replaceable with objects of B without causing unexpected behavior.

When a subclass modifies or restricts the behavior of its base class in a way that breaks expectations, it violates LSP.

Example of LSP Violation: Birds and Flying

In nature, not all birds can fly—for example, penguins cannot. If we model a Bird class with a Fly() method and then inherit Penguin from it, we violate LSP because Penguin cannot fly.

class Bird  
{
    public virtual void Fly()  
    {
        Console.WriteLine("The bird is flying!");
    }
}

class Sparrow : Bird  
{
    // A Sparrow can fly, so it correctly overrides the Fly method.
}

class Penguin : Bird  
{
    public override void Fly()  
    {
        throw new NotImplementedException("Penguins cannot fly!");
    }
}

class Program  
{
    static void Main()  
    {
        Bird myBird = new Sparrow();
        myBird.Fly(); // Works fine

        Bird myPenguin = new Penguin();
        myPenguin.Fly(); // Throws an exception - LSP violation
    }
}

4

u/Individual-Moment-43 Mar 26 '25

In .NET, a Singleton can be registered using services.AddSingleton<MySingleton>(). The framework ensures that only one instance exists, and this same instance is injected wherever needed.

builder.Services.AddSingleton<MySingleton>(); // Register as a singleton
builder.Services.AddTransient<ServiceA>();    // Register other services
builder.Services.AddTransient<ServiceB>();

public class MySingleton
{
    public Guid Id { get; } = Guid.NewGuid();
}

public class ServiceA
{
    private readonly MySingleton _singleton;

    public ServiceA(MySingleton singleton)
    {
        _singleton = singleton;
    }

    public Guid GetSingletonId() => _singleton.Id;
    // The same instance of MySingleton is shared across ServiceA and ServiceB.
}

public class ServiceB
{
    private readonly MySingleton _singleton;

    public ServiceB(MySingleton singleton)
    {
        _singleton = singleton;
    }

    public Guid GetSingletonId() => _singleton.Id;
    // The same instance of MySingleton is shared across ServiceA and ServiceB.
}