Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2006

Tip: Looking for answers? Try searching our database.

should getInstance() be idempotent?

Thread view: 
jlowery05 - 10 Mar 2006 19:34 GMT
Seems it should be, at least if there's state involved.  What about
pooled Singletons, though? In that case I wouldn't necessarily expect
the same object to come back with every call.

Seeking opinions...
Oliver Wong - 10 Mar 2006 19:56 GMT
> Seems it should be, at least if there's state involved.  What about
> pooled Singletons, though? In that case I wouldn't necessarily expect
> the same object to come back with every call.
>
> Seeking opinions...

   Question is vague:

   If a method returns different (by reference), immutable and equal
objects, do you consider it to be idempotent?

   e.g.

public List getEmptyList() {
 return new ArrayList();
}

   - Oliver
jlowery05 - 10 Mar 2006 20:48 GMT
Equivalent instances may be sufficient if mutators on one instance
affect similar changes across all Singleton occurrences.

I think in practice, though, that would be difficult. You'd have to
implement some sort of ACID framework (like in a database) to ensure
that two processes aren't mutating the same object members
concurrently, otherwise you're never going to ensure equivalency on
subsequent calls.
Oliver Wong - 10 Mar 2006 21:32 GMT
> Equivalent instances may be sufficient if mutators on one instance
> affect similar changes across all Singleton occurrences.
[quoted text clipped - 4 lines]
> concurrently, otherwise you're never going to ensure equivalency on
> subsequent calls.

   "affect similar changes across all occurrences" would probably be
undesirable in the example of

public List getEmptyList() {
 return new ArrayList();
}

   because you might call a method called "getEmptyList", and then find
that it is not empty! (if another thread modified the a different instance,
but that modification is reflected across all instances of the list).

   However, I'd argue that getEmptyList() is indeed idempotent if you take
the definition of "always does the same thing, no matter how many times you
call it".

   - Oliver
Raymond DeCampo - 11 Mar 2006 02:07 GMT
>> Equivalent instances may be sufficient if mutators on one instance
>> affect similar changes across all Singleton occurrences.
[quoted text clipped - 20 lines]
> take the definition of "always does the same thing, no matter how many
> times you call it".

But that is not the definition of idempotent.  An idempotent
transformation I is one such that I^2 = I.  Applied to a method, that
would mean that the second call has no effect, not that it does the same
thing as the first call.  A method such as Arrays.sort() is idempotent.

Almost all (reasonable) methods will satisfy the definition the way you
have written it.  E.g., a method to square a value "always does the same
thing" but is not idempotent.

I've not sure that the term idempotent applies to a method that does not
accept arguments or modify internal state.  For the above getEmptyList()
method, the heap is modified in a different way for each invocation;
that may be nitpicking however.

Ray

Signature

This signature intentionally left blank.

jlowery05 - 11 Mar 2006 21:51 GMT
Idempotent, indempotent: Refers to an operation that produces the same
results no matter how many times it is performed.

Borrowed definitions in computer science tend to be looser than the
original.  Basically what I was asking was if getInstance() should
return the same object on every call. Call it what you will.
Roedy Green - 11 Mar 2006 22:32 GMT
>Idempotent, indempotent: Refers to an operation that produces the same
>results no matter how many times it is performed.

see http://mindprod.com/jgloss/idempotent.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

neuneudr@yahoo.fr - 10 Mar 2006 22:46 GMT
> I think in practice, though, that would be difficult. You'd have to
> implement some sort of ACID framework (like in a database) to ensure
> that two processes aren't mutating the same object members
> concurrently, otherwise you're never going to ensure equivalency on
> subsequent calls.

"...to ensure that two processes aren't mutating the same object
members concurrently, ..."

Like two threads ? Couldn't that problem simply be solved by
correctly using the synchronization mechanisms provided by
Java ?   (not that it would solve other problems, like the "EmpyList"
example that Oliver Wong gave).
jlowery05 - 11 Mar 2006 01:23 GMT
Synchronization on a single instance, sure. But were talking about
multiple objects, not a sing one.

Yeah, it's called a singleton, but it is possible to write a singleton
that creates more than one instance of itself... but now I'm thinking
that's more appropriately called a singleton factory.

So now I've convinced myself that getInstance() should always return
the identical object no matter how many times it's called (making it
idempotent), and if you want to manage multiple singletons, use a
singleton factory.
neuneudr@yahoo.fr - 10 Mar 2006 22:43 GMT
Hi,

want more infos, want more infos :)

