D
D
Dmitry Khaperets2014-11-02 18:13:13
PHP
Dmitry Khaperets, 2014-11-02 18:13:13

Which option is better for singleton?

What is the best option for implementing the getInstance method in the Singleton pattern?
one.

public static function getInstance()
{
    return self::$instance ? : self::$instance = new static;
}

2.
public static function getInstance()
{
    if (!static::$instance) {
        static::$instance = new static;
    }

    return static::$instance;
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
ajaxtelamonid, 2014-11-02
@ajaxtelamonid

My opinion - you can not use ternary operators anywhere, as they worsen readability. Second option.

S
Sergey, 2014-11-02
Protko @Fesor

And I see you do not calm down in any way.
From the point of view of the specific implementation, there is no difference, from the point of view of code readability - the second option.
Just read the code:
1) return an instance if it exists otherwise return the result of assigning instance equals instantiating itself
2) if we don't have an instance, then we create it, then we return the instance.
stop chasing symbols for savings, and if we are talking about the underlying code, then it is better to choose a slightly more verbose option, but understandable to everyone from the first time.
And yes, singletons are good, but not very good. And if in your system there is a need for a base class for singletons and each component is built on its basis, you have problems with the architecture.

K
Konstantin Andreevich, 2014-11-02
@reffy

If someone else's opinion is so important, then I like the second option better.
In general, this is such an insignificant issue that I would not waste my life on such things.

N
neolink, 2014-11-02
@neolink

It doesn't matter, the first option is shorter, only I would change it a little:

public static function getInstance()
{
    return static::$instance ?: static::$instance = new static();
}

D
Dmitry Vasilyuk, 2014-11-03
@vasilukwolf

There are, of course, religious preferences.

public static function getInstance()
{
    return self::$instance ? : self::$instance = new static;
}

From a programmer's point of view, such code is more attractive and faster. However, for teamwork, the old version is better. Otherwise, an evil programmer will come to you, who was looking for a bug after you and will take out the brain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question