Class with static members vs singleton - c++

Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help.

This kind of class is known as a monostate - it is somewhat different from a singleton.
Why use a monostate rather than a singleton? In their original paper on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):
More natural access syntax
singleton lacks a name
easier to inherit from
I must admit, I don't find any of these particularly compelling. On the other hand, the monostate is definitely no worse than the singleton.

Robert C. Martin wrote an article some times ago about the differences between the mono state pattern and the singleton pattern.

Consider a family of Logging classes. They all implement "LogMessage(message, file, line_number). Some send messages to stderr, some send email to a set of developers, some increment the count of the particular message in a message-frequency table, some route to /dev/null. At runtime, the program checks its argument vector, registry, or environment variables for which Logging technique to use and instantiates the Logging Singleton with an object from a suitable class, possibly loading an end-user-supplied DLL to do so. That functionality is tough to duplicate with a pure static Singleton.

class with all static members/methods
a kind of singleton design pattern
Class - not pattern. When we talk about classes we can say class implements pattern.
Static functions - is not member functions, they are similar on global functions. Maybe you don't need any class?
Quote from wikipedia:
In software engineering, the singleton
pattern is a design pattern that is
used to restrict instantiation of a
class to one object.
By this definition your implementation is not singleton implementation - you don't use common idea One (or several in extended definition) instance of class.
But sometimes (not always) usage of class with all static functions and singleton pattern - not have meaningful difference.

For a singleton all constructors have to be private, so that you can access only through a function. But you're pretty close to it.

Related

Abstract Factory and classes as first class objects

A theoretical question. I'm reading Gof's Design Patterns, section Abstract Factory. The book mentions the possibility of implementing this pattern like a Prototype or, if the language permits it, with a Prototype which stores classes instead of objects.
I have understood this; e.g. in Java or Smalltalk, classes are also objects (in Java they are in fact instances of the class Class). Hence, we can store them inside a class and, when needed, invoke the creation of instances of these classes.
In C++, classes are not first class objects; hence, we shouldn't be able to follow this approach. However, couldn't we declare nested classes inside inside a Concrete Factory, with methods which invoke their constructors (and return their instances)? The final result would be the same of other languages such as Java or Smalltalk. Am I right?
Thank you for your attention.

Static variables inside instance methods - How to fix that?

Recently I inherited 10 year old code base with some interesting patterns. Among them is static variables inside instance methods. Only single instance of the class is instantiated and I can hardly find reason to justify existence of those static variables in instance methods.
Have you ever designed instance methods with static variables? And what are your rationales?
If this pattern is considered bad then how to fix it?
Note: This question is not relevant to Static variables in instance methods
EDIT:
Some reading:
static class and singleton
http://objectmentor.com/resources/articles/SingletonAndMonostate.pdf
http://www.semantics.org/once_weakly/w01_expanding_monostate.pdf
This is a classic C++ implementation of the singleton pattern, described in one of Scott Meyers C++ books.
Singleton is a controversial pattern, so there is no industry-wide consensus on singleton being good or bad.
An alternative to singletons is a purely static objects. This question has a good discussion.
About the only time I've used static fields in an instanciable class has been as constants.
Generally speaking, you would want to create your class to be either entirely static, or entirely instanciable (with perhaps the exception of constants which you may want to keep static). With a singleton class they will behave in much the same way. The danger of mixing the two techniques is if you decide to make the class no longer a singleton, you might run into some strange behaviours in your now multi-instanced class.
Having a static variable is useful in a procedural function as it can serve as a kind of global variable with limited scope.
The only reason I can see to do something like this in a method would be to have the variable persist over many calls without having to declare a member variable that serves no other purpose. Honestly, I feel like this is just lazy programming and should be avoided.

name of this c++ implementation pattern

There is certain implementation pattern in C++, that I describe below, it is used in std::iostream library and other similar libraries.
Can anybody recall name of this pattern?
The pattern is described like this:
- There is central class IO used for output of data, or for conversion of data (e.g, std::ostream).
- for every application class for which output conversion is defined, "converters" are GLOBAL functions, not member functions of IO. The motivation for this pattern is
(1) designer of IO wants to have it "finished", not needing any changes when another application class with convertor is added, and
(2) because you want IO to be a small manageable class, not a class with 100 members and 1000s of lines. This pattern is common when decoupling is needed between IO class and multitude of "user" classes.
What is name of this pattern?
looks like it's the Herb Sutters' "Interface Principle"
at least I read it from one of his books
the interface must be minimal, all functions, which do not need private data (for compiling or runtime speed), should be in outer functions.
This is not a design pattern at all.
Design patterns are not tied to a programmng language. What you describe is done because the class std::ostream comes from a library. So you can not conveniently add "operator <<(MyClass &ob)" member functions.
The proper term instead of design pattern is "idiom". See e.g.: http://en.wikibooks.org/wiki/C++_Programming/Idioms or http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms (not sure if your case is listed, on a first glance I did not find it)

