What does "Client" mean when referencing SOLID principles? - solid-principles

I'm currently reading Adaptive Code: Agile coding with design patterns and SOLID principles and in each principle they reference "the client". Who is "the client"?
Even in Wikipedia:
https://en.wikipedia.org/wiki/Interface_segregation_principle
In the field of software engineering, the interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.
Thanks!

Client here simply refers to the user of the code construct in question. So let's say you write a Queue class backed by an array:
class Queue:
void enqueue(item)
item dequeue()
void resize() // doubles the size of the array if it's full
The user could be yourself, if you import your own Queue class somewhere else, or it could be other developers, if they are using your queue class. Then in this case, your clients do not depend on resize (the queue class calls it internally, so it's not for users to call), the interface should only expose what's needed for the queue functionality
interface QueueI:
void enqueue(item)
item dequeue()

Related

ASP.NET 5 Best practice to log exceptions in layers

I have a project using ASP.NET 5 and MVC 6. I have several layers :
My presentation layer
My domain model layer
My infrastructure layer
My business logic layer
And my data access layers.
For the moment, I log exceptions in my controllers methods using Dependency Injection.
private readonly ILogger<CustomerController> _logger;
public CustomerController(ILogger<CustomerController> logger)
{
_logger = logger;
}
public bool TestLog()
{
_logger.LogError((int)LoggingEvents.LIST_ITEMS, "Test info #543434");
return true;
}
What is the best practice to use the logger in my others layers, like my data access layer ?
Best is to use ILogger<T> only in your application layer (Controllers, application services - but not domain services).
If you want to add logging around your domain services/repositories, it'd be best to create decorators for it. This only works well if you have abstracted your interfaces from their implementations and use/inject interfaces everywhere).
However, there are limitations on what you can do with decorators. You can log before and after the call to a method defined in the public interface. Not inside the call.
Why avoid logging/injecting your logger into the service?
Coupling
You should avoid injecting ILogger<T> in your domain objects, as this couples your domain to ASP.NET Core logging framework/base classes. However, you can always define your own logger interface to use it within your domain and implement it as wrapper around ILogger<T>.
SOLID Principle
S in SOLID principle stand for SRP (Single Responsibility Principle) and says, one object should just have one and only one responsibility. Doing logging and persistence or businesses logic into one object violates this principle.
But in the end, you got to weight up costs of development with the benefits you gain with it. If it's a long living application (to be used for the next 10 years or so) and a complex one, logging as decorators makes sense for sure. If it's a small project with only a few weeks of development time, the benefit of this abstraction may not outweigh the costs.
The “best practice” would be to just inject own loggers for every component and let every component do its own logging.
If you think this becomes too noisy for your application, then you can change the verbosity level for namespace parts, so you only get e.g. Information level logs for your controllers, and Warning (or worse) for everything else:
loggerFactory.AddConsole(new ConsoleLoggerSettings()
{
Switches = new Dictionary<string, LogLevel>()
{
["MyNamespace.Services"] = LogLevel.Warning,
["MyNamsepace.Controllers"] = LogLevel.Information
}
});
If you want to log unhandled exceptions, you should probably add a middleware that can take care of that. You can see an example in this SO answer: https://stackoverflow.com/a/31054664/5795

How exactly do "Objects communicate with each other by passing messages"?

In several introductory texts on Object-oriented programming, I've come across the above statement.
From wikipedia, "In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects and can be viewed as an independent 'machine' with a distinct role or responsibility."
What exactly does the statement mean in code?
class A
{
methodA()
{
}
}
class B
{
methodB()
{
}
}
class C
{
main()
{
A a=new A();
B b=new B();
a.methodA(); // does this mean msgs passing??
b.methodB(); // or does this?? I may be completely off-track here..
}
}
If we are talking about OOP than the term "message passing" comes from Smalltalk. In a few words the Smalltalk basic principles are:
Object is the basic unit of object-oriented system.
Objects have their own state.
Objects communicate by sending and receiving messages.
If you are interested in Smalltalk take a look at Pharo or Squeak.
Java/C#/C++ and many other languages use slightly different approach probably derived from Simula. You invoke a method instead of pass a message.
I think this terms are more or less equivalent. May be the only interesting difference is that message passing (at least in Smalltalk) always rely on dynamic dispatch and late binding while in the case of method invocation one can use static dispatch and early binding too. For example, C++ (AFAIK) does early binding by default until "virtual" keyword appears somewhere...
Anyway, regardless of which formalism do your programming language use for communication between two objects (message passing or method invocation) it's always considered a good OOP style to forbid direct access to instance variables in Smalltalk terminology or data members in C++ terminology or whatever term is used in your programming language.
Smalltalk directly prohibits access to instance variables at the syntax level. As I mentioned above objects in Smalltalk program can interact only by passing/receiving messages. Many other languages allow access to instance variables at the syntax level but it's considered a bad practice. For example, the famous Effective C++ book contains the corresponding recommendation: Item 22: Declare data members private.
The reasons are:
syntactic consistency (the only way for clients to access an object is via member functions or message passing);
more precise control over the accessibility of data members (you can implement no access, read-only access, read-write access, and even write-only access);
you can later replace the data member without breaking your public interface.
The last one is the most important. It's the essence of encapsulation - information hiding on the class level.
The point about encapsulation is more important than it might initially appear. If you hide your data members from your clients (i.e., encapsulate them), you can ensure that class invariants are always maintained, because only member functions can affect them. Furthermore, you reserve the right to change your implementation decisions later. If you don't hide such decisions, you'll soon find that even if you own the source code to a class, your ability to change anything public is extremely restricted, because too much client code will be broken. Public means unencapsulated, and practically speaking, unencapsulated means unchangeable, especially for classes that are widely used. Yet widely used classes are most in need of encapsulation, because they are the ones that can most benefit from the ability to replace one implementation with a better one.
(с) Scott Meyers, Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)
Not exactly an answer to your question, but a little digression about message dispatch vs. method invocation:
The term message refers to the fact that you don't know which method will be invoked due to polymorphism. You ask an object to do something (hence the term message) and it acts accordingly. The term method invocation is misleading as it suggest you pick one exact method.
The term message is also closer to the reality of dynamic language, where you could actually send a message that the object doesn't understand (see doesNotUnderstand in Smalltalk). You can then not really speak of method invocation given that there is none matching, and the message dispatch will fail. In static typed language, this problem is prevented.
"Passing a message" is an abstraction.
Most OO languages today implement that abstraction in the form of feature invocation. By feature I mean a method an operation (see edit below), property or something similar. Bertrand Meyer in OOSC2 argues that feature invocation is the basic unit of computation in modern OO languages; this is a perfectly valid and coherent way to implement the old abstract idea that "objects communicate by message passing".
Other implementation techniques are possible. For example, objects managed by some middleware systems communicate by passing messages via a queue facility.
In summary: don't confuse abstractions with code. In the olden days, programmers used to care a lot about theory because programming barely existed as a mainstream profession. Today, most programmers are rarely familiar with the theory behind the code. :-)
By the way, and for the theory inclined, agent-oriented modelling and programming approaches often emphasise message passing as a communication mechanism between agents, arguing that it derives from speech act theory. No method invocation is involved here.
Edit. In most OO languages, you call operations rather than methods. It is the runtime engine which decides which particular method to invoke as a response to the operation that you have called. This enables the implementation of the so often mentioned mechanisms of polymorphism. This little nuance is usually forgotten in routine parlance when we refer to "calling a method". However, it is necessary in order to differentiate between operations (as features that implement message passing) and methods (as specific versions of said operations).
They're referring to the fact that a client can invoke a method on a receiving object, and pass data to that object, but that object can decide autonomously what to do with that data, and maintain its own state as required.
The client object can't manipulate the state of the receiving object directly. This is an advantage of encapsulation - the receiving object can enforce its own state independently and change its implementation without affecting how clients interact with it.
In OOP, objects don't necessarily communicate with each other by passing messages. They communicate with each other in some way that allows them to specify what they want done, but leaves the implementation of that behavior to the receiving object. Passing a message is one way of achieving that separation of the interface from the implementation. Another way is to call a (virtual) method in the receiving object.
As to which of your member function calls would really fit those requirements, it's a bit difficult to say on a language-agnostic basis. Just for example, in Java member functions are virtual by default, so your calls to a.methodA() and b.methodB() would be equivalent to passing a message. Your (attempts a) calls to b.methodA() and a.methodB() wouldn't compile because Java is statically typed.
On the contrary, in C++, member functions are not virtual by default, so none of your calls is equivalent to message passing. To get something equivalent, you'd need to explicitly declare at least one of the member functions as virtual:
class A {
virtual void methodA() {}
};
As it stands, however, this is basically a "distinction without a difference." To get some idea of what this means, you need to use some inheritance:
struct base {
void methodA() { std::cout << "base::methodA\n"; }
virtual void methodB() { std::cout << "base::methodB\n"; }
};
struct derived {
void methodA() { std::cout << "derived::methodA\n"; }
virtual void methodB() { std::cout << "derived::methodB"; }
};
int main() {
base1 *b1 = new base;
base2 *b2 = new derived;
b1->methodA(); // "base::methodA"
b1->methodB(); // "base::methodB"
b2->methodA(); // "base::methodA"
b2->methodB(); // "derived::methodB"
return 0;
}
What you have posted will not compile in any oop language, as methodB does not belong to object A and methodA doesn't belong to object B.
If you called the correct method, then both of these are message passing by object C:
a.methodA();
b.methodB();
From wikipedia:
The process by which an object sends data to another object or asks the other object to invoke a method.
Your example won't work with Java or Python, so I have corrected and annotated your main
class C{
main()
{
A a=new A();
B b=new B();
a.methodA(); // C says to a that methodA should be executed
// C says to b that methodB should be executed
// and b says to C that the result is answer
answer = b.methodB();
}
}
Some of the early academic work on OO was in terms of objects passing messages to each other in order to invoke behavior. Some early OO languages were actually written that way (SmallTalk?).
Modern languages like C++, C# and Java do not work that way at all. They simply have code call methods on objects. This is exactly like a procedural language, except that a hidden reference to the class being called is passed in the call ("this").
passing object as parameter to a method of an object that belong to a different class type.
this way you pass attribute of an object to another object of a different class
just call an methods of a object of an other class.
so you can create an object of this class to get information of other object of different class.
Note:
this no override methods ok because they can be the same name but belong to a different class type.
override methods is went you heritage a methods in a sub class and you change the behavior of the same methods that you get for heritance of a super class.
the method to call is depending of arguments that you put in the method or the data type. the system call the right method and they can be located in a object of a superclass or in a object of a subclass.
a lot of people ask the same question. when they are working with OOP.
I recommend read those old books.
to understand what is OOP and not learn to programming object oriented in a programming language as CPP, JAVA and PHP.
introduction to OOP (Timothy Buud)
Object-Oriented Programming: An Evolutionary Approach
(Brad J Cox . Andrew J Novobilski)
and not forget to read Bjarne stroustrup CPP new books.
#include <iostream>
#include <string>
using namespace std;
class Car{
string brand;
public:
void setBrand(string newBrand){this->brand=newBrand;}
void Driver(){cout<<" IS DRIVING THIS CAR BRAND "<<brand<<endl;}
void Brake(){cout<<"IS BRAKING"<<endl;}
};
class Person{
private:string name;
public:
void setName(string newName){this->name=newName;}
//HERE WE CALL METHOD OF CAR CLASS AND REDEFINE METHODS NO OVERRIDE OK
void Driver(Car objectOfClassCar){cout<<this->name<<ends;
objectOfClassCar.Driver();}
void Brake(string str, Car objectOfClassCar){cout<<this->name<<"
"<<str<<ends;objectOfClassCar.Brake();}
};
int main(){
Car corolla;
corolla.setBrand("TOYOTA");
Person student;
student.setName("MIGUEL");
student.Driver(corolla);
student.Brake("CAR",corolla);
//it open a lot of opportunities to do the same.
}
Does that code works?
Anyway you're out of the road...
Message passing is a way for interprocess communication, one among many others. It means that two (or more) object can only speak one each other by messaging, which should say from who, to who, and what...
You can see it's very different from shared memory, for example...

What is your best example of a violation of the Single Responsibility Principle?

I'm looking for some good examples of code that violates the Single Responsibility Principle. Don't show me any examples from Uncle Bob's books or web sites since those are plastered all over the internet, like this one:
interface Modem
{
public void dial(String pno);
public void hangup();
public void send(char c);
public char recv();
}
The granularity of your OO design is a matter of taste and might be inapropriate for others. Thus, I wouldn't look for examples of breaking the single responsibility principle in some business-logic-class, discussing whether it has too much or too little to do.
In my opinion, the best examples (with worst side-effects) come from breaking the layering of your application. F.ex.:
Performing business logic in the data access layer (whose only responsibility should be providing persistence access to the application)
Accessing business services from (through) the domain model (whose only responsibility should be to store most of the application's state)
Performing complex business logic in the view layer (responsible for data presentation & user input)
Here's some code from a PHP project I had to take on:
class Session
{
function startSession()
{
// send HTTP session cookies
}
function activateUserAccount()
{
// query the DB and toggle some flag in a column
}
function generateRandomId()
{}
function editAccount()
{
// issue some SQL UPDATE query to update an user account
}
function login()
{
// perform authentication logic
}
function checkAccessRights()
{
// read cookies, perform authorization
}
}
I believe this class does waaay to much.
The clue about SRP is to define the responsibilities so that your implementation does just that thing. It's like you're making a rule (by giving a class a name and a responsibility) and then trying to follow it.
So if you're not following it you're either not defining the rule properly or you're being inconsistent while implementing it (or both, which might actually be the most common case).
I generally find the classes that do not give a half-decent try at defining a single main responsibility or good name to be the best violations. Then you'll just have to read the whole class to try to determine if there's any well defined responsibilities at all.
Actually, in most OO languages that I have used, the top-level Object class is a good example. In Ruby, for example, the Object class (or more precisely the Kernel mixin, which gets mixed into Object) has 45 public instance methods. Now, some of those are aliases, but there's still got to be at least 20, and they are from all over the place. I can easily identify at least 5 responsibilities.
Now, I don't mean to pick on Ruby. It is my favorite programming language. That's why I used it as an example: because it's the language I'm most familiar with. And I am reasonably sure that what I wrote about Ruby applies 100% also to at least Java and .NET.
It's a qualitative question to ascertain the 'responsibilities' of a class.
Just looking at a given class code, can in no measure give us an idea of how well it handles it's repsonsibility.
It is very necessary, atleast as per my experience, to take into account how the requirement changes to the class will propagate to other modules ( or how will the changes from other classes get propagated to this class).
As #schmeedy gives a nice explanation of 'breaking the layering of the system' , which I think is just one of the ways to analyse 'responsibility domain'.
I have attempted to take the discussion little further. My attempts are to define 'responsibility' in a quantitative way.
Some discussions at my blog: http://design-principle-pattern.blogspot.in/2013/12/single-responsibility-principle.html
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#interface Spreadsheet : NSObject
- (void)loadFromURL:(NSURL *)url;
- (void)saveToURL:(NSURL *)url;
- (void)drawTo:(CGRect*)targetArea withContext:(CGContextRef *)context;
#end
I would argue that the above example violates the SRP.
On the face of it, it is clear that the class is responsible for one thing: Spreadsheets. It is distinguished from other entities in the Document Management problem domain such as Word Processing.
However, consider the reasons why the Spreadsheet object could change.
There may be a change to the model underlying the Spreadsheet. This affects load and save code but would not affect how the Spreadsheet is drawn. So the load/save responsibilities are separate from the drawing responsibilities. Our class has two responsibilities.
So if we think about all the reasonably foreseeable reasons to change a class, and see that only particular methods on the class would be affected, we see an opportunity to factor out a responsibility to get a more focussed class.
A revised class would be:
#interface SpreadsheetEncoder
- (NSData *)encodedSpreadsheet:(Spreadsheet *)spreadsheet;
- (Spreadsheet *)spreadsheetFromEncodedData:(NSData *)data;
#end
#interface Spreadsheet2 : NSObject
- (NSData *)data;
- (instancetype)initSpreadsheetFromData:(NSData *)data;
- (void)drawTo:(CGRect*)targetArea withContext:(CGContextRef *)context;
#end
As product development advances, we can ask ourselves again 'what could change' and then refactor the classes to keep them responsible for only one concern. SRP is only relative to the problem domain and our understanding of it at a given time.
SRP in my view boils down to asking 'what can change?' and 'what would be affected'. When 'what can change' maps onto only one thing that is affected, you have classes that implement the SRP principle.

When to use template method Vs. Strategy?

The template method pattern and the strategy pattern do roughly the same thing. I understand the basic differences between them (template method is inheritance based, strategy is composition based), but are there any decent guidelines on when to choose one over the other? It seems like they do basically the same thing.
Strategy allows for a reusable algorithm to be used in more than one place. If you have an algorithm that can be provided by your consumer and can be used in several places, this is a good spot for Strategy (sorting algorithms, predicates, comparers... are good examples of that).
Template method is specifically targeted at cases where you want people to be able to inherit from your class and want them to be able to override your implementation in a controlled manner (basically preventing them from replacing all your plumbing and offering them a specific extension point without risking a problem because they did not call the base method or called it at the wrong time).
They can be similar, and they can serve the same kind of purpose depending on what you are actually doing.
As with all design patterns, it is difficult to answer such a question because there is not really a definitive answer. It's actually easier to decide in context...
The two can actually be used together quite effectively.
Here's a video that details how
Don't think of patterns as recipes with specific code to implement them.
It's the design intent that is the key, and there can be many implementations. By mentioning a pattern name in your code somewhere, you're letting a reader in on your intent when you wrote that code. The implementation is secondary.
Template method gives you an "algorithm with replaceable steps". (The algorithm is normally defined in a non-overridable method (final or private for example) )
The GoF implementation of this concept uses inheritance and method overriding to replace those steps.
However, you're still using Template method if those steps are replaced by strategies.
For example, think about a class that wants to walk a binary tree inorder and "do something" at each node.
The intent is that the inorder() method is a template method - the structure of the walk is always the same.
The "hook" method, the part that "does something" can be implemented as a method in the same class (and overridden in subclasses to change behavior), or externally, in which case it's a strategy for "doing something".
I use Template method when the algorithm needs knowledge of the internals of the objects it runs on.
In all other cases (i.e. when the algorithm only needs to use the object's interface), I try to use Strategy.
Further, Strategy is only useful when there are actual algorithms to implement: If the only difference between classes is (for example) what simple value to return, use Template method.
Consider usage strategy when:
Your object behaviour needs to be changed in runtime.
You already have class hierarchy by other criteria.
You want to share strategy logic across different classes.
In other cases it should be enought to use template pattern.
I disagree with this statement (from this answer):
"Template method is specifically targeted at cases where you want
people to be able to inherit from your class and want them to be able
to override your implementation in a controlled manner."
If you WANT people to inherit from your class then you're WANTING a specific implementation, rather than wanting a particular behaviour. That smells bad to me.
A valid thing to WANT is the ability to override or provide implementations of individual steps of an algorithm. That goal can be achieved by both Template Methods (where we can selectively override protected methods) or the Strategy Pattern (where we inject implementations).
If you are building a class that implements an algorithm, and you want to allow steps in that algorithm to be altered by other developers, that's your requirement. Your only decision is whether to allow them to do that via inheritance or composition.
All other things being equal we should favour composition over inheritance, but we should only even get to the inheritance/composition decision by first figuring out what our goal is (we may need neither).
I would never start with "I want to allow them to inherit from this class". That's cart before the horse IMO.
You can create big inheritance tree just to change one of the N behavior. And you can create second big inheritance tree to change second of the N behavior.
But also you can unload your tree by creating small strategy trees.
So if you noticed that you add more and more classes just to add some changes in some behavior - it is time to supply your classes with strategies.
I would like to agree and second Scott's explanation.
Template pattern = cares about drawing the generic lines along which an operation will be carried on - templating - basically an "algorithm with replaceable steps" (very well coined) where the replaceable steps can be delegated using the Strategy pattern concept.
Strategy pattern = cares only about decoupling the client from the underlining implementation of an operation whose outcome needs to always abide by some predetermined rules (like sorting where the outcome is always a sorted list but you may deffer de actual sorting to bubble sort or to quick sort).
Cheers.
One of the central OO Design principles is "Favour Composition over Inheritance", so that suggests to favour the Strategy pattern. It obviously depends on what you are trying to accomplish in a particular scenario.
My summary: The Strategy Pattern is more loosely coupled than the Template Method pattern, which is generally a good thing.
Robert C. Martin in TEMPLATE METHOD & STRATEGY: Inheritance vs. Delegation
Thus, the STRATEGY pattern provides one extra benefit over the
TEMPLATE METHOD pattern. Whereas the TEMPLATE METHOD pattern allows a
generic algorithm to manipulate many possible detailed
implementations, by fully conforming to the DIP the STRATEGY pattern
additionally allows each detailed implementation to be manipulated by
many different generic algorithms.
DIP is the Dependency Inversion Principle:
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.
I would almost always go for strategy for the very important reason that client code has no dependency on implementation whereas in template pattern part of implementation stays in the abstract class and any change in abstract class may need to change the client which very often result in rigid code and we end up developer telling that "this came out to be a bigger change than I expected".
But in cases when it is really helpful to get common code in an abstract class I would not hesitate to do it and also try to keep code related to client code away from it
I think the answer from #Lennaert is correct. I would like to add some details to it:
The Template pattern differs from the Strategy pattern in a sense that the Template Method uses inheritance and the Strategy pattern uses composition to achieve a common goal. The Strategy pattern is preferred in case the strategies/algorithms are ‘self-contained’ (e.g. more then just a difference in a ‘simple’ return) and must be shared amongst possible other clients/Contexts. The Template pattern is preferred in case the algorithms diverge in their fine details (e.g. just a difference in a ‘simple’ return) and/or access of the internal details of the concrete implementation is required by the base class.
This means:
from client reusability point of view, the Strategy pattern is
preferred over the Template method. Each Strategy can be reused
within a different Context (=client). A new Context solely depends
on the interface of the Strategy and not on the 'extensive'
interface of the full Context. (A compliment to the Interface
Segregation principle). In contrast, within the Template method the
base and concrete implementation are ‘glued’ together. This means
clients, whom would like to re-use the concrete template-method
implementation, are ‘automatically’ bounded to the base class
implementation as well. Even if they don’t want that! This could
violate Interface Segregation. Adhering to Interface Segregation
enables in this case: less recompilation, more confident of changing
an interface (less search hits) and the client is constraint
(‘role’ interface).
the Template pattern might be preferred in case the base algorithm
(=Context or Base Template) requires access to the internals of the
concrete algorithm (=Strategies or Concrete Template). In the
Template Method pattern, the base class can get access to the
concrete implementation via “the Hollywood principle”. This can be
done via a relative encapsulated approach, by making the members
protected. In contrast, the Strategy pattern does not provide this
encapsulated approach (in this particular use-case). Each Strategy
would need to expose its internals on its interface, making it
available to all clients. This might violate encapsulation,
resulting in possible unwanted coupling that is provoked by the
design.
I would prefer using a mix of both, dumping default implementation (from Template pattern) into Context class of strategy pattern. This way, I can enforce user to call method I want them to call so that the order of execution on algorithm's steps remains controlled.
/**
* enables replaceable steps in algorithm
*/
public interface HouseStrategy{
void buildWalls();
void buildPillars();
}
public class HouseContext{
//public API that enforces order of execution
public void build(HouseStrategy strategy){
buildFoundation();//default implementation
strategy.buildPillars();//delegated to concrete strategy
strategy.buildWalls();//delegated to concrete strategy
buildWindows();//default implementation
}
//default implementation
private void buildWindows() {
System.out.println("Building Glass Windows");
}
//default implementation
private void buildFoundation() {
System.out.println("Building foundation with cement,iron rods and sand");
}
}
public class WoodenHouse implements HouseStrategy {
#Override
public void buildWalls() {
System.out.println("Building Wooden Walls");
}
#Override
public void buildPillars() {
System.out.println("Building Pillars with Wood coating");
}
}
public class GlassHouse implements HouseStrategy {
#Override
public void buildWalls() {
System.out.println("Building Wooden Of glass");
}
#Override
public void buildPillars() {
System.out.println("Building Pillars with glass coating");
}
}
As we can see, concrete strategies are still open to extension. As in,
public class GlassHouse implements HouseStrategy,EarthquakeResistantHouseStrategy{......}
The usage
HouseContext context = new HouseContext();
WoodenHouse woodenHouseStrategy = new WoodenHouse();
context.build(woodenHouseStrategy);
GlassHouse glassHouseStrategy = new GlassHouse();
context.build(glassHouseStrategy);
One disadvantage I see here is that concrete strategies can only change the variant behavior of algorithm i.e. buildWalls() and buildPillars(). If we need to change invariant parts i.e. buildFoundation() and buildWindows(), we need to make another Context class implementing the new behavior.
Still, we get some code reusability which is not found in pure Strategy Pattern :-)

How should I refactor my code to remove unnecessary singletons?

I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.
Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.
So: How do I go about removing singletons from existing code?
For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:
Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.
Should I instead:
Create one instance of each object and pass references to every object that needs access to them?
Use globals?
Something else?
Globals would still be bad, but at least they wouldn't be pretending.
I see #1 quickly leading to horribly inflated constructor calls:
someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?
Dependency Injection is your friend.
Take a look at these posts on the excellent Google Testing Blog:
Singletons are pathologic liars (but you probably already understand this if you are asking this question)
A talk on Dependency Injection
Guide to Writing Testable Code
Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.
It's not the Singleton-ness that is the problem. It's fine to have an object that there will only ever be one instance of. The problem is the global access. Your classes that use Store should receive a Store instance in the constructor (or have a Store property / data member that can be set) and they can all receive the same instance. Store can even keep logic within it to ensure that only one instance is ever created.
My way to avoid singletons derives from the idea that "application global" doesn't mean "VM global" (i.e. static). Therefore I introduce a ApplicationContext class which holds much former static singleton information that should be application global, like the configuration store. This context is passed into all structures. If you use any IOC container or service manager, you can use this to get access to the context.
There's nothing wrong with using a global or a singleton in your program. Don't let anyone get dogmatic on you about that kind of crap. Rules and patterns are nice rules of thumb. But in the end it's your project and you should make your own judgments about how to handle situations involving global data.
Unrestrained use of globals is bad news. But as long as you are diligent, they aren't going to kill your project. Some objects in a system deserve to be singleton. The standard input and outputs. Your log system. In a game, your graphics, sound, and input subsystems, as well as the database of game entities. In a GUI, your window and major panel components. Your configuration data, your plugin manager, your web server data. All these things are more or less inherently global to your application. I think your Store class would pass for it as well.
It's clear what the cost of using globals is. Any part of your application could be modifying it. Tracking down bugs is hard when every line of code is a suspect in the investigation.
But what about the cost of NOT using globals? Like everything else in programming, it's a trade off. If you avoid using globals, you end up having to pass those stateful objects as function parameters. Alternatively, you can pass them to a constructor and save them as a member variable. When you have multiple such objects, the situation worsens. You are now threading your state. In some cases, this isn't a problem. If you know only two or three functions need to handle that stateful Store object, it's the better solution.
But in practice, that's not always the case. If every part of your app touches your Store, you will be threading it to a dozen functions. On top of that, some of those functions may have complicated business logic. When you break that business logic up with helper functions, you have to -- thread your state some more! Say for instance you realize that a deeply nested function needs some configuration data from the Store object. Suddenly, you have to edit 3 or 4 function declarations to include that store parameter. Then you have to go back and add the store as an actual parameter to everywhere one of those functions is called. It may be that the only use a function has for a Store is to pass it to some subfunction that needs it.
Patterns are just rules of thumb. Do you always use your turn signals before making a lane change in your car? If you're the average person, you'll usually follow the rule, but if you are driving at 4am on an empty high way, who gives a crap, right? Sometimes it'll bite you in the butt, but that's a managed risk.
Regarding your inflated constructor call problem, you could introduce parameter classes or factory methods to leverage this problem for you.
A parameter class moves some of the parameter data to it's own class, e.g. like this:
var parameterClass1 = new MenuParameter(menuBar, editor);
var parameterClass2 = new StuffParameters(sasquatch, ...);
var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
It sort of just moves the problem elsewhere though. You might want to housekeep your constructor instead. Only keep parameters that are important when constructing/initiating the class in question and do the rest with getter/setter methods (or properties if you're doing .NET).
A factory method is a method that creates all instances you need of a class and have the benefit of encapsulating creation of the said objects. They are also quite easy to refactor towards from Singleton, because they're similar to getInstance methods that you see in Singleton patterns. Say we have the following non-threadsafe simple singleton example:
// The Rather Unfortunate Singleton Class
public class SingletonStore {
private static SingletonStore _singleton
= new MyUnfortunateSingleton();
private SingletonStore() {
// Do some privatised constructing in here...
}
public static SingletonStore getInstance() {
return _singleton;
}
// Some methods and stuff to be down here
}
// Usage:
// var singleInstanceOfStore = SingletonStore.getInstance();
It is easy to refactor this towards a factory method. The solution is to remove the static reference:
public class StoreWithFactory {
public StoreWithFactory() {
// If the constructor is private or public doesn't matter
// unless you do TDD, in which you need to have a public
// constructor to create the object so you can test it.
}
// The method returning an instance of Singleton is now a
// factory method.
public static StoreWithFactory getInstance() {
return new StoreWithFactory();
}
}
// Usage:
// var myStore = StoreWithFactory.getInstance();
Usage is still the same, but you're not bogged down with having a single instance. Naturally you would move this factory method to it's own class as the Store class shouldn't concern itself with creation of itself (and coincidentally follow the Single Responsibility Principle as an effect of moving the factory method out).
From here you have many choices, but I'll leave that as an exercise for yourself. It is easy to over-engineer (or overheat) on patterns here. My tip is to only apply a pattern when there is a need for it.
Okay, first of all, the "singletons are always evil" notion is wrong. You use a Singleton whenever you have a resource which won't or can't ever be duplicated. No problem.
That said, in your example, there's an obvious degree of freedom in the application: someone could come along and say "but I want two stores."
There are several solutions. The one that occurs first of all is to build a factory class; when you ask for a Store, it gives you one named with some universal name (eg, a URI.) Inside that store, you need to be sure that multiple copies don't step on one another, via critical regions or some method of ensuring atomicity of transactions.
Miško Hevery has a nice article series on testability, among other things the singleton, where he isn't only talking about the problems, but also how you might solve it (see 'Fixing the flaw').
I like to encourage the use of singletons where necessary while discouraging the use of the Singleton pattern. Note the difference in the case of the word. The singleton (lower case) is used wherever you only need one instance of something. It is created at the start of your program and is passed to the constructor of the classes that need it.
class Log
{
void logmessage(...)
{ // do some stuff
}
};
int main()
{
Log log;
// do some more stuff
}
class Database
{
Log &_log;
Database(Log &log) : _log(log) {}
void Open(...)
{
_log.logmessage(whatever);
}
};
Using a singleton gives all of the capabilities of the Singleton anti-pattern but it makes your code more easily extensible, and it makes it testable (in the sense of the word defined in the Google testing blog). For example, we may decide that we need the ability to log to a web-service at some times as well, using the singleton we can easily do that without significant changes to the code.
By comparison, the Singleton pattern is another name for a global variable. It is never used in production code.