wood burning stoves 2.0*
The moose likes Java in General and the fly likes Looking for Object Oriented Solution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Looking for Object Oriented Solution" Watch "Looking for Object Oriented Solution" New topic
Author

Looking for Object Oriented Solution

Ahmed Basheer
Ranch Hand

Joined: Apr 15, 2004
Posts: 77
I have a problem. A singleton class implements interface having
bunch of methods declared in it. Singleton class also has init(int i) method
which does initialisation and only after successfull initialisation should
it give access to world, of the methods that it implements.

I can have a boolean flag in init(int) method which sets this flag true or false and then have all methods check the boolean flag before methods do their processing. I am sure there has to be better way , object oriented and modular way of fixing this issue. Do you guys have any helpful suggestions.

My questions is that how can Singleton class give limited access to world if the initialisation has not been done yet and full accees to the methods if the initialisation has occured, without using boolean flag in the every method in singleton. The singleton is huge library and has
houndreds of methods.

I appreciate.
Basheer

[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ]
[ July 16, 2004: Message edited by: Dirk Schreckmann ]
Ray Stojonic
Ranch Hand

Joined: Aug 08, 2003
Posts: 326
If you call init() (or check to see if it is init'd) in the constructor, can't you assume it's initialized? or am I missing something?
Ahmed Basheer
Ranch Hand

Joined: Apr 15, 2004
Posts: 77
I can't call init from constructor. Init has a parameters which are used for initialisation and configuration of the module. Here is the sequence

1. User first calls getInstance() and gets an instance
2. Using instance, calls init to initialise and configure the library
3.At this point configuration is complete and module is ready to be used

i,e all API served by this singleton instance can be called.

Hope I am able to explain to you this time.

Basheer
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I have the strong feeling that this shouldn't be a Singleton. Can you please explain why it is?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ahmed Basheer
Ranch Hand

Joined: Apr 15, 2004
Posts: 77
It has be to singleton in my case. Basicallly It is a dictionary having APIs.The example I gave was made simple for the sake of understanding problem. The init methods accepts two things, xml file to be parsed and logger instance for logging. With these two parameters it parses and creates java objects. the APIs in the singleton class should access those java objects and return result to the caller. As a matter of fact after init finishes its job , it sets the initialisation flag(static) to true and checks it at the begining of this mathod to make sure that initialisation doesn't occurs twice.
I can check same flag in every API of the singleton method , but I am looking for more portable solution. e.g What will happen if the future person adds API to singleton method without checking the flag.

Having said that may be checking flag in every method is the simplest way, but I love to learn new and agressive techniques/patterns in java.

Regards,
Basheer
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Let's get cute ... and hope we don't get thrown out of the intermediate forum

Now a client can try this:

Advantage: No "if initialzed()" tests anywhere. SingleThing is shorter, simpler, can't forget to put the test on one method, impress the boss, go home early!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
A J Beal
Greenhorn

Joined: Jul 17, 2004
Posts: 2
Let me see if I understand your problem:
You've got a singleton class that has:
1)some methods that need to be callable regardless of whether init() has been called, and
2)some methods that should be called only AFTER init() has been called
3)An init() method that accepts an XML parser and a logger, that subsequently creates objects and activates all methods of type 2.
4)A reason why you can't include the init code into the constructor call (e.g. the type 1 methods must be available to be called well before you have enough information to call the init method.)

What if you went a superclass/subclass route? That is, all methods that do not require init() live in the superclass, and init becomes a new static constructor method that in addition to whatever processing it already does, replaces the current singleton instance with an instance of the instantiated subclass? Then you simply move all methods that are dependant on init being called into the subclass, ensuring they aren't called inappropriately. Your other constructor instead of checking for a null pointer would check for an instance of the subclass, ensuring that if you called init twice, the subclass wouldn't be replaced.

Just some thoughts, hope they help.

Aron Beal
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Stan's solution is *exactly* what I first thought of when seeing your post - basically a combination of the State pattern and Null Object pattern.

I still think that it smells, though - I don't like objects that aren't usable directly after their instantiation.

So, if you'd care to explain why your class "needs" to be a Singleton, we *might* find an alternative, less smelly solution...
Wirianto Djunaidi
Ranch Hand

Joined: Mar 20, 2001
Posts: 210

So do you meant that you can only have a Singleton object for each configuration of the init variables, or there can only one init every happen which result in a ready to be used Singleton object.

Can it be solved using Factory Method pattern which will do the init for you?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Thinking later I believe what I suggested fails in that if somebody gets an object that hasn't been initialized it won't get any better for waiting ... its state won't change to initialized some time in the future. This might be ok if anybody who tried a method and got an exception called getInstance() again to retry, but if the object had been passed around a few times it might be hard to try the whole chain again. A more pure state solution might be better.