What are "pooled Singletons" ?  1 Match on Google :(

If you put an 's' to singleton, is it still a singleton?

"pooled singleton" gives 100 matches, but it's always
with a comma between "pooled" and "singleton" :(

I'm honestly asking, I'm kind of confused by the terminology.
jlowery05 - 11 Mar 2006 01:43 GMT
One of the benefits of using a singleton instead of a class with static
members is that it's possible to instantiate more than one singleton
(in theory).

A case where you might do this is where you have mulitple singletons
running in different contexts. for example, I can subclass a singleton
to add properties related to the context I'm running in. For one
context, getInstance() returns a base class, for the other a derive
(separate) instance. They're both singletons in that only one of each
type is created and each has its own instance data.

A more unusual case is where you have a singleton that's being hit on
by many threads at once and want to  to instantiate more than one to
delegate the load. I've never done this, but it seems conceptually
similar to what is done with distributed EJB instances.

As in the case of EJB, there's overhead involved in keeping distributed
'singletons' in sync.  At that point I'm not sure 'singleton' is an
appropriate term.

-----

The reason for bringing up this topic was that I came across some code
where a class' getInstance() method was returning a static instance
variable that was set in its constructor... bad code, IMO, but it got
me thinking if one should expect getInstance() to return the same
object everytime.

So my thought now is "yes, it should", and if you want to do something
schmancy with multiple singleton instances, then you should be using a
factory to dole them out and manage them.
Oliver Wong - 13 Mar 2006 16:11 GMT
> The reason for bringing up this topic was that I came across some code
> where a class' getInstance() method was returning a static instance
[quoted text clipped - 5 lines]
> schmancy with multiple singleton instances, then you should be using a
> factory to dole them out and manage them.

   If the method has documentation, then you should read the documentation
as to whether it is intended to return the same object every time, intended
to return a different object every time, or doesn't define whether the
objected returned is the same one or a different one.

   If there is no documentation, then with a name like "getInstance", I
wouldn't automatically assume it returns the same instance every time; I'd
treat it as "undefined."

   If it were called "getNewInstance" (and had no documentation), then I'd
assume it returns a different object every time.

   If it were called "getSingletonInstance" or "getSoleInstance" (and had
no documentation), then I'd assume it returns the same object every time.

   - Oliver
Kent Paul Dolan - 13 Mar 2006 17:30 GMT
> So my thought now is "yes, it should", and if you
> want to do something schmancy with multiple
> singleton instances, then you should be using a
> factory to dole them out and manage them.

For an instance I encounter where you might want to
do exactly that:

I run a Java version, from Sean Luke, of the
Mersenne Twister pseudo-random number generator
(PNG).

Normally I run it as a singleton, with synchronized
access from the dozens of places and several threads
where my application wants random numbers, to save
memory footprint; the Twister keeps a fairly huge
amount of state, and I cannot afford to have dozens
of instances' state cluttering RAM.

However, it is well known in the cryptography
community that in a sufficiently high-dimensional
space, the output of a congruential generator PNG
forms a very regular lattice in that space.

So, if I have two groups of places I need PNG
output, but I don't want to take the risk of them
being mutually correlated in lockstep, I'd want to
create _two_ singleton Twister instances,
initialized them by separate mechanisms, and use
them to parcel out independent streams of PNG
output. The two groups would be uncorrelated,
because how many calls to the Twister each makes is
data dependent, in two disparate data streams.

Each group of clients would then gain references to
its associated Twister instance, and the lockstep
would be broken.

FWIW

xanthian.
Tony Morris - 11 Mar 2006 01:43 GMT
> Seems it should be, at least if there's state involved.  What about
> pooled Singletons, though? In that case I wouldn't necessarily expect
> the same object to come back with every call.
>
> Seeking opinions...

Better, should getInstance() exist?
Answer: no, the singleton antipattern should be avoided always since
there is always a more appropriate alternative that aligns with formal
notation of requirement specification (the limitations of Java itself
withstanding).

A singleton is only ever used for one of two things:
1) A global point of access for two unrelated components to be capable
of sharing data (spot the contradiction in this statement).
2) Someone is too lazy to provide the appropriate declaration of
abstraction to whatever contract would otherwise use a singleton (this
one is pretty obvious).

Books have agendas other than to portray truth - for example, to make
money for the author/publisher. They are not divine truth, not even GoF.

Signature

Tony Morris
http://tmorris.net/

Tony Morris - 11 Mar 2006 01:44 GMT
> Seems it should be, at least if there's state involved.  What about
> pooled Singletons, though? In that case I wouldn't necessarily expect
> the same object to come back with every call.
>
> Seeking opinions...

Better, should getInstance() exist?
Answer: no, the singleton antipattern should be avoided always since
there is always a more appropriate alternative that aligns with formal
notation of requirement specification (the limitations of Java itself
withstanding).

A singleton is only ever used for one of two things:
1) A global point of access for two unrelated components to be capable
of sharing data (spot the contradiction in this statement).
2) Someone is too lazy to provide the appropriate declaration of
abstraction to whatever contract would otherwise use a singleton (this
one is pretty obvious).

Books have agendas other than to portray truth - for example, to make
money for the author/publisher. They are not divine truth, not even GoF.

Signature

