• (cs) in reply to nickelarse

    My personal favourite is the abstract final singleton factory.

  • Asd (unregistered) in reply to brazzy
    brazzy:
    Quinnum:


    Well, it works in theory, except that the JVMs are broken.



    Nope, it's the theory that's broken because it tries to out-smart the JIT compiler in the very sensitive area of multi-thread synchronization, and doesn't take into account out-of-order execution.

    But the real joke is that the most simple and short implementation - initializing the Singleton in the static field declaration - has exactly the intended benefit (lazy initialization, no synchronization), without any drawbacks.

    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.
  • (cs) in reply to Ytram

    Ytram:

    Yeah, you can still type out the accessor/mutator methods just like Java.  It's just creating methods instead of using the built-in syntactic sugar of .NET properties. 

    That would be WTF itself.  If you are going to use the language, use it properly.

  • (cs) in reply to dubwai
    dubwai:

    What is the difference between a single class member and a single Object member?  Not much.

    One doesn't provide polymorphism and the other does.

  • (cs) in reply to The Troll

    Anonymous:
    And calling the parent's constructor is usually advisable at some point. Or is it not ?

    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.

  • (cs) in reply to Kinko
    Anonymous:
    b) it introduces all the rubbish that Java removed deliberately

    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.

    Chris F:
    Kinko:

    I suggest you get a real job at a proper company and you will see that majority server side code is written in Java, and would never be written on C# for the obvious reasons i.e. stability, security , scalability, portability


    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.

    Doesn't even fail as far as portability is concerned since:

    • C# has been a public ISO standard since 2003, anyone can gather his shit together, work on a .Net environment and implement C#
    • Mono implements the whole .Net 1.x environment but Winforms as well as some parts of .Net 2
  • George Jempty (unregistered)

    "Simpleton": George Bush's favorite design pattern!

  • Dange (unregistered) in reply to Mung Kee

    Mung Kee:
    Anonymous:
    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).


    Oh, I understand completely.  All I said was, why do I have to call Instance() at all when the constructor allows protected access.  If I just use the constructor when does instance == null get evaluated?  It doesn't. 

    Does "protected" in C# mean 'subclass access' as it does in Java?

    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

  • (cs) in reply to JohnO
    JohnO:

    Ytram:

    Yeah, you can still type out the accessor/mutator methods just like Java.  It's just creating methods instead of using the built-in syntactic sugar of .NET properties. 

    That would be WTF itself.  If you are going to use the language, use it properly.



    Agreed.  I just was saying that it's actually possible.  Not necessarily advised.
  • (cs) in reply to ProffK
    ProffK:
    What's wrong with static classes?  I always use them as well, and I always declare them like thism, in case I need more than one:

    private StatClass1
    {
      static string scName;
    }
    private StatClass2
    {
      static string scName;
    }


    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.
  • (cs) in reply to Dange
    Anonymous:

    Mung Kee:
    Anonymous:
    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).


    Oh, I understand completely.  All I said was, why do I have to call Instance() at all when the constructor allows protected access.  If I just use the constructor when does instance == null get evaluated?  It doesn't. 

    Does "protected" in C# mean 'subclass access' as it does in Java?

    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



    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
  • Dange (unregistered) in reply to Mung Kee
    Mung Kee:
    Anonymous:

    Mung Kee:
    Anonymous:
    It needn't be in a multi-threaded app since the constructor allows protected access.  Any subclass can ignore the Instance() method and invoke the constructor, provided that "protected" means the same thing in the language used in the example as it does in Java.

    I'm not sure you understand. If two threads call Instance() at the same time, you could get two instances created. Both threads check that instance is null at the same time (before either constructs it and sets that field).


    Oh, I understand completely.  All I said was, why do I have to call Instance() at all when the constructor allows protected access.  If I just use the constructor when does instance == null get evaluated?  It doesn't. 

    Does "protected" in C# mean 'subclass access' as it does in Java?

    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



    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

    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.

  • (cs) in reply to Mung Kee
    Mung Kee:
    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


    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.
  • (cs) in reply to Mung Kee
    Mung Kee:
    dubwai:
    Other than that, I don't have a lot of use for Singletons.


    I agree.  For a seldom used pattern, it sure gets a lot of publicity.



    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?
  • (cs) in reply to Chris F
    Chris F:
    dubwai:

    Seriously, read the pattern, specifically the purpose.  If it's not sublclassed, it's not really a GoF singleton.  Mos people who are implementing 'singletons' haven't actually read the pattern description.


    The intent states: Ensure a class only has one instance, and provide a global point of access to it.

    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.


    It doesn't matter if the class is subclassed or not.  The examples in the GoF book specifically provide a non-subclassed MazeFactory.  It's still called a singleton.  Subclassing the singleton instance is just a useful technique the authors mention, not the defining point of the pattern.

    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'.

  • (cs) in reply to Jim Cooper

    Anonymous:
    Subclassing Singletons is most definitely *not* "the whole point". You may or may not want to subclass a Singleton, but IME you almost always do not. The GoF struggled to find an example of subclassed Singletons too.

    Bullshit.  I'm looking at the MazeFactory example at this moment.

  • (cs) in reply to JohnO
    JohnO:
    dubwai:

    What is the difference between a single class member and a single Object member?  Not much.

    One doesn't provide polymorphism and the other does.

    A final or otherwise unextensible class doesn't realy allow polymorphism.

  • (cs) in reply to hank miller
    hank miller:
    Mung Kee:
    dubwai:
    Other than that, I don't have a lot of use for Singletons.


    I agree.  For a seldom used pattern, it sure gets a lot of publicity.



    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?


    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.
  • (cs) in reply to Ytram
    Ytram:
    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.


    Fair enough.  On second reading, it seems like it's definitely written from a C# perspective, with superficial knowledge of Java.
  • (cs) in reply to Dange

    Anonymous:
    Why protected allows other classes in the same package access makes no sense to me.

    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.

  • (cs) in reply to hank miller

    hank miller:

    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)

    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".

  • (cs) in reply to Asd
    Anonymous:

    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.


    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.
  • (cs) in reply to Mung Kee

    Mung Kee:
    Ytram:
    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.


    Fair enough.  On second reading, it seems like it's definitely written from a C# perspective, with superficial knowledge of Java.

    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:

    <FONT color=#0000ff>C# access modifier</FONT> <FONT color=#ff0000>Java access modifier</FONT>
    <FONT color=#0000ff>private</FONT> <FONT color=#ff0000>private</FONT>
    <FONT color=#0000ff>public</FONT> <FONT color=#ff0000>public</FONT>
    <FONT color=#0000ff>internal</FONT> <FONT color=#ff0000>[default]</FONT>
    <FONT color=#0000ff>protected</FONT> N/A
    <FONT color=#0000ff>internal protected</FONT> <FONT color=#ff0000>protected</FONT>

  • (cs) in reply to dubwai

    dubwai:
    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".

    <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>

  • Teemu (unregistered) in reply to dubwai
    dubwai:

    Anonymous:
    Why protected allows other classes in the same package access makes no sense to me.

    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.



    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



  • (cs) in reply to masklinn
    masklinn:
    Anonymous:
    b) it introduces all the rubbish that Java removed deliberately

    Such as sane accessors via properties instead of that fucking getters/setters crap?

    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!

  • (cs) in reply to Teemu

    Anonymous Retard:

    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

    Your reading comprehension is poor.

  • (cs) in reply to JohnO
    JohnO:
    dubwai:

    What is the difference between a single class member and a single Object member?  Not much.

    One doesn't provide polymorphism and the other does.



    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.

     
  • Teemu (unregistered) in reply to dubwai
    dubwai:

    Your reading comprehension is poor.



    Yes, it seems so. After reading your post again, I realized that you were not the one
    misunderstanding this. Sorry about that.
  • OverloadedOperator (unregistered)

    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?



  • (cs) in reply to OverloadedOperator

    Anonymous:

    Now, what condiment do you use for cooking?

    Ketchup?  No... Catsup!

  • (cs) in reply to OverloadedOperator
    Anonymous:
    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.


    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?  :^)


  • (cs) in reply to masklinn
    masklinn:

    2.1 Adopter

    The Adopter Pattern provides a home for orphaned functions. The result is a large family of functions that don't look anything alike, whose only relation to one another is through the Adopter.

    Oh, someone must have seen my code.... those poor little functions needed somewhere to live.

    masklinn:

    2.3 Compromise

    The Compromise Pattern is used to balance the forces of schedule vs. quality. The result is software of inferior quality that is still late.

    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........

    masklinn:

    3.1 Chain of Possibilities

    The Chain of Possibilities Pattern is evident in big, poorly documented modules. Nobody is sure of the full extent of its functionality, but the possibilities seem endless. Also known as Non-Deterministic.

    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 :(

  • (cs) in reply to dubwai
    dubwai:
    masklinn:
    Anonymous:
    b) it introduces all the rubbish that Java removed deliberately

    Such as sane accessors via properties instead of that fucking getters/setters crap?

    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!

    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.

  • (cs) in reply to masklinn

    masklinn:
    Uh, the ability to define accessors is a Good Thing.

    Java provides a perfectly usable way to define accesors.  You create a method.  What's the problem, you don't like typing '()'?

    masklinn:

    It was fucking badly done in C# compared to Ruby or Python for example, but they still tried, and that's hella nice.

    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.

  • hermit (unregistered)

    Maybe he thought it was called the 'Simpleton' pattern? That could explain it...

  • (cs) in reply to hermit

    Anonymous:
    Maybe he thought it was called the 'Simpleton' pattern? That could explain it...

    Are you recycling the joke from the title of this thread?

  • (cs) in reply to dubwai
    dubwai:

    Mung Kee:
    Ytram:
    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.


    Fair enough.  On second reading, it seems like it's definitely written from a C# perspective, with superficial knowledge of Java.

    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:

    <font color="#0000ff">C# access modifier</font> <font color="#ff0000">Java access modifier</font>
    <font color="#0000ff">private</font> <font color="#ff0000">private</font>
    <font color="#0000ff">public</font> <font color="#ff0000">public</font>
    <font color="#0000ff">internal</font> <font color="#ff0000">[default]</font>
    <font color="#0000ff">protected</font> N/A
    <font color="#0000ff">internal protected</font> <font color="#ff0000">protected</font>



    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.
  • (cs) in reply to kipthegreat

    kipthegreat:

    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.

    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.

  • (cs) in reply to dubwai
    dubwai:

    masklinn:
    Uh, the ability to define accessors is a Good Thing.

    Java provides a perfectly usable way to define accesors.  You create a method.  What's the problem, you don't like typing '()'?

    1. You reveal the innards of your objects (if you're calling a method it's an accessor, otherwise it's a member)
    2. You can't change your mind and hide a member by accessors if you need to without breaking everything

    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.

    Getters and setters should be the exception, not the rule.

    And I fully agree with this.

    Therefore, I find a language feature that supports them to be of little value.

    Try a language with an implementation of accessors actually worth using before saying that please.

  • (cs) in reply to brazzy

    brazzy:
    Quinnum:


    Well, it works in theory, except that the JVMs are broken.



    Nope, it's the theory that's broken because it tries to out-smart the JIT compiler in the very sensitive area of multi-thread synchronization, and doesn't take into account out-of-order execution.

    But the real joke is that the most simple and short implementation - initializing the Singleton in the static field declaration - has exactly the intended benefit (lazy initialization, no synchronization), without any drawbacks.

    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.

  • (cs) in reply to masklinn
    masklinn:
    dubwai:

    masklinn:
    Uh, the ability to define accessors is a Good Thing.

    Java provides a perfectly usable way to define accesors.  You create a method.  What's the problem, you don't like typing '()'?

    1. You reveal the innards of your objects (if you're calling a method it's an accessor, otherwise it's a member)
    2. You can't change your mind and hide a member by accessors if you need to without breaking everything

    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.

    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.

    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.

    Getters and setters should be the exception, not the rule.

    And I fully agree with this.

    Therefore, I find a language feature that supports them to be of little value.

    Try a language with an implementation of accessors actually worth using before saying that please.

    Explain to me how accessors are better than methods.

  • (cs) in reply to OneFactor
    OneFactor:

    brazzy:
    Quinnum:


    But the real joke is that the most simple and short implementation - initializing the Singleton in the static field declaration - has exactly the intended benefit (lazy initialization, no synchronization), without any drawbacks.

    Well, you don't get lazy initialization.

    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.

  • (cs) in reply to BogusDude

    Anonymous:
    Anonymous:
    Finally, they do provide a second example using double-checked locking to provide a lazy synchronized init, but double-checked locking doesn't work:
    Wrong. Double Checked locking doesn't work IN JAVA !!! It works perfectly well in C++.

     

    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.

     

     

  • konijn (unregistered) in reply to Chris F
    [image] Kinko wrote:

    I suggest you get a real job at a proper company and you will see that majority server side code is written in Java, and would never be written on C# for the obvious reasons i.e. stability, security , scalability, portability


    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.

  • (cs) in reply to dubwai
    dubwai:

    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.

    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.

    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.

    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.

    Explain to me how accessors are better than methods.

    • They allow you to change your mind while sticking to the simplest path. You can expose members as public when you have no reason to make them private. It doesn't matter because you can hide them if required later. Without breaking anything. With methods, you can't change your mind, or you'll have to break your API/interface
    • They're much more natural to use, want to change the value of a member? object.member = value. Want to retrieve it? value = object.member. A member, real or virtual, is data. It should be treated as such.
    • They tidy the code, less parentheses, less repetitive keyword (get, set)
  • (cs) in reply to dubwai
    dubwai:

    Explain to me how accessors are better than methods.



    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?

  • (cs) in reply to masklinn
    masklinn:
    dubwai:

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    Explain to me how accessors are better than methods.

    • They allow you to change your mind while sticking to the simplest path. You can expose members as public when you have no reason to make them private. It doesn't matter because you can hide them if required later. Without breaking anything. With methods, you can't change your mind, or you'll have to break your API/interface

    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.

    • They're much more natural to use, want to change the value of a member? object.member = value. Want to retrieve it? value = object.member. A member, real or virtual, is data. It should be treated as such.

    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.

    • They tidy the code, less parentheses, less repetitive keyword (get, set)

    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.

  • (cs) in reply to kleinux
    kleinux:
    dubwai:

    Explain to me how accessors are better than methods.



    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;

    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 :/

  • (cs) in reply to kleinux
    kleinux:
    dubwai:

    Explain to me how accessors are better than methods.



    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?

    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.

Leave a comment on “The Simpleton Design Pattern”

Log In or post as a guest

Replying to comment #:

« Return to Article