- 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
My personal favourite is the abstract final singleton factory.
Admin
Er.. nope. The JIT compiler outsmarts itself in this case and out of orders things it shouldn't. I believe it is going to be fixed at some point.
Admin
That would be WTF itself. If you are going to use the language, use it properly.
Admin
One doesn't provide polymorphism and the other does.
Admin
It's a requirement in c#. If you don't do it explicitly, then the parent must have a parameterless constructor that is called implicitly for you.
Admin
Such as sane accessors via properties instead of that fucking getters/setters crap?
Or delegates maybe?
Yes C# took inspirations from Java, and Delphi if you want to know, and C++ to boot, just as Java took inspiration in C/C++, Scheme, Smalltalk and Objective C when Oak was first thought.
Doesn't even fail as far as portability is concerned since:
Admin
"Simpleton": George Bush's favorite design pattern!
Admin
I don't think protected means what you think it means in Java. protected in C++ and C# means the class and all subclasses. Not exactly the same in Java:
http://www.25hoursaday.com/CsharpVsJava.html#access
Admin
Agreed. I just was saying that it's actually possible. Not necessarily advised.
Admin
Many have a problem with it because it's not object-oriented. I'm not hung up on that but I do use them sparingly. Some things, like common string and date validation, are better left stateless. I can't imagine why you would always or even frequently use them though.
Admin
Wrong. That's exactly what it means in Java. I'm not sure who wrote the fecal matter on that page but it says there is no "protected" keyword in Java. Also wrong.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
Admin
Well you did a good job reading the page. It says it does have a protected keyword - only that it doesn't mean the same thing as C++.
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Why protected allows other classes in the same package access makes no sense to me.
Admin
I don't think that it was saying that there is no protected keyword in Java, just that protected in Java corresponds to internal in C#. I could be wrong though.
But yeah, that page seems terribly uninformed. As far as I can see with Java, that the package scope is the equivalent of internal in C#. The protected scope is the same in both languages.
Admin
I wish it was seldom used. I maintain code written by someone who was in love with the singleton. He fell in love with Python just before starting this project, so he decided to write in Python. Which would be a good decision if he knew anything about python, but he decided that the readable syntax is the one difference between C++ and python. Thus he decalred all his variables, but then accessed them via selfm not realizing that he was refering to two different variables. Needless to say his singletons never works as singletons, which was good because he never wrote a class that needed a singleton.
class myClass:
def myFuct(self):
...
self.myVariable = ...
myVariable = foo.
I have come to hate singletons. Yes there are times and places for them. However 95% of the time when I see them they are not needed. A singleton that is not needed now has to keep track of state that should be kept track of by different instances of the class. (Of course there is that 5% of the time when the singleton is used to protect something that can only have one instance, normally a file or hardware device)
Did I mention I hate singletons?
Admin
Applicablilty - [second bullet] when the sole instance should be extensible by sublcassing and clients should be able to use an extended instance without modifying their code.
Consequences - Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class.
Implementation - 2. Subclassing the Singleton class.
If you just read the intent, you might think that. This is the problem, most developers have a very superficial understanding of the Singleton pattern. Note that the MazeFactory constructor is protected.
If you don't allow for subclassing and mutitple implementations, all you are creating is a global Object. It's really no different than a 'static class'. The main advantage of a global Object is that references to it can be passed to other Objects. But you can acheive the same effect with Object wrappers around 'static classes'.
Admin
Bullshit. I'm looking at the MazeFactory example at this moment.
Admin
A final or otherwise unextensible class doesn't realy allow polymorphism.
Admin
I guess you couldn't catch the inflection there. I was really saying that circumstances in which a Singleton is appropriate come about a lot more seldomly than they're used. I would certainly hate them too, if I worked with some clown who thought everything should be one.
Admin
Fair enough. On second reading, it seems like it's definitely written from a C# perspective, with superficial knowledge of Java.
Admin
Java has four levels of access (from most strict to least strict):
private - class + inner and nested classes
[default] - package access
protected - subclasses
public - every class
Each level grants a new access on top of the others. If protected didn't allow package access, it would be removing access already given above it.
Package access is actually more controlled than protected access. You can't stop people from subclassing your classes but you can (for the most part) keep them out of your package.
Admin
The problem is people who are used to using globals get into a language that doesn't provide them and get stuck. Then they find out about Singletons and they can continue to code with globals and feel content that their code is "OO".
Admin
And who decides what the JIT compiler should and should not reorder? As I understand it, the VM spec basically says that between memory barriers (entry and exit of synchronized blocks), anything goes as long as it doesn't change the semantics for a single thread, because that gives the JIT maximal freedom for optimization. If you need predictable behaviour in a multithreaded environment, "synchronized" is how you get it.
Do you really want to argue that the VM spec is "broken" because a unnecessary clever hack that tries to get something for nothing doesn't work?
There are efforts to make the Java Memory Model simpler as well as more accomodating to some JIT optimizations and less to others (esp. in regard to volatile fields) - "fixing" it to make double-checked locking work is not a motivation nor a likely outcome of that effort.
Admin
That table does appear to be wrong. If I understand the meaning of the C# key words correctly (from the explanation in that page) then it should be:
Admin
<FONT face="Courier New" size=2>the great cycle of life is thus preserved, and the hunters cull the weak from the herd. the tide washes away the majestic sand piper, leaving it to ruffle feathers with the hermit crab, a swath of sea foam in its wake. it's not often one finds solace in the 'natural' state of the world. waiting for that styrofoam to take you back, or perhaps, a canoe fashioned out of milk jugs and cans of raid. no, that can't keep out the sea cows! god help us! they're coming!</FONT>
Admin
I know it used to be like that. I also know that I thought it was still like that, but
it isn't. Did you even bother to read the sun tutorial that was linked? Or even try that
out?
I did. Protected in Java nowadays allows package access also. If you don't believe me,
please try it out yourselves. It's no use fighting here about it
Admin
Yes, they took one of the worst practices in the Java world and made it a part of the C# language. Way to go MS!
Admin
Your reading comprehension is poor.
Admin
I don't think it's quite that simple. If it were then people would always use inheritance (and thus polymorphism) and composition when each is appropriate. Many people mistakenly use the former when they should be using the latter. There are hazards associated with making the wrong choice.
Reference: http://www.ziggr.com/javaone2002/
Inheritance vs. Composition
Inheritance invites Fragile Subclass problem. Modifications to superclass breaks subclasses, because subclasses usually depend on superclass implementation. Inheritance has its uses, but don’t overuse it.
Composition promotes Builder classes: classes that glue together sub-units at component or application level. Composition avoids class explosion: lots of little subclasses each with slightly different behavior.
Admin
Yes, it seems so. After reading your post again, I realized that you were not the one
misunderstanding this. Sorry about that.
Admin
A clueless person asked an equally clueless question. The person answering the question had no idea the answer would be used for evil/stupidity.
This question is as good as asking a chef what specific condiment he/she uses all the time. You use the condiment required for the dish. Same with design patterns.
My rule is if you cannot justify the use of a pattern, you probably have no business using it. The design pattern used should fit application or architecture needs. If you find yourself abusing on type of pattern, you might be screwing things up.
We could classify Singleton as a Creation Pattern. Other creation patterns are Abstract Factory, Builder, Factory Method, Prototype, etc
There are also Structural and Behavioral patterns, not to mention Design , Deployment and Build patterns -- Heinz ketchup does indeed come in 57 varieties!
So the next time someone asks you what pattern you use to develop, educate the poor slob -- or better yet -- find out what he/she means.
Here are a couple good places to start him/her off:
http://www.dofactory.com/Patterns/Patterns.aspx [for .NET]
http://www.csc.calpoly.edu/~dbutler/tutorials/winter96/patterns/ [for Java]
http://home.earthlink.net/~huston2/dp/patterns.html [all]
Now, what condiment do you use for cooking?
Admin
Ketchup? No... Catsup!
Admin
So what you're saying is "so I can put it on my resume" or "it's a hot buzzword and everyone is talking about it" doesn't justify use of a specific pattern? :^)
Admin
Oh, someone must have seen my code.... those poor little functions needed somewhere to live.
Oh, they have also seen that website....... it wasn't late, however. We managed to make it of good quality by leaving out half the features. It turns out that half of the features were not actually necessary until at least a pair of months after the deadline........
Um, non-deterministic, just like my error processing logic. You never know where the actual error message will end up :) The system log? the error page? discarded inside the error displaying page because it's not the appropiate type of error?
Not to mention that nice corner-case login error that won't give you an opportunity to retry login and won't let you reload the login form because you are not logged in :) Hitting "back" is useless because all pages will now redirect you to the trap :)
Of course, this error requires logging in and then not closing the browser window for four hours while not reloading or visiting any page in the server...... so it only happens to me :(
Admin
Uh, the ability to define accessors is a Good Thing.
It was fucking badly done in C# compared to Ruby or Python for example, but they still tried, and that's hella nice.
Admin
Java provides a perfectly usable way to define accesors. You create a method. What's the problem, you don't like typing '()'?
I think it just encourages a bad practice and the syntactical sugar ain't that sweet.
People often create a class with a bunch of state and then provide public getters and setters to all their private variables and think they've acheived encapsulation. In fact it's terrible OO, on;y marginally better than making all the variables public.
Getters and setters should be the exception, not the rule. Therefore, I find a language feature that supports them to be of little value.
Admin
Maybe he thought it was called the 'Simpleton' pattern? That could explain it...
Admin
Are you recycling the joke from the title of this thread?
Admin
Yes, the table you put up is correct. For those ignorant of Java, this page might clear up a little: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
I've always found it annoying that there is no keyword for default access in Java. It's not used very often, but if I do intend to use it, it will look to the person maintaining my code as if I forgot to put an accessor on it, and they might make it public or protected. Of course I would put some comment saying that I intended default access, but there should be an explicit keyword that can be used as well.
Admin
I love package protected access. At first I didn't get the value of it, but it's really a great feature. It allows encapsulation at the package level. You can have a bunch of hidden classes in the package and provide a public factory. You can do all kinds of ugly stuff in the package protected classes without making a mess of the API or propagating your implementation details throughout the application. I use it much more than protected access.
Admin
Check the Python or the Ruby way to do these things, accessors generate fully virtual members instead of having you create useless functions, and allow you to switch any member from raw access to accessors-protected without changing the outer interface of the object.
And I fully agree with this.Try a language with an implementation of accessors actually worth using before saying that please.
Admin
Well, you don't get lazy initialization. And you do get the drawback of exceptions in the constructor (for example, trouble reading a configuration file) causing the class not to load and causing subsequent calls to give a NoClassDefFoundError which then sends you on a wild goose chase of trying to find a classpath problem.
If getinstance calls the constructor and throws the exception, then you can fix the config file, and then subsequent calls to getinstance will succeed rather than fail. Exceptions in static intializers are bad bad things. Synchronizing the getinstance method is a reasonable solution that I have yet to see cause performance problems.
Admin
I'm not sure I follow you. If you define a accessor method, how does that keep you from changing the implementation and how does that expose the implementation more than accessors? You can't know how a given method works just by looking at it's name.
This whole concept, IMO, is bad OO, or at least backwards OO. The API is the API, it should not be driven by the implementation. So much bad code is written in this way. The internal structure of the class is defined, then the developer creates some methods for working with them. It should be the other way around. The API is defined and then you create one or more implemetations. Formalizing accessors not only makes it easier to do it backwards, it legitimizes it in the minds of developers.
Explain to me how accessors are better than methods.
Admin
In most cases, the static initializer version and the 'lazy' version will create the instance at the same time in the application lifecycle. The static verison initializes when the class is first used. Generally, this is when the getInstance() method is first called.
Admin
Wrong again. It only works perfectly well in C++ on a single-processor machine. Multiple processors will have serious cache coherency issues with double-checked locking in any of the given languages. It's a disaster waiting to happen, and should just be avoided.
Admin
OK, since these reasons are so obvious, please cite some specifics. How does C# (or .Net, rather) fail when it comes to stability, security and scalability? I will grant you that portability is a definite failing, but 1 outta 4 is not good odds.
Let's see, .NET runs on windows,
yes mono exists, no corporations do not use it in production.
So windows :
stability Ooops,
security Ooops,
scalability It's not bad
portability Ooops.
T.
Admin
Let's say you're coding in Java.
Since you don't have any properties system (aka "true" accessors), either you have methods, or you have "true" members right?
The methods hide the implementation, that's ok, the members don't, because when you access a variable member you know what it is, you know that it's real and that it has a type.
Now if you want to change the implementation of your object, or if you realise that suddenly you have protection operations to do to a public member, you're fucked, because you can't hide it anymore unless you accept to break your object interface.
Result, either you have to get it right the first time and only expose as public the members that'll stay public, or you have to put every single member private and litter your code with useless getters and setters that only do single affectations or returs.
Many useless methods, and public members that are kept private for "future safety" reasons.
Ok, first of all let's define how properties ("true" accessors) work in Python or ruby.
Everything they do is create virtual members. From outside they look like regular member, are used and exposed the same way, but from the inside they're handled by specific methods. A property can correspond to a member, or not. No one cares. But from the outside of the object, properties are members and use as such for affectation or data retreival. They work logically.
The greatest strength of properties is that they allow the programmer to take the simplest way (KISS) and change his mind when the simplest way isn't enough. Changing his mind can be making a member read-only or completely reworking the inner part of the class. And properties allow him to do that "on the fly", without changing the interface, and even when he exposed public members because he had no reason to hide them (at the time).
Properties also hide the innards of the class because the outside of the object never knows if a member that it accesses is a "true" member or a virtual one, created via properties.
Properties are not any more "driven by the implementation" than method accessors.
object.member = value
. Want to retrieve it?value = object.member
. A member, real or virtual, is data. It should be treated as such.Admin
Better? Given one is syntactic sugar over the other it is hard to argue better, but it is cleaner IMO. Consider the usage:
int i = foo.getBar();
V.
int i = foo.Bar;
The get is implied and rather obvious, so what will having it in the method name possibly provide? For that matter, the only thing that binds getBar() and setBar(…) is a naming convention. That is much sloppier than just Bar. If you find yourself programming in C# and adding get to the name is "better" I recommend calling the functions get_Bar() or set_Bar(…). There, aren't we all happy now?
Admin
My point is the idea of exposing members is completely wrong. It's bad OO in theoretical and practical ways. Whether you make the members public or make them private an provide an accessor, it's wrong. You should not be leaking implementaion details. It's the wrong way to think about Object design. This is something it took me a while to learn but it's a huge difference in thinking.
What you are talking about are glorified structs. They are not Objects in the true OO sense.
But it's still a backwards design. You are creating this piece of data and them manipulating it from the outside. That's procedural design, not OO.
It might seem that way but the problem is the whole public member approach (through accessors or not) causes the entire application to depend on an API that was designed around the concept that this Object has a specific internal property that it maintains. This is a corrosive element in the design and is very difficult to undo.
Huh? That makes no sense. You are saying that I can't change the implementation of a method without changing the API? That's just wrong. In fact my APIs are generally abstract and have no inherent implementation.
Again, this whole idea is bad for general Object design. Its only helpful in the most trivial of Objects, e.g. essentially structs. it's like saying the Singleton pattern should be supported by the language syntax. It's a corner case that is overused because a lack of understanding of OO design.
I don't have many getter and setters because accessors are a bad way to design APIs. So this is a solution to a non-problem. If it do provide properties, they are generally read-only and I don't append "get" to them.
Admin
Python or Ruby guys would use
i = foo.bar
BTW. I guess C# guys have to differentiate accessors and members since accessors behave vastly differently :/Admin
It don't think you are getting the point. I wouldn't create a getBar() and a setBar() method or make the members public or similarly wrong approach in the vast majority of public APIs.
For the most part, this is syntactical sugar that makes it easier to do something stupid.