Tony Morris
http://tmorris.net/

Andrew McDonagh - 11 Mar 2006 10:48 GMT
>> Seems it should be, at least if there's state involved.  What about
>> pooled Singletons, though? In that case I wouldn't necessarily expect
[quoted text clipped - 7 lines]
> notation of requirement specification (the limitations of Java itself
> withstanding).

+1
Patrick May - 11 Mar 2006 12:40 GMT
> Better, should getInstance() exist?
> Answer: no, the singleton antipattern should be avoided always since
> there is always a more appropriate alternative that aligns with
> formal notation of requirement specification (the limitations of
> Java itself withstanding).

    I agree, but would add that another problem with the
getInstance() method is that it exposes too much about the
implementation of the class.  Clients of the class shouldn't care if
there is exactly one instance, one instance per thread, multiple
instances, or a clerk named Edna behind the scenes.  If there should
only be one instance of the implementation of a class, the class
should handle that (with, for example, the MonoState pattern) without
exposing the details to the outside world.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Alex Hunsley - 11 Mar 2006 19:54 GMT
>> Better, should getInstance() exist?
>> Answer: no, the singleton antipattern should be avoided always since
[quoted text clipped - 10 lines]
> should handle that (with, for example, the MonoState pattern) without
> exposing the details to the outside world.

Suppose you're using Flyweight. What do you suggest then? MonoState
isn't great for everything.
Andrew McDonagh - 11 Mar 2006 20:02 GMT
>>> Better, should getInstance() exist?
>>> Answer: no, the singleton antipattern should be avoided always since
[quoted text clipped - 12 lines]
> Suppose you're using Flyweight. What do you suggest then? MonoState
> isn't great for everything.

Flyweight is completely different to singleton/monostate
Alex Hunsley - 12 Mar 2006 02:23 GMT
>>>> Better, should getInstance() exist?
>>>> Answer: no, the singleton antipattern should be avoided always since
[quoted text clipped - 14 lines]
>
> Flyweight is completely different to singleton/monostate

I know. What I am pointing out is that when you use a pattern like
flyweight, you are using it because you have finely grained classes and
want to use common instances of these classes in different object
compositions. MonoState would offer many different instances that share
state, which is still not ideal for flyweight - the idea of flyweight is
that the object(s) contain compositions share references to the same
object. Not to many different instances: even though those instances may
share state via MonoState, it's still wasteful...
Patrick May - 12 Mar 2006 11:29 GMT
> I know. What I am pointing out is that when you use a pattern like
> flyweight, you are using it because you have finely grained classes
[quoted text clipped - 5 lines]
> though those instances may share state via MonoState, it's still
> wasteful...

    Singleton is certainly one way of implementing Flyweight.  You
could also use a HashTable of Flyweight instances, or any of a number
of other mechanisms for sharing references to a single instance.

    Flyweight may be one extreme where the classic Singleton with
getInstance() is justified.  Where the number of references is not so
high, the benefits of not exposing that amount of implementation
detail outweigh the costs of a few extra objects.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Chris Smith - 13 Mar 2006 04:35 GMT
> >> If there should
> >> only be one instance of the implementation of a class, the class
[quoted text clipped - 5 lines]
>
> Flyweight is completely different to singleton/monostate

Wow!  I couldn't have asked for a more striking demonstration of the
Dark Side of patterns.  Would it have killed anyone to say, for example:

   "If there should only be one logical instance of the implementation,
    the class should handle that by sharing some OO model of the shared
    state while still giving each client its own object to hide that
    implementation detail."

   "Suppose, though, that it is important to prevent creating a copy of
    an object per client, in a large application, for performance
    reasons."

And we'd be in a much better place, without anyone assuming some intent
in some pattern name that was never really there.  Why, oh why, do
design patterns have to block the natural ability to communicate?

Step 1: Read about a design pattern.
Step 2: Understand a design pattern.
Step 3: Practice a design pattern.
Step 4: Internalize a design pattern.
Step 5: Communicate clearly without using Capitalized Name.

IME, failure in step five follows directly from a weak or incomplete
step four (or occasionally, two).  Instead of continuing to actually
design, the developer attempts to compensate by carrying around a
dictionary of patterns in his/her head, and more or less applying them
wholesale.  The result is a rather rigid entity that's unable to adapt
to the situation at hand.  This is accompanied by (and largely caused
by) an inability to even talk about the design in language that admits
to adaptation, if there's no Capitalized Name for the adaptation.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Alex Hunsley - 13 Mar 2006 21:58 GMT
>>>> If there should
>>>> only be one instance of the implementation of a class, the class
[quoted text clipped - 6 lines]
> Wow!  I couldn't have asked for a more striking demonstration of the
> Dark Side of patterns.  

Why bother with the word "demonstration"? Wouldn't the words "act of
showing or making evident" have done just as well? :)

