Hot answers tagged

39

No. SOLID exists as guidelines to account for inevitable change. Are you really never going to change your logging library, or target, or filtering, or formatting, or...? Are you really not going to change your caching library, or target, or strategy, or scoping, or...? Of course you are. At the very least, you're going to want to mock these things in a ...


35

If the class has no state, you could consider turning it into a function or static method depending on your language.


33

Yes This is the whole point of the term "cross-cutting concern" - it means something that does not fit neatly in the SOLID principle. This is where idealism meets up with reality. People semi-new to SOLID and cross-cutting often run into this mental challenge. It's OK, don't freak out. Strive to put everything into terms of SOLID, but there are a few ...


32

If one object is enough, creating an object every time is a waste, and here your boss may be right. The problem is proper access to that object. A factory-like method with proper visibility which always returns that static object is the first solution that springs to mind. Others certainly exist.


29

Some problems with enum singletons: Committing to an implementation strategy Typically, "singleton" refers to an implementation strategy, not an API specification. It is very rare for Foo1.getInstance() to publicly declare that it'll always return the same instance. If needed, the implementation of Foo1.getInstance() can evolve, for example, to return one ...


28

I agree that it is an anti-pattern. Why? Because it allows your code to lie about its dependencies, and you can't trust other programmers to not introduce mutable state in your previously immutable singletons. A class might have a constructor that only takes a string, so you think it is instantiated in isolation and does not have side effects. However, ...


27

It has the same problems as a global variable. It gives you global accesses to mutable state. Anything that uses the Singleton is now tightly coupled to it. Try and avoid tight coupling. It makes the code hard to update. Hard to test. If your choice is a Singleton or global variable. Than at least Singleton provides lazy initialization. But ...


24

The Singleton pattern is basically just a lazily initialized global variable. Global variables are generally and rightly considered evil because they allow spooky action at a distance between seemingly unrelated parts of a program. However, IMHO there is nothing wrong with global variables that are set once, from one place, as part of a program's ...


24

For logging I think it is. Logging is pervasive and generally unrelated to the service functionality. It's common and well-understood to use the logging framework singleton patterns. If you don't, you're creating and injecting loggers everywhere and you don't want that. One issue from the above is that someone will say 'but how can I test logging?'. My ...


23

The two main criticisms of Singletons fall into two camps from what I've observed: Singletons are misused and abused by less capable programmers and so everything becomes a singleton and you see code littered with Class::get_instance() references. Generally speaking there are only one or two resources (like a database connection for example) that qualify ...


23

It is sometimes considered that the singleton is an anti-pattern. Unless the problem being solved specifically requires the use of the singleton pattern, it is generally best to avoid it. You mention that the function would have no state or other long lived requirements, so the immediate need for an object is not there either. A free function would be best ...


19