Say class ThePublicSingleton implements SingletonInterface but all methods pass through to a private InitializedSingleton or UninitializedSingleton which also implement SingletonInterface. Since we're passing all method calls through, we could even make ThePublicSingleton have all static methods and not worry about all the factory stuff.

I solidly agree with Ilja that having an uninitialized state is troublesome. It's apparently awkward because it spawned this whole conversation, and it invites subtle (hard to find) timing problems. I took it as a requirement, but in real life I'd push back on the requirement ... that just happens to be part of my job description right now
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Stan James:
that just happens to be part of my job description right now


Mine too - at least of my own description of what constitutes a professional software developer...
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
I'm not getting why you can't use the constructor. There are two ways to do this, load the Singleton instance on first reference to the class and load on first call to getInstance():



The upshot is, it sounds like you want to be able to instantiate this Singleton and have it lying around without initializing it. That's not a good idea. Objects should only be constructed when they are ready to go, and if you don't have everything ready to initialize them, then wait until you do. There's no good reason to split construction of the object from initialization of the object that I can think of.

sev
Ahmed Basheer
Ranch Hand

Joined: Apr 15, 2004
Posts: 77
I hope that I am not stopping other people getting their questions answered.
A couple of things real quick.

sever oon:

This singleton class is a dictionary/library. It is initialised by a seprate module with appropriate parameters and can throw variety of exceptions if any problem happens during initialisation. Having said that you are suggesting to make getInstance() as getInstance(args). That is to do object creation and initialisation in single step. This is going to involve me in more deeper problems. geetInstance() should then take care of throwing exceptions and then I am expecting every caller to pass the args while getting singleton instance. Thanks for your answer but I have feeling that it will just not work for me. I am bound to go for two step approach.


Stan James:

Thanks for your helpful tip in the second post, I guess state pattern should be way for me to go. BTW in your first post there was also problem in calling init. With the code you have presented there was no access to the init method. Because getInstance() returned "useThisVariable" which doesn't host "init" method.

Ilja:

I had requirement, based on those requirement there were two options available to me either to have static class with static methods in it or to have singleton. I choose later. Singleton bacuase XML parsing in the init methods is only to be done once during the entire life of the object and all methods which act as API, and are based on the parsed java objects, were pretty much static in nature and hence methods of the singleton class.


I will try to act upon the advice give by Stan and Ilja of combining the state pattern with Singleton. I hope that I will list my final solution. You guys including other have been extremely helpful. I love to be part of this forum.

Thanks,
Basheer
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Heh heh, I knew I had a couple problems. I think a private constructor on the null object was bad too.

Not knowing your architecture at all ... is there any opporunity for an "application assembler" module to build the dictionary in a way that is assured to be ready by the time anybody else asks for it? For example, my current project has a concept of "custom objects" that are initialized at server startup. One of these is our assembler - it reads configuration and sets options on many other objects. Could an assembler do the parsing and build up a complex argument containing everything the dictionary needs for a constructor?

I'm fishing for ways to make some other object do the hard work.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Basheer Ahmed:
I had requirement, based on those requirement there were two options available to me either to have static class with static methods in it or to have singleton.


Could you quote the relevant part(s) of the requirements? There might actually *be* a third option...
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
That's fine, Basheer--I still don't see the problem. Objects sometimes require the help of other objects to intialize themselves, so they can call those objects from the constructor. java.util.Random, for instance, has a constructor that makes a call to the System class to get the current time so it can set its random seed value.

This gets into some deeper design issues...for example it sounds as if to make my solution work you may have to invert the dependency between your intialization object and the Singleton. But this may be a better design for you--right now, it sounds like the problem you're experiencing is due to the fact that the existing dependency goes the wrong way! You have an object that initializes this Singleton, but it has no idea when this must be done whereas the Singleton itself could just make the calls to the initializer-helper upon construction. This choice seems to be causing you a lot of problems, so you might consider reevaluating this aspect of your design to see if there are other, better reasons to keep it the way it is.

sev
[ July 20, 2004: Message edited by: sever oon ]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Ignoring for the moment the question of whether the direction of the dependency is correct, I can think of two fun ways to solve this problem.[list]Wrap your singleton in a dynamic proxy with an invocation handler that performs the initialisation check and then simply delegates to the underlying object:
  • In fact, you might recognise the code above as essentially an AOP aspect applied against the MyInterface methods, and use an AOP tool such as AspectJ to turn the check into an aspect and have it weaved into your singleton class automatically.
  • - Peter
    [ July 20, 2004: Message edited by: Peter den Haan ]
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Looking for Object Oriented Solution
     
    Similar Threads
    method unavailable
    How to call a generic method with two bounds (for a single argument) if one bound needs a cast
    Question on casting
    instantiating an interface
    What the??? Interface & Implements in regards to inheritance & polymorphisms