>Would it have killed anyone to say, for example:
>
[quoted text clipped - 6 lines]
>      an object per client, in a large application, for performance
>      reasons."

No, it wouldn't have hurt. It's a trade-off - if someone knows the
principle already, by a certain name, it can be simpler to be terse, if
you believe they are going to know what you mean.
Someone else was talking about MonoState, so I presumed they'd
understand the 'Flyweight' reference, and I think they did. It's my
fault that I wasn't clear enough about why MonoState would reduce the
effectiveness of Flyweight. This doesn't automatically mean referring to
design patterns is evil, though.

> And we'd be in a much better place, without anyone assuming some intent
> in some pattern name that was never really there.  Why, oh why, do
[quoted text clipped - 8 lines]
> IME, failure in step five follows directly from a weak or incomplete
> step four (or occasionally, two).  

I think you're jumping the gun a little here.

If someone else is comfortable with using a pattern name to refer to a
concept or idea, it seems a little long winded for me to not use a
pattern name, if it is appropriate, in my reply to them. Yes, I should
have been clearer in the exact aspect I was referring to, however.

Out of interest, do you ever use words with complex meanings? If yes,
then why? Isn't it easier for everyone if you just use a longer
collection of simpler words? Does you using a complex word mean that
you've failed to internalise or understand their meaning? Does this mean
that you have to think about everything you see and do in terms of the
complex words? (Hmm, we're straying into Chomsky land here, perhaps.)

> Instead of continuing to actually
> design, the developer attempts to compensate by carrying around a
[quoted text clipped - 3 lines]
> by) an inability to even talk about the design in language that admits
> to adaptation, if there's no Capitalized Name for the adaptation.

Some people certainly use design patterns as a proverbial golden hammer
and view the world through rose-tinted design glasses, yes.
Chris Smith - 14 Mar 2006 03:22 GMT
> > Wow!  I couldn't have asked for a more striking demonstration of the
> > Dark Side of patterns.  
>
> Why bother with the word "demonstration"? Wouldn't the words "act of
> showing or making evident" have done just as well? :)

Indeed, but no one misunderstood me because I said "demonstration".

The problem here is not with definitions, but rather with taking a set
of several design decisions that are demonstrated together in some book,
and using a single word to refer to all of them.  To be fair, there's
often (though not always) some degree of synergy between the various
design decisions demonstrated in a pattern.  Nevertheless, their primary
benefit is that you've now seen each of those design decisions being
made, and what implications they had, at least in a very limited
context.

> No, it wouldn't have hurt. It's a trade-off - if someone knows the
> principle already, by a certain name, it can be simpler to be terse, if
> you believe they are going to know what you mean.

And I am disputing that there is "a" principle here.  My copy of the GoF
book defines Flyweight using an inheritance tree for the flyweight class
and a separate factory class which are in no way related to the idea of
sharing objects, as well as implying some kind of hierarchical
composition which certainly isn't relevant to your point, but is
nevertheless very often associated with this pattern name in people I've
talked to.  Though I've often used shared objects, I can't recall ever
using the whole set of classes in this book.

And that's the point.  Your comment was not about Flyweight, but about
the performance cost of creating a large number of objects.  The term
"Flyweight" is, in my experience, pretty much useless in terms of real
design discussions because of all this conceptual baggage that quite
rarely comes together in exactly that way.  Flyweight is a bit extreme
in that sense, but the general idea applies to most patterns (and, when
it doesn't, the "pattern" name was generally in wide use prior to anyone
writing a patterns book anyway).

> > IME, failure in step five follows directly from a weak or incomplete
> > step four (or occasionally, two).  
>
> I think you're jumping the gun a little here.

And I figured you would probably think so.  If you didn't disagree with
me, it would have been a little silly for you to have written that prior
message.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Patrick May - 11 Mar 2006 21:13 GMT
> >      I agree, but would add that another problem with the
> > getInstance() method is that it exposes too much about the
[quoted text clipped - 8 lines]
> Suppose you're using Flyweight. What do you suggest then? MonoState
> isn't great for everything.

    What about the Flyweight pattern requires the use of a Singleton
exposing a getInstance() method?

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Alex Hunsley - 12 Mar 2006 01:48 GMT
>>>      I agree, but would add that another problem with the
>>> getInstance() method is that it exposes too much about the
[quoted text clipped - 10 lines]
>      What about the Flyweight pattern requires the use of a Singleton
> exposing a getInstance() method?

Nothing at all. But I'm interested in what your alternative method(s)
would be of ensuring re-use of existing instances that are appropriate.
You might propose a factory that returns instances (and caches
references to already created instance for possible re-use). But then
what is the essential difference between knowing that you must use
getInstance() for a singleton class and knowing that you shouldn't
create instances of an object directly, but use the factory instead?
Both require special knowledge outside of the normal constructor mechanism.
Alex Hunsley - 12 Mar 2006 04:17 GMT
>>>>      I agree, but would add that another problem with the
>>>> getInstance() method is that it exposes too much about the
[quoted text clipped - 18 lines]
> create instances of an object directly, but use the factory instead?
> Both require special knowledge outside of the normal constructor mechanism.

