#Acceptability of 'Singleton Pattern' code

1 messages · Page 1 of 1 (latest)

low mesa
#

I've been browsing a few codebases in the past week and I noticed a 'singleton pattern' (exists in both Java and C# applications) that resembles something like

//field variable
public static Foo instance;

public Foo getInstance() {
    if (instance == null)
        instance = new Foo (fooParam1, fooParam2);
    return instance;
}

Is this acceptable industry code or is it a hacky workaround? It's fairly different from the singleton patterns we used with DI in springboot.
It feels like the type of thing my classmates would criticize for not having thread safety/ability to use lazy loading/decoupling, is it still 'correct' code? I'm not experienced enough to tell

dreamy mothBOT
#

<@&987246883653156906> please have a look, thanks.

dreamy mothBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

ke this:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
public class Singleton {
    private static readonly object lockObject = new object();
    private static Singleton instance;

    private Singleton() {}

    public static Singleton Instance {
        get {
            lock (lockObject) {
                if (instance == null) {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

I've read some articles and discussions about the singleton pattern, and it seems to be a controversial topic. Some argue that it violates the Single Responsibility Principle and can lead to tight coupling and global state issues. Others argue that it can be useful in certain scenarios, such as managing shared resources or ensuring only one instance of a class exists.

In my opinion, the acceptability of using the singleton pattern depends on the specific context and requirements of the application. If there is a genuine need for a single, globally accessible instance of a class, then the singleton pattern can be a valid solution. However, it should be used with caution and careful consideration of its potential drawbacks.

Some alternatives to the singleton pattern include dependency injection, where instances are passed as dependencies rather than being accessed globally, or using a factory pattern to control object creation.

Overall, I would say that while the singleton pattern can be acceptable in certain situations, it should not be used indiscriminately and should be evaluated on a case-by-case basis.

#

A case-by-case basis refers to a decision-making approach where each individual situation is evaluated independently, considering its unique circumstances and factors. It means that decisions are not made based on a general rule or policy, but rather by examining the specific details of each case.

The acceptability of cases on a case-by-case basis depends on the context and the criteria set for evaluation. For example:

  1. Legal cases: Courts may consider each case individually to determine guilt or innocence based on evidence, witness testimonies, and applicable laws.

  2. Employment cases: Employers may assess employee requests for accommodations or promotions on a case-by-case basis, considering factors such as performance, qualifications, and company policies.

  3. Immigration cases: Immigration officers may evaluate visa applications individually, taking into account factors like the applicant's background, purpose of travel, financial stability, and ties to their home country.

  4. Medical cases: Doctors may diagnose and treat patients based on their specific symptoms and medical history rather than applying a one-size-fits-all approach.

In general, any situation that requires thoughtful consideration of unique circumstances can be evaluated on a case-by-case basis. The acceptability of these cases depends on the fairness, consistency, and transparency of the evaluation process.

low mesa
#

funny chatgpt

sinful vortex
#

Ive also heard that the singleton pattern should be avoided as much as possible, but everyone has their own opinions on it

#

But honestly I see no reason why you would want to do this over a private constructor and static methods

dusky vector
sacred pebble
#

Also note that you usually rerally need a singleton, it's more often than note mark of bad design

dusky vector
#

Oh yeah field should be private, missed that one

snow inlet
#

Its kinda a hacky workaround

#

like - most of the time you do not need the lazy initialization

jagged wedge
#

they have some actual use cases tho, if you want to cache a resource and only want to actually compute it when needed

snow inlet
#

these are the ways that you can do an actual singleton

#

if that is what you actually want

#

there are more approaches for multi-tons like "caching instances"

sacred pebble
snow inlet
#

but also, its medium rare you want the actual vm guarrentee that something is a single instance

snow inlet
dusky vector
#

Enum Singleton is really dirty ngl pepekek

snow inlet
#

In the context of using a DI container, using @Singleton on something is generally good enough

#

is it still 'correct' code? I'm not experienced enough to tell
It is not

#

we can show that with some threading shenanigans

#

Example of ways you can work around a singleton if it is serializable

sacred pebble
sacred pebble
#

also note that you can make a thread safe and lazy singleton at the same time easily with a nested class

snow inlet
#

So first, another way to get two instances

sacred pebble
#

yes, that's the only thing that enum can prevent compared to this, but why would you do that ?

#

if it is your code, it makes no sense to do that

#

and if it is a lib, modules are a thing

snow inlet
#

well for my json stuff for example, people might rely on Json.ofNull() only ever returning one instance

#

so I have to put in the legwork to make that always be the case, which is a bit harder than with an enum but still doable

sacred pebble
#

you wouldn't break it yourself with reflection

snow inlet
#
public final class JsonNull implements Json {
    @Serial
    private static final long serialVersionUID = 1L;
    private static final JsonNull INSTANCE = new JsonNull();

    private JsonNull() {}

    /**
     * Returns an instance of {@link JsonNull}. Guaranteed to be comparable with ==,
     * but not to be safe for identity sensitive operations.
     *
     * @return An instance of {@link JsonNull}
     */
    public static JsonNull instance() {
        return INSTANCE;
    }

    @Override
    public java.lang.String toString() {
        return "null";
    }

    @Serial
    private Object writeReplace() {
        return new JsonSerializationProxy(Json.writeString(this));
    }

    @Serial
    private Object readResolve() {
        throw new IllegalStateException();
    }

    @Override
    public void write(JsonGenerator generator) {
        generator.writeNull();
    }
}
sacred pebble
#

users who depends on it behaving like that wouldn't break it with reflection

#

and if your project correctly use modules, then reflection wouldnt be a thing at the first place

snow inlet
#

I'm just trying to point out that if the goal is "guarentee a single instance" thats a bit hard

#

you see i don't even care about the invoking private constructor case, but i do handle serialization

#

and its not even really a thing worth caring about usually

snow inlet
#
  • i'm having fun with my new toy