Why are Singleton and static method your only options? From my point of view, both options are pretty bad. Read up on the Singleton AntiPattern. Most use cases of the Singleton Pattern is incorrect. In your case, I would use an instance object and use dependency injection (if you're using a DI framework) or a Service locator/Registry pattern


19

What you want sounds like a good case for the Factory pattern. You would write something like: class LoaderFactory { public Loader getLoader() { if (environment1) return ZipLoader.getInstance(); else if (environment2) return DiskLoader.getInstance(); else return SomeOtherLoader.getInstance(); } } Each type of Loader class is a singleton, ...


16

1. Singleton You restrict the number of instances because the constructor will be private meaning only static methods can create instances of that class (there are other dirty tricks actually to accomplish that but let's not get carried away). Creating a class that will have only 2 or 3 instances is perfectly feasible. You should be using singleton ...


15

The purpose of a singleton is to enforce that only one instance can ever exists within a certain realm. This means that a singleton is useful if you have strong reasons to enforce singleton behavior; in practice, this is seldom the case though, and multi-processing and multi-threading certainly blur the meaning of 'unique' - is it one instance per machine, ...


13

The only time a singleton is useful, over a simple global variable, is when you require global access and it's an error to have more than one instance. Some people use singletons to represent log files, but it's not an error to have more than one instance of your log class (for example, you might want to log to a separate file for some particular purpose: if ...


13

I think he meant that you should use dependency injection to inject a single instance of the service, instead of using the classical Singleton implementation with a static accessor MySingleton.Instance. public class MySingleton { public static MySingleton Instance{get{...}}; } With the classical singleton implementation all your code depends on that ...


12

With a singleton class, you have more control in terms of how you manage the object that is created. First, a singleton is an object. The static method returns an instance of the object and allows you to create only a single instance, or more if you so choose. Singletons are also lazy-loaded, meaning that they are not instantiated until the first time ...


12

There is no difference in the dangers by changing your static methods into instance methods on a singleton. They are effectively the same. Sometimes you simply have functions. A function in mathematical terms, contains no state. It is simply the calculations to apply to an input to determine your output. For example, Math.Sqrt does not contain any ...


11

I suggest you look into using a dependency injection framework to achieve inversion of control. Your "Manager" would not be a traditional Singleton, but you would only create one through the framework configuration. The "Manager" would also not be global, but every component that would need to use it would have it assigned.


10

Why would you separate your factory from the object-type it creates? public class Foo { // Private constructor private Foo(...) {...} public static Foo of(...) { return new Foo(...); } } This is what Joshua Bloch describes as his Item 1 on page 5 of his book, "Effective Java." Java is verbose enough without adding extra classes and ...


10

My 2 cents ... Yes and no. You should never really violate the principles you adopt; but, your principles should always be nuanced and adopted in service to a higher goal. So, with a properly conditioned understanding, some apparent violations may not be actual violations of the "spirit" or "body of principles as a whole." The SOLID principles in ...


9

It always depends on the usage. I think the revolution comes from the fact, that every programmer learns this pattern as the object oriented pattern. Most forget to think about where it makes sense and where it doesn't. This, of course, is true for every pattern. Just by using patterns you don't create good code or good software. If you have a stateless ...


8

As byte points out, singletons are often overused. However, they are often over-used because they are used where a static instance would be better. From your question you seem to be implying they are the same thing or are interchangeable. They are not the same, and although they can be interchangable in some cases there is usually agood reason to prefer one ...


8

I can't comment your specific case, but using global variables is sometimes a good solution. Java's System class is full of static, global variables. But in general, if you think you're right and your boss is wrong, then why don't you ask your boss to explain why he thinks a global variable is a better solution? A plain "I don't like it" is as vague as ...


8

It is not a Singleton. My is just a namespace containing static classes, methods and properties that point to other parts of the .NET framework, and provide some additional capabilities (e.g. CopyDirectory) Think of it as a set of shortcuts, a speed-dial of sorts. Visual Basic provides language/compiler support with the My keyword. You can use the My ...


8

Most people already explained what singletons/abstract classes are. Hopefully, I'll provide a little different perspective and give some practical examples. Singletons - When you want all calling code to use a single instance of variables, for whatever reasons, you have the following options: Global variables - obviously no encapsulation, most of the code ...


8

It's a Singleton combined with a Factory Method, such that the calling code has no idea that it is dealing with a singleton, or even the class it's dealing with. Even the class itself doesn't know it's a Singleton. The factory can be mocked out, making testing possible but, within the context of the application, it is always the same object returned. I have ...


8

The idea that logging should always be implemented as a singleton is one of those lies that has been told so often it has gained traction. For as long as modern operating systems have been about it has been recognised that you may wish to log to multiple places depending on the nature of the output. System designers should constantly be questioning the ...


7

Your code will be more flexible if you use a singleton. The advantage is that the code that uses the singleton doesn't need to know if it is a singleton or a transient object. Using a static class means you have to call static methods explicitly. Think about dependency injection, for example. Moreover, singleton, as a non-static class, can still implement ...



Only top voted, non community-wiki answers of a minimum length are eligible