As a side note... implementing things as singleton can be a pain when it
comes to writing tests and can be limiting. Just a side issue I thought
worth mentioning.
Patrick May - 12 Mar 2006 11:20 GMT
> >      What about the Flyweight pattern requires the use of a
> > Singleton exposing a getInstance() method?
>
> Nothing at all. But I'm interested in what your alternative
> method(s) would be of ensuring re-use of existing instances that are
> appropriate.

    I would use a Singleton, but I wouldn't expose that design
decision to users of the class.  That means that the interface would
not expose a getInstance() method.  The implementation of the class
might look like a MonoState or it might use the envelope-letter
technique.  Clients would simply instantiate an instance of the class.

    The important point is that the code of clients of the class is
not littered with getInstance() calls -- the Singleton is used like
any other class.  This not only keeps the code cleaner, it decouples
the clients from the Singleton so that it could be changed to a
ThreadSingleton or even a non-Singleton in the future with no impact
to existing clients.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Alex Hunsley - 12 Mar 2006 23:41 GMT
>>>      What about the Flyweight pattern requires the use of a
>>> Singleton exposing a getInstance() method?
[quoted text clipped - 7 lines]
> might look like a MonoState or it might use the envelope-letter
> technique.  Clients would simply instantiate an instance of the class.

I thought you might be thinking about the inner-class idea. I've never
heard it called envelope-letter but now I know!
Just so I can be clear I'm thinking along the same lines, is this basic
example what you mean by the envelope-letter:

class Fooble {
 private static InnerFooble instance = null;

 public Fooble() {
    if (instance == null) {
    instance = new InnerFooble();
    }
 }

 // delegate all methods to inner class
 public void setX(int x) {
    instance.setX(x);
 }

 public int getX() {
    return instance.getX();
 }

 class InnerFooble {
    private int x = 0;
   
    public void setX(int x) {
     this.x = x;
    }

    public int getX() {
     return this.x;
    }
 }

 public static void main(String[] args) {
    Fooble foobleA = new Fooble();
    System.out.println("foobleA has x: "+foobleA.getX());
    foobleA.setX(5);
    System.out.println("foobleA has x: "+foobleA.getX());
    Fooble foobleB = new Fooble();
    System.out.println("foobleB has x: "+foobleB.getX());
    foobleB.setX(10);
    System.out.println("foobleA has x: "+foobleA.getX());
 }
}

>      The important point is that the code of clients of the class is
> not littered with getInstance() calls -- the Singleton is used like
> any other class.  This not only keeps the code cleaner, it decouples
> the clients from the Singleton so that it could be changed to a
> ThreadSingleton or even a non-Singleton in the future with no impact
> to existing clients.

I can see the advantages, certainly.
alex
Patrick May - 13 Mar 2006 07:54 GMT
> >      I would use a Singleton, but I wouldn't expose that design
> > decision to users of the class.  That means that the interface
[quoted text clipped - 5 lines]
> I thought you might be thinking about the inner-class idea. I've
> never heard it called envelope-letter but now I know!

    It seems that my C++ background is showing.

> Just so I can be clear I'm thinking along the same lines, is this
> basic example what you mean by the envelope-letter:
[ good example elided -- pjm ]

    That's a good way of using inner classes to accomplish the goal.
If the implementation can be used separately from the Singleton in
other contexts (not as common a situation), the same thing can be done
without the inner class.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Ed - 11 Mar 2006 21:13 GMT
>    If there should
> only be one instance of the implementation of a class, the class
> should handle that (with, for example, the MonoState pattern) without
> exposing the details to the outside world.

Thanks, Patrick, for that reference to the MonoState pattern; I have't
seen that pattern before.

I liked the quote in some article I've just read about it, "I find this
to be a delightfully twisted pattern. No matter how many instances of
MonoState you create, they all behave as though they were a single
object."

Interesting ...

.ed

--
www.EdmundKirwan.com - Home of The Fractal Class Composition
Thomas Hawtin - 12 Mar 2006 00:19 GMT
> I liked the quote in some article I've just read about it, "I find this
> to be a delightfully twisted pattern. No matter how many instances of
> MonoState you create, they all behave as though they were a single
> object."
>
> Interesting ...

I can think of different words to describe it. "Pointless", perhaps. Or
"perverse".

Prefer static creation methods over naked constructors. To use a
constructor where you don't actually mean it... lost for words.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Alex Hunsley - 12 Mar 2006 02:06 GMT
>> I liked the quote in some article I've just read about it, "I find this
>> to be a delightfully twisted pattern. No matter how many instances of
[quoted text clipped - 8 lines]
> Prefer static creation methods over naked constructors. To use a
> constructor where you don't actually mean it... lost for words.