When to use friend class in C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.
Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?
I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good reason to look at internal details that are deliberately hidden from other classes.
In my experience, the cases when friend (or mutable, which is a little similar) to actually enhance encapsulation of data are rare compared with how often it's used to break encapsulation.
It's rarely useful to me but when I do use it it's for cases in which I've had to split a class that was formerly a single class into two separate classes that need to access some common data/functionality.
Edit to respond to Outlaw Programmer's comment: We absolutely agree on this. One other option apart from friend'ing classes after splitting them is to make public accessors, which sometimes break encapsulation! I think that some people think that friendly classes somehow breaks encapsulation because they've seen it used improperly a lot, and many people probably never see code where it's been used correctly, because it's a rare thing. I like your way of stating it though - friendliness is a good middle ground between not allowing you to split up your class and making EVERYTHING accessible to the public.
Edit to respond to David Thornley: I agree that the flexibility that C++ allows you to do things like this is a result of the design decisions that went into C++. I think that's what it makes it even more important to understand what things are generally good and bad style in flexible languages. Java's perspective is that you should never have friend classes so that these aren't provided, but as C++ programmers it's our responsibility as a community to define appropriate use of these very flexible but sometimes misused language constructs.
Edit to respond to Tom: Mutable doesn't necessarily break encapsulation, but many of the uses of the mutable keyword that I've seen in real-life situations break encapsulation, because it's much more common to see people breaking encapsulation with mutable than to actually find and understand a proper use of mutable in the first place.
When you wish that one class (Factory) be responsible for creating instances of another class (Type). You can make the constructor of the Type private and thus make sure that only the Factory can create Type objects. It is useful when you wish to delegate the checks to some other class which could serve as a validator.
Just one usage scenario.
P.S. Really missing the "friend" keyword in C#...
A concrete instance would be a class factory, where you want one class to only be created through another factory class, so you make the constructors private, and the factory class a friend of the produced class.
It's kinda' like a 2" 12-point 3/4"-drive socket - not terribly common, but when you need it, you're awfully glad you have it.
Helps with Memento design pattern
The FAQ's section about friends: here
The FQA's section about friends: here
Two different points of view about friend.
I look at the friend construct as one of those features of the language that should be used in rare occasions, but that doesn't make it useless. There are several patterns that call for making friend classes, many of them already on this site in that "Related" bar on the right. ====>
Friendship is used when you have multiple classes and/or functions that work together to provide the same abstraction or interface. The classic example is implementing some kind of numerical class, and all the non-member operator functions (*, -, +, <<, etc) are given friendship so that they can work on the private data of the numerical class.
Such use cases are somewhat rare, but they do exist, and friend is very useful.
Here is one example, of several, I'm sure, where a friend class can be legitimately used without disregarding the reasons for encapsulation.
MyClass inherits from GeneralClass. MyClass has gotten big, so you created HelperClass to encapsulate some of the function of MyClass. However, HelperClass needs access to some protected functions in GeneralClass to properly perform it's function, so you make HelperClass a friend to MyClass.
This is better than exposing the protected functions, because they don't need to be available to everybody, but it helps keep your code organized in an OOP way to keep MyClass from getting too complex. It makes sense, because although HelperClass isn't concretely related to MyClass by inheritance, it does have some sort of logical connection to it, embodied in the code, and in design, as "friend".
I always ( and only ) use friend for unit testing private methods. The only other way I can imagine to do this would be to load up the public interface with a whole lot of testing methods, which is just too messy and so I prefer to hide the test methods in a seperate test class.
Something like this:
class cMyClassTest;
class cMyClass
{
public:
.....
private:
friend cMyClassTest;
int calc(); // tricky algorithm, test carefully
};
class cMyClassTest
{
public:
int test_calc()
{
cMyClass test;
....
int result = test.calc();
if( result == 42 )
return 1;
return 0;
}
};
friend class mean we all know that is acesss the value of variable from other class so it is mainly used for use the values so we no need to return the value of other class to main function then main to needed class member function but it having the problem that is a class is friend for other class then friend class should be in below of that class

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.