Answer the question
In order to leave comments, you need to log in
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;
}
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
My opinion - you can not use ternary operators anywhere, as they worsen readability. Second option.
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.
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.
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();
}
There are, of course, religious preferences.
public static function getInstance()
{
return self::$instance ? : self::$instance = new static;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question