I'm completely with you on this one. Being able to use a normal
constructor to construct an object that has only static members seems,
well, just silly.
I don't think the pattern name MonoState is very well chosen either - it
sounds like it means "one state", when in fact a MonoState object can
have any amount of states - but only one instance (of data), in effect.
I think the name "Singleton" is less misleading.
Chris Smith - 13 Mar 2006 05:48 GMT
> I'm completely with you on this one. Being able to use a normal
> constructor to construct an object that has only static members seems,
> well, just silly.

Indeed.  Given the choice, I'd say that hiding whether a class is a
singleton or not should be done by always building it with static
methods.  They are certainly the more general-purpose mechanism.  In the
end, though, the issues probably aren't universal enough to have a right
answer.

> I don't think the pattern name MonoState is very well chosen either - it
> sounds like it means "one state", when in fact a MonoState object can
> have any amount of states

Eh?  In the sense in which OO design uses the term, no object has
multiple states... an object has state, which is sometimes used as a
singluar noun, and sometimes as a mass noun.  Perhaps you mean multiple
fields?  Together, those fields would constitute the object's state.  
Multiple states might be discussed if you are examining how the object
changes through the lifetime of the application.

By MonoState is presumably meant that many instances share only one
state, which would be correct.  Nevertheless, I am generally in
agreement that any design pattern name is silly when used as MonoState
has been used in this thread.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Alex Hunsley - 12 Mar 2006 01:53 GMT
>>    If there should
>> only be one instance of the implementation of a class, the class
[quoted text clipped - 10 lines]
>
> Interesting ...

I still don't see the attraction of MonoState. It seems purposefully
wasteful - potentially loads of instances, all behaving the same, the
same state. Why bother? So you can just always call a normal constructor
and not have to worry about calling getInstance or a factory method
somewhere else? It's a trade-off, certainly.
jlowery05 - 12 Mar 2006 05:09 GMT
I'm with you.. getInstance() might be 'funny' but it's not odd enough
to matter to most folks.  Tempest in a teapot.

I'm not sure how much memory each instance of a monostate with all
static members would use, but certainly very small. But addionally, the
GC has got to track and clean all those (temporary) instances, where as
a Singleton has only one.
Patrick May - 12 Mar 2006 11:25 GMT
> I still don't see the attraction of MonoState. It seems purposefully
> wasteful - potentially loads of instances, all behaving the same,
> the same state.

    The way I've typically used it, there is only one static member
variable, just as in the Singleton pattern.  The number of
simultaneous instances isn't usually high and the overhead compared to
an object reference to a Singleton isn't necessarily huge.

> Why bother? So you can just always call a normal constructor and not
> have to worry about calling getInstance or a factory method
> somewhere else? It's a trade-off, certainly.

    The big benefit is that it doesn't expose your implementation
decisions unnecessarily.  That makes future change easier and less
intrusive.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Chris Uppal - 12 Mar 2006 12:17 GMT
> I liked the quote in some article I've just read about it, "I find this
> to be a delightfully twisted pattern. No matter how many instances of
> MonoState you create, they all behave as though they were a single
> object."

A curious question relating to a recent thread: should a MonoState
instance be considered to be immutable ?

   -- chris
Oliver Wong - 13 Mar 2006 16:36 GMT
>> I liked the quote in some article I've just read about it, "I find this
>> to be a delightfully twisted pattern. No matter how many instances of
[quoted text clipped - 3 lines]
> A curious question relating to a recent thread: should a MonoState
> instance be considered to be immutable ?

   I think the whole point of MonoState was for it to be NOT immutable.
That is, somewhere, you modify the state of a MonoState, and every else, all
other instances of the same MonoState class are instantly, magically
updated.

   - Oliver
Chris Uppal - 14 Mar 2006 11:15 GMT
[me:]
> > A curious question relating to a recent thread: should a MonoState
> > instance be considered to be immutable ?
[quoted text clipped - 3 lines]
> all other instances of the same MonoState class are instantly, magically
> updated.

The point I was hinting at was that it depends on how you see "mutability".  In
one very definite, if rather literal-minded, sense the instances are clearly
immutable.  They don't have any local state, so they cannot have any local
state that changes.  OTOH, they certainly behave as if they change, so they
behave as if they have state (somewhere).  IIRC you recently distinguished
between internal and external mutability -- these things are internally
immutable, externally mutable.  In my terms the /location/ of the state is
unimportant, they behave as if they are mutable, so they are.

(Which is why I have doubts about the mutable/immutable distinction when
applied to OO.  It's fine and dandy for informal discourse, but if it were
added to the language as a keyword, then there would be considerable potential
for confusion and/or misuse.)

