- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Go away.
Admin
Admin
What? You never need to access bar outside that class? Ever? You never need to retrieve or set the value of a member variable from outside of its containing object? Amazing.
You know what's that real WTF? These CAPTCHAs work only half of the time, if that.
Admin
Yes, you do, unless you use the class in some other way before.
Only if you don't pay attention to the ExceptionInInitializerError that will be thrown wherever you tried to access the class first.
No difference - you'll still have to analyze the error and fix it. Or, if you can react to it in the program, you can do a more sophisticated initialization including exception handling and fallback to a default configuration in a static initializer block.
Admin
It's really not amazing. The problem is that by and large, most developers do not understand OO design and are building procedural designs with Objects and thinking it's OO.
For example, I created a multi-purpose tool for flat file formats that parses the flat-file spec and the data based on that spec and displays in it a command-line mode or an editable gui mode. When I finished the initial iteration, none of the concrete classes that are used to represent the data in memory were public and the abstract base class didn't have any public methods or properties.
I implemented this using a Builder pattern.
Admin
Let me clarify that I may end up at some level providing methods that take values to modify state. But in no way are these represented on the API as internal properties of the Object.
Admin
You can obviously populate a value object using the constructor but how would a client make use of the that value object without public (methods and/or members) accessors?
Admin
Mono will not happen, it will not get industry use. Like Nant and other .Net toys, it is simply a bunch of bored developers doing something unoriginal like porting crap. They may aswell stick to C++ and keep porting this. On security , scalability, stability, I need just to state that C# runs on Windows. DO NOT be mislead by the ISO standard rubbish. Microsoft wants this to run on Windows and only Windows, as this is how they make money. If they felt any threat of platform i.e. Linux , they would not hestistate to make things incompatible. Remeber J++ and nice String class it had? I am not saying Java is the 'perfect' OO language, and have used both, but in terms of an abstraction and being thought through it is superiour. I wish it was purer akin to Small Talk. Microsoft had all the opportunity, resource and made no leaps forward and left all the holes trying to maintain backward compatability i.e. pointer support. I find their Tower of Bable approach to computing laughable but depressing. Why would you endever to have a portable language that runs on any machine when you six hundred syntactactic variants that run on One? Cause you want one platform aka Windows. Also yes delegates are crap the simplest way to allow naieve or new developers to write apps called MainForm.cs. Would you really trust a language that needs if (this == null) code for backward compatabilty ? I dont
Admin
The very concept of a "value object" violates OO principles. The most essential fundament of object orientation is that objects have state AND behaviour. In most cases, clients should not take values from an object but instead ask the object to perform actions using the values(=state) it holds. i.e. not (as ist still most commonly done)
file.write(format(valueObject.getId()));
file.write(format(valueObject.getName()));
...
but instead
valueObject.writeTo(file);
Admin
Are there structs in Java? I havent seen and sometimes you just want to bunch together data that belongs together. I those cases I've used an private class with the nessesary fields. If there is a better way please enlighten me.
Admin
I think you're a bit late for that
Admin
You may want to provide a value like name() from your API. But this decision should be made completely independent of whether you have a String member variable 'name' in your class.
Admin
And why the hell would you provide it through a damn blasted method for god's sake?
Methods are supposed to be messages to the object, you don't want to send a message you want to retrieve an information!
Admin
An accessor is just a special method. What's your point?
Admin
While I won't contest your statement, I believe you are overcomplicating the definition of the pattern beyond the intent given in the GoF book. Surely subclass-extensible operations are important, and surely it's important to show how the pattern can be used to achieve those goals. But to commingle that ability with such a simple concept is a misrepresentation, IMHO.
Global objects are fine if the instance really is global to the scope of the program.
Static (or stateless) classes are plenty useful. As are stateful instances. Each serves its own purpose, and the religious avoidance or adherence to either is unwise, IMHO.
Admin
Simpleton or Singleton ?
Admin
No, there are no structs in Java. In those cases, if you manfully resist the urge to program procedurally, you will more often than not find that you can equip that class with some methods and have it actually do something with the data it holds, instead of having some other class retrieve the dat and do something with it.
Admin
This is not a singleton. It's a monostate class. Back to handbooks! BTW: I do not see any synchronization here, I guess class is used only in single-threaded environment?
Admin
Whats with this multi-threading fetish everyone here seem to have? Personally, in 25 years of programming, I have only twice needed multi-threading (I've used it more often because I've had to because I wasn't making the design decisions). Once was for an embedded platform where the OS in use had ridiculously expensive process creation. Once was because I stupidly decided to try it to "simplify" a finite state machine that worked perfectly well as it was.
Without exception, whenever I've considered multi-threading the end result has been that I've realised that a multi-process design with state exchange or access synchronisation through pipes or sockets would work just as well and give more flexibility, scalability and security.
I've never once (and I've worked on systems with millions of users) been in a situation where multi-threading would give even a tenth of the performance improvement needed to justify the cost in developer time (two man weeks lost over the lifetime of a system would easily finance an extra dual CPU server - I've seen projects lose many times that in design/development alone) of dealing with the additional defects to deal with complex synchronisation issues and availability problems due to the ease of corrupting state for all the threads at once.
All the discussions here about thread safety are great examples of exactly why to stay the hell away from multi-threading.
Now, I know there are valid cases where multi-threading is needed, but it's nowhere near as important as people make it out to be (or is Windows and/or Java process creation costs really that high?), and the advantages are usually outweighed by the problems it causes.
V
Admin
As in industry standard you clown. What does it run on Linux, Solaris ... Unix flavours? What are these used for predominantly in the industry ? Servers. What has the industry already plugged for interms of server side development? Java. You do and will continue to find that the majority of server development will be in for Java and using Unix/Linux, purely for the reasons I have sighted. C# will remain confined to the the Windows rich client dev language of choice.
Admin
A multiprocess design can only be more flexible or scalable when you're actually going to run it on multiple machines - otherwise it's inevitably LESS flexible and scalable than a multithreaded design. As for security - you still have fundamentally the same problems with state exchange and synchronization, except that with a multiprocess design you have to do a lot more work and lose a lot more performance for every inter-process communication. The only disadvantage of multithreading is that inter-thread communication is TOO easy and can happen inadvertedly.
The only reason why thread-safety is discussed here so often is that the theme of the site puts people in fault-finding mode - most of the time it's perfectly fine to write code that is not threadsafe, even in an environment that is multithreaded by default like Java, because you're not actually going to share instances between threads.
Admin
Singleton is not about global variables (though it can be abused in this way). Global variables don't provide data hiding and behavioral encapsulation. With global objects, you can do that, although of course the compiler won't force you. And singleton objects can be used polymorphically, unlike free functions or static methods. So, many, though not all, disadvantages of global variables are not shared by singletons. The only remaining potential problem seems to be shared state, which of course is exactly the reason why singletons are used in the first place. So if you need shared state (shared throughout the entire process, if we ignore thread-local "singletons" for now), singleton objects are a good choice. If you don't need it, then there is no point in using singletons, and you will only suffer the disadvantages of shared state.
Admin
Indeed that does not compile,
but take a look at this:
about the use of a private constuctor in C#:
<a href="http://msdn2.microsoft.com/en-us/library/kcfb85a6.aspx> http://msdn2.microsoft.com/en-us/library/kcfb85a6.aspx
Admin
Not looking too hard dude, are you? What's the name of any subclass of MazeFactory? Oh wait, there isn't one.
Instead of telling people what they say is bullshit, you should be more sure of your facts. The GoF book repeatedly gives examples of non-subclassed Singletons. And none , repeat none, of any subclassed ones. It says you "can" or "may" subclass, it does not at any time say you "must".
You also succeeded in missing the other point I made completely, which is that some languages do not support static classes, so Singleton is your only option if you want to do this sort of thing.
Admin
Singletons are often exclusively about providing a "global point of access" (google for that phrase), not about preventing further instantiations, so said "contract" (if you use the compiler to enforce this restriction, you don't need a contract anyway) is irrelevant in most cases. Even if you do need uniqueness, there are mechanisms to enforce it when using subclasses. For example, the base class could initialize the static variable that holds the singleton instance in the constructor (thread-safely, of course, if necessary) and throw an exception if another instance registered itself beforehand. Granted, a run-time check is only the second-best solution.
Factory is an entirely different kind of pattern and has little to do with singletons, except that factories can be (ab?-)used to return singleton objects, and, of course, factories can be singletons themselves and often are.
At my workplace, we use a factory that is a singleton, and which creates/returns objects that may or may not be singletons (depending on the type). Also, objects are strictly returned by interface. This may sound a little bit confusing, but it works very smoothly.
Admin
The example (DesignPatterns (pg. 133, Gamma et. al.: 16th printing December 1998) contains the following code:
Exactly what do you think, BombedMazeFactory, EnchantedMazeFactory are and what do you think "other subclasses" means?
It says the pattern is applicable when you need subclassing. After using the pattern extensively I've also learned from experience that it's nothing special without sublclassing.
How do you get the single instance without some sort of static or global reference? What languages are you referring to in particular?
Admin
How can Singletons and Factories be 'entirely different' and at the same time have a Factory that is a Singleton? A Singleton is basically a Factory that return the same instance to all callers. For the caller's perspective, how is it different?
Admin
The rules in C# and Java are almost the same as in C++, even a bit more strict. That is, in C++, you can derive from a class that has only private constructors, but you can never instantiate the subclass (unless of course the subclass is a friend of the superclass). So the subclass can only be used as a container for static fields and methods.
In C#, on the other hand, deriving from a class with no non-private constructors immediately causes a compile-time error, because, unlike C++, C# does not use "lazy instantiation" of compiler-generated methods.
Admin
I suppose if you are talking about the GoF Abstract Factory, it is quite different. I usually think of the Factory in terms of the simple 'Horse Trader' pattern, as I've seen it called.
Admin
Hello Mr. Beennappingforalongtime,
constructors do not instantiate classes, they initialize instances. Nothing prevents you from writing a constructor for an abstract class. If you don't, the compiler will typically (i.e. in all of C++, C# and Java) provide one or more auto-generated constructors that subclasses can use. Any virtual function except a virtual destructor can be implemented without calling the superclass version (at least from a "make it compile" point of view), but constructors are special. If you don't explicitely call the superclass constructor in a subclass, the compiler will call the default constructor of the superclass for you. If it's inaccessible or cannot be instantiated, you will get an error. It doesn't matter one iota whether the superclass is abstract or not. Only interfaces aren't initialized in this way - they cannot have constructors.
This is the way things are in C++ and they have been ever since its inception. Same for C# and Java. If you don't believe me, RTFM or try it yourself.
And, by the way, "parent" and "children" are not the terms typically used to describe superclass and subclass (base and derived class in C++ terminology).
Admin
No, it works perfectly well in some C++ implementations, on some hardware architectures. And it mostly doesn't work at all in multi-threaded applications running in environments with more than one hardware thread (i.e. multi-threaded processors, multi-core processors, multi-processor systems or any combination thereof). Unless you use the ProcessAffinityMask (or whatever it's called on your target OS) to force execution on a single hardware thread.
In short: If you use double-checked locking in C++, you should better know exactly what you are doing.
Admin
Ok, let me rephrase that - Singleton and Factory Method are patterns with different purposes and useful in different contexts. However, a single method can both be a factory method and a singleton-providing method.
Likewise, "black" and "billiard ball" are entirely different concepts, even though there are black billiard balls. The concepts are distinct even though they are not disjoint.
PS: Isn't billard a brillant game?
Admin
I just see Singleton 'instance()' methods as a subset of factory methods. All Singleton 'instance()' methods are factory methods, are they not? Can you give an example of a Singleton 'instance' method that clearly not a factory method?
So going back to your analogy, I see it more like 'ball' and 'billiard ball'.
Admin
I think the problem here is that the Singleton is poorly defined in the GoF. If you read carefully, (e.g. the applicability section) it becomes clear that the point is not merely to create a global Object, it's to create something that can be easily modified so that code built around it can be reused.
This is not to say that you can't create a Singleton without creating subclasses. It's often that there is no other implementation. I may have overstated my case before. The point I am trying to make is that when people claim that subclassing the Singleton is verboten, they are missing the point of the pattern. The point (even if you don't sublcass initially) is to create a place where you can 'inject' new behavior without changing the clients.
If all you are doing is creating a single instance of a single class fo ever more, you might as well make a static class and if you need them create wrappers to that class that implement interfaces. Obviously, it's more convienient to just create the global Object, which is fine. But it's not the real goal of the Singleton pattern.
I'm not saying they are not useful. But the idea that creating a global Object is much better than creating a static class is a widely held misunderstanding of the real value of the Singleton pattern.
Admin
Singleton 'instance()' methods are just one of many ways to implement the Singleton pattern. For example, the simplest way in C++ is just a object in namespace scope, or as a static class member. Or as a free function or static method or non-virtual non-static method returning a reference to a static variable of the given type (implicitly offers lazy initialization). Another way is stuffing object pointers/references into a global hashtable, etc.
This offers a global point of access - if you need unique instances, there are ways to ensure this as well in all of the given cases (preferrably at compile time, but at least at runtime).
Factory Method means to use polymorphism to create objects of different types depending on the concrete type of the class that contains the factory method. In GoF it is assumed that the factory method returns newly created objects, but these could also be singletons or be recruited from a pool for all I care.
So a factory method can return singletons, but singletons need not be provided by a factory method in any way.
Admin
Er.. nope:
The issue of the failure of double-checked locking is not due to implementation bugs in JVMs but to the current Java platform memory model. The memory model allows what is known as "out-of-order writes" and is a prime reason why this idiom fails."
Admin
This means that code that relies on a compiler that does not re-order writes in a way permitted by the Java memory model is inherently broken. Compilers are not required to sacrifice performance just in order to ensure that the code does what you mean it to do, or what you think it does.
Computers are stupid because they only do what someone told them to.
Admin
"Mono will not happen, it will not get industry use. Like Nant and other .Net toys, it is simply a bunch of bored developers doing something unoriginal like porting crap."
Look into it more before you spout bullshit. Mono in real terms is less mature simply because it's a larger project, but NAnt is already seeing widespread industry use. I use it at work, with great success.
By your logic, Linux wouldn't be widely used by, well, anyone, since all it does is ape Unix.
Admin
Indeed. The fundamental thing that makes programming difficult is that the computer does exactly what you tell him to do - not what you want him to do. The problem is therefore telling the computer what you want correctly and unambiguously - something that humans are surprisingly bad at.
I read a pretty funny account somewhere of how the first programmers working on tube based machines back in the 1940s found out that programming was far more difficult than they'd imagined; one said that he "could remember the exact moment when I realized that I'd spend a significant part of my life from then on finding errors in my own thinking".
Admin
LOL It was a nice re-troll. I thought a nice "back at ya" was appropriate since he was making generalities, I made my own.
But the statement about the java programmers that worked at my old company was unfortunately true - and they are the only java programmers that I have known. It kinda left a bad taste in everybody's mouth about java, especially as the performance was crap and really really buggy.
Admin
Good point though, and something to remember for the future (not that I've really used singletons that much).
Admin
Like you've said, it is sytactic sugar, but I like it and makes the code about 1000 times more natural and readable. Technically, all languages are 'syntactic sugar' - we should all be coding pure binary if you want to take it that far. Anything else is just being lazy - do you think a microprocessor knows anything about objects?
But you don't seem to understand how these work in C# - the actual variable accessed is not the same name as the public accessor. The name is arbitrary, just like the name of a method you wish to expose. My accessor can be called 'foo', but it will store the actual value in 'bar' if I wanted.
<font size="2">public string foo {</font>
<font size="2"> get {</font>
<font size="2"> return bar;</font>
<font size="2"> }</font>
<font size="2"> set {</font>
<font size="2"> bar = value;</font>
<font size="2"> }</font>
<font size="2">}</font>
No implementation details are exposed by this at all.
In fact, the name has to be different anyway, otherwise you end up with a recursive loop - that's a little gotcha that caught me when I first learned about these.
Admin
Python's had 'em since 2.0. And yes, this is relevant to .NET if you've heard of IronPython, it's the Jython you have when you get sick of going to court with Sun.
Admin
You get more and more charming on each reply.
Right, and none of those subclasses are singletons. They can't be because they have public constructors.
(And this is even before we start on how bad a piece of code that is. An ancestor class that has to know about its subclasses? Please.)
After my extensive experience I've found it very rarely has subclasses. This is because of language bias, and that is also the reason why your experience is different.
That's not what I'm saying. Languages like Delphi (Object Pascal) have historically not had static field or properties. So you cannot use the technique of having a purely static class if that class needs state information. You have to use a Singleton implementation instead, whether or not you have any intention of subclassing it.
There is a subtle language bias in the GoF. If you have only ever used C++, Java, or C# you probably will not see the usefulness of Singleton for non-subclassed types, because you can just use a static class all the time. Delphi programmers can't (well, they can now in .NET), so they have to use Singletons instead.
OTOH, Delphi has always allowed virtual static methods, so if you don't need state info, you can do subclassing without using Singleton. I miss not being able to do that in C#.
In .NET versions of Delphi, you do not need Singleton except if you require a fixed number of instances > 1. Since you can have static fields and properties and static virtual methods you can subclass to your heart's content. If the GoF had used a language like that then Singleton might not even have made the book. Language bias, see?
Admin
What does he mean it doesn't work? I can definitely see a single TON of issues here!