Which makes these things rather strange from an OO perspective.  If we take the
objects' behaviour as the most (or only) important knowledge we have about
them, then the fact that they all behave in the same way (in lockstep) is
extremely unusual.  Not wrong, but also not something that is "just an
implementation detail".  So the design is exposing itself just as clearly as it
did if we used an explicit Singleton.

   -- chris
Oliver Wong - 14 Mar 2006 16:04 GMT
> [me:]
>> > A curious question relating to a recent thread: should a MonoState
[quoted text clipped - 11 lines]
> immutable.  They don't have any local state, so they cannot have any local
> state that changes.

   Ah, I see your point now. The implementation for MonoState I saw was to
just declare every field in the object as static. So my brain registered the
following facts: {"object has fields", "no 'final' keyword in sight"} and
came to conclusion: {"object is imutable"}. But now that you've reminded me
that the state is "somewhere else", I can see the case being made for
considering the object to be immutable.

> OTOH, they certainly behave as if they change, so they
> behave as if they have state (somewhere).  IIRC you recently distinguished
> between internal and external mutability -- these things are internally
> immutable, externally mutable.  In my terms the /location/ of the state is
> unimportant, they behave as if they are mutable, so they are.

   I'm in agreement with you. I didn't use the terms "internally mutable"
and "externally" mutable though (not sure what those terms would mean);
rather I was spoke of "immutable from the compiler's perspective" and
"immutable from the (client) programmer's perspective". I suggested, like
you it seems, that the (client) programmer's perspective is more important.

> (Which is why I have doubts about the mutable/immutable distinction when
> applied to OO.  It's fine and dandy for informal discourse, but if it were
> added to the language as a keyword, then there would be considerable
> potential
> for confusion and/or misuse.)

   I have a "favorite" definition of "immutable", but I know that not
everyone uses this definition, so I often don't assume that the person I'm
speaking to shares this definition. It says that an immutable object is an
object for which there does not exist a sequence of method calls which would
change the apparent state of the object.

> Which makes these things rather strange from an OO perspective.  If we
> take the
[quoted text clipped - 4 lines]
> as it
> did if we used an explicit Singleton.

   I think to say that an object is a "Singleton" is also a description of
its behaviour (or at least, it says something about the behaviour of its
constructors and factory methods). And the JavaDocs should document the
behaviour of the objects. So as long as the author clearly writes that the
object is a "singleton" or is a "monostate", I'm personally fine with it.

   If there is no documentation, I figure singleton would be easier to
"detect", as it tends to have an obvious signature (all constructors are
private), whereas monostate doesn't seem to have such an obvious signature
(a bunch of static fields, might lead to a lot of false positives if that's
the criterion used to detect monostates).

   - Oliver
Chris Uppal - 15 Mar 2006 11:03 GMT
> > OTOH, they certainly behave as if they change, so they
> > behave as if they have state (somewhere).  IIRC you recently
[quoted text clipped - 9 lines]
> you it seems, that the (client) programmer's perspective is more
> important.

I'd misremembered.  Pity really since I rather liked the terms ;-)

By internal mutability (or immutability) I meant that the observer is looking
at it from the point of view of the object itself -- i.e. focussing on what's
inside it, it's own fields.  External (im)mutability is how it looks from
outside the object -- the POV of every other object and every programmer except
someone writing the code for that class.

>     I have a "favorite" definition of "immutable", but I know that not
> everyone uses this definition, so I often don't assume that the person I'm
> speaking to shares this definition. It says that an immutable object is an
> object for which there does not exist a sequence of method calls which
> would change the apparent state of the object.

From outside the object (which, IMO, is the only POV that should matter to any
programmer, not just to "client" programmers), state (and hence mutability) is
not really a property of an object, but of a /system/ of objects.  Individual
object's behaviour will typically change in response to the events "seen" by
the system, but you have no reason to know or care exactly /which/ object holds
onto which parts of the state.  You do care and should care what effects
sending, say, close() to a stream object will have on its subsequent behaviour,
but you have no reason to care where (or even whether) there's a
   boolean isClosed;
flag.  Maybe "openness" is implemented as a list of currently open instances
held in a class field.

   -- chris
jlowery05 - 11 Mar 2006 22:01 GMT
Let's see if I got this right:

Monostate -- multiple instances, mostly shared data (can have
instance-specific data)

Singleton -- single instance, shared data (no instance specific data)

I would agree Monostate is generally preferrable (and I'll start using
it), but in cases where you have many members with default values,
statics just don't give you control over when initialization occurs.  I
may not want to initialize a slew of object members if I never use them
in a particular execution path; it could be that Monostate statics
would get initialized by the JVM even if a logic path never
instantiated one.

I think JVMs may be smarter about when to initialize statics nowadays,
so perhaps the point is moot.
Patrick May - 11 Mar 2006 22:17 GMT
    My main point is that even when Singleton is the best choice,
exposing that decision by requiring the use of getInstance() is not
good design.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Andrew McDonagh - 11 Mar 2006 23:25 GMT
> Let's see if I got this right:
>
> Monostate -- multiple instances, mostly shared data (can have
> instance-specific data)

no...Monostate -- Multiple Instances, Shared data.

MonoState objects don't have instance data - only class data.

They are singletons...just in a different form ...  you have to create
an instance of the class in order, but its internal state is always the
same as every other instance of that class.

public class MonoState {

  private static String name;

  public void setName(String newName){
    name = newName;
  }

  public String getName() {
    return name;
  }
}

(note no constructor to initialise the name - this is preferable as it
helps show that just creating on need not also change the state of the
singleton.)

> Singleton -- single instance, shared data (no instance specific data)
>
> I would agree Monostate is generally preferrable (and I'll start using
> it), but in cases where you have many members with default values,
> statics just don't give you control over when initialization occurs.  

As above, don't provide a constructor to initialise the class vars.

> I
> may not want to initialize a slew of object members if I never use them
> in a particular execution path; it could be that Monostate statics
> would get initialized by the JVM even if a logic path never
> instantiated one.

They can be initialised to 'null' then initialised later.

> I think JVMs may be smarter about when to initialize statics nowadays,
> so perhaps the point is moot.
jlowery05 - 12 Mar 2006 05:03 GMT
see last comment on:
http://codebetter.com/blogs/darrell.norton/archive/2004/02/05/6644.aspx
Oliver Wong - 13 Mar 2006 16:38 GMT
> see last comment on:
> http://codebetter.com/blogs/darrell.norton/archive/2004/02/05/6644.aspx

   So in other words, "MonoState" is just a fancy way of saying "sometimes
declaring fields to be static is useful"?

   Actually, that's about par for most design patterns. ;)

   - Oliver
Tony Morris - 12 Mar 2006 06:08 GMT
> Let's see if I got this right:
>
[quoted text clipped - 13 lines]
> I think JVMs may be smarter about when to initialize statics nowadays,
> so perhaps the point is moot.

That's what the marketing literature will tell you, but not our best
known definition of reality. Unless you can refute the many
astrophysicists before you, a singleton has never been observed to exist
- not ever - certainly not within a universe that is not known (or
otherwise) to be finite.

A singleton may exist within a context - for example, a singleton across
an object (a field), a singleton across a class loader (a static field),
a singleton across a VM, or a singleton across many VMs. Most often, I
see a singleton across a class loader, with some contrived attempt to
abstract with a method (in this example, the method is getInstance()).
To attempt to define "A Singleton" requires the bounds of that singleton
to be specified, which then goes on to suggest that it is not a
singleton after all. You have a very clear, distinct and direct
contradiction in your definition. That is, I could call a for loop index
a singleton under the very same definition that the aforementioned
marketing literature provides (and obscures ala marketing) and remain
legitimate. Isn't it wonderful how easily a mass can be so easily
misdirected by flashing lights?

To suggest that you have a "singleton" without defining the context,
assumes "a singleton across the entire universe", which is an extremely
bold claim, and certainly not something you (I am not addressing a
divine force here) or I have ever encountered.

The moral of the story is, Think For Yourself.

Signature

Tony Morris
http://tmorris.net/

John C. Bollinger - 12 Mar 2006 05:50 GMT
>      I agree, but would add that another problem with the
> getInstance() method is that it exposes too much about the
> implementation of the class.  Clients of the class shouldn't care if
> there is exactly one instance, one instance per thread, multiple
> instances, or a clerk named Edna behind the scenes.

Oooh!  I vote for Edna!

Signature

John Bollinger
jobollin@indiana.edu

Patrick May - 12 Mar 2006 11:30 GMT
> >      I agree, but would add that another problem with the
> > getInstance() method is that it exposes too much about the
[quoted text clipped - 3 lines]
>
> Oooh!  I vote for Edna!

    Never underestimate the capabilities of a system with Edna
sitting at the other end of a telnet session.

Regards,

Patrick

------------------------------------------------------------------------
S P Engineering, Inc.    | The experts in large scale distributed OO
                        | systems design and implementation.
         pjm@spe.com    | (C++, Java, Common Lisp, Jini, CORBA, UML)
Hendrik Maryns - 13 Mar 2006 11:42 GMT
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message

jlowery05 schreef:
> Seems it should be, at least if there's state involved.  What about
> pooled Singletons, though? In that case I wouldn't necessarily expect
> the same object to come back with every call.
>
> Seeking opinions...

How about getInstance(Symbol, List), which returns the unique instance
which contains that particular symbol and that particular list of whatever?

H.
Signature

Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org

jlowery05 - 13 Mar 2006 18:32 GMT
If you're going to store an instance id, you might as well store the
instance itself.
I suppose there could be an case where the instance is large and you
don't want to hold a direct reference to it for GC purposes, but why
not use WeakReference then?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.