473,698 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton designs and exceptions

KC
Greeting all!

I have a problem that I'm hoping will be of interest to others here, and
maybe a solution will crop up. I appoligize for the message's length.

Now, I'm new to C# and .NET, so I am developing an application during my
learning phase. Because of this, I'm trying to use as many *features* as is
reasonable. Some may be more reasonable than others :) Keep that in mind.

OK, basicaly my problem is how to handle exceptions in constructors for
Singletons. Let me set it up:

I have (among others of course) a MainForm class, a Profiles class and a
ProfilesXmlFile class. The purpose of the MainForm class is obvious, the
Profiles class keeps a list of Profile class instances and the
ProfilesXmlFile class reads and writes the list of Profile instances to
an...erm..XML file. A Profile is simply a set of parameters under which the
application works. The user can only select one Profile at any time.

So, I only want/need one instance of the Profiles class, and only one
instance of the ProfilesXmlFile . I can choose many different ways to
approach this, of course, but for the sake of the learning experience I
chose Singletons. I follow MS's recommended approach:

sealed class Profiles {
private ArrayList theProfiles;
public static readonly Profiles Instance = new Profiles();
private Profiles() {
ProfilesXmlFile xmlFile = ProfilesXmlFile .Instance;
theProfiles = xmlFile.LoadPro files();
}
}

sealed class ProfilesXmlFile {
private XmlDocument doc;
public static readonly ProfilesXmlFile Instance = new ProfilesXmlFile ();
private ProfilesXmlFile () {
doc = new XmlDocument();
doc.Load("profi les.xml");
}
public ArrayList LoadProfile() {...}
}

During application initialization, I do this in MainForm:
Profiles myProfiles = Profiles.Instan ce;

Like I said before, Singletons are not necessary, but it helps me explore
the language.

The problem lies in the exception handling. "doc.Load("prof iles.xml")" in
the ProfilesXmlFile class's contructor can throw a couple of exceptions
(FileNotFoundEx ception and XmlException). I want to let the user know that
there was a problem with loading his saved profiles, but ProfilesXmlFile is
not the right place to do that (it is a helper class and should not display
dialog boxes, IMO). Therefore I want to catch the exception and rethrow it
so that Profiles handles it (or prolly even rethrow it there to let MainForm
handle it).

The behaviour is strange though. If I catch FileNotFoundExc eption and
rethrow it (or a custom exception), then I get an "Unhandled exception
FileNotFoundExc eption" raised in that same constructor! The calling class
gets a "TypeInitializa tionException" (or something like that). I tried for
hours to get some sort of notification to the calling classes that something
went wrong, but the only way to avoid getting "unhandled exception xxx" was
to catch and ignore the exception in the constructor.

How DO you handle exceptions in constructors, and especially for singletons
like the ones I descripbed?

I realize that there are a number of redesigns that will solve the problem.
For instance, I can empty the constructor and do all the work in
LoadProfiles(), which can throw the exceptions. Or I could continue to catch
and set a success/failure flag, and have the calling class do a check to see
if init was successfull. As the class is today, the constructor ignores all
exceptions, but LoadPofiles() checks the status of the doc object (!= null,
HasChildren, etc.).

Anyway, I am probably way out there in la-la land, but let's see what you
think :)
Nov 16 '05 #1
4 2376
KC <no@mail.com> wrote:

<snip>
How DO you handle exceptions in constructors, and especially for singletons
like the ones I descripbed?


What you could do is change Instance to a property like this:

sealed class Profiles
{
static Profiles instance;
static object padlock;

...Constructor as before...

public static Profiles Instance
{
// Thread-safety...
lock (padlock)
{
if (instance==null )
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
KC
Thanks for the response.

I see how that could solve it, but that code is not utilizing C#'s built-in
singleton functionality. In that code I have the overhead of locking on
each invokation. That can be fixed with double-checks, i.e.:
if (instance==null )
{
lock (padlock)
{
if (instance==null )
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}

So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons
like the ones I described, without breaking the MS recommended design (that
uses the built-in functionality).

Thanks again!
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
KC <no@mail.com> wrote:

What you could do is change Instance to a property like this:

sealed class Profiles
{
static Profiles instance;
static object padlock;

...Constructor as before...

public static Profiles Instance
{
// Thread-safety...
lock (padlock)
{
if (instance==null )
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
}

Nov 16 '05 #3
KC <no@mail.com> wrote:
Thanks for the response.

I see how that could solve it, but that code is not utilizing C#'s built-in
singleton functionality. In that code I have the overhead of locking on
each invokation. That can be fixed with double-checks, i.e.:
if (instance==null )
{
lock (padlock)
{
if (instance==null )
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
No, that *can't* be solved with double-checks, unless instance is
volatile.

See http://www.pobox.com/~skeet/csharp/singleton.html
So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons
like the ones I described, without breaking the MS recommended design (that
uses the built-in functionality).


You could use a static constructor and stash not just the instance but
the exception as well, and make the property:

public Profiles Instance
{
get
{
if (constructionEx ception != null)
{
throw constructionExc eption;
}
return instance;
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
KC
Thanks again!

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message >

No, that *can't* be solved with double-checks, unless instance is
volatile.

See http://www.pobox.com/~skeet/csharp/singleton.html
Well, apparently there is some controversy as to whether that is safe or not
:) Let's leave it
at that. No use risking it though, which is why I like the MS design.
So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons like the ones I described, without breaking the MS recommended design (that uses the built-in functionality).


You could use a static constructor and stash not just the instance but
the exception as well, and make the property:

public Profiles Instance
{
get
{
if (constructionEx ception != null)
{
throw constructionExc eption;
}
return instance;
}
}


Yeah, I like that. So, I make the instance variable private and force the
use of the property, which throws the exception (if there was one). I will
test that tonight :)

Thanks!!!

/Kris
Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
12473
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a) explicitly make the arbitrary class's constructor and destructor private b) declare the Singleton a friend of the arbitrary class
18
2113
by: Alfonso Morra | last post by:
Hi, Anyone knows of a link to a singleton design pattern example in C++ (preferably not using a global variable?).
11
2164
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be possible to extend the Singleton pattern to handle this? Assuming that my Customer class follows the Singleton pattern (particularly Skeet's 4th version) I'm thinking if I add private static SomeCollectionType customers;
21
2460
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
16
13985
by: ed_p | last post by:
Hello, I have implemented the singleton pattern for a class to hold a SqlConnection object that will be used thruout the application to create commands. My application is a simple Windows Form Application that connects to a MSDE Database. I was reading the thread yesterday on this very same subject, but it only mentioned ASP.NET Applications. Can anyone tell me if it's a good idea
11
4912
by: Eric | last post by:
I have a VB.net dll project with a class that is a singleton. I've been using this in winform apps without any problems. I would like to use this same dll in a web form project but my singleton will cause problems because some sessions may need different values in the singleton. I want to change my singleton to store a private hashtable with different instances. I guess this is more like a factory pattern now but that doesn't matter ...
7
1424
by: ThunderMusic | last post by:
Hi, I have a problem regarding singletons in C#. What I would like to do is the following ClassA is a singleton ClassB inherits from ClassA and is also a Singleton there cannot and instance of ClassA and an instance of ClassB, there must be only one of one or the other... Is there a way to do it? or it's simply not possible?
3
2962
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single
3
1798
by: stevewilliams2004 | last post by:
I am attempting to create a singleton, and was wondering if someone could give me a sanity check on the design - does it accomplish my constraints, and/or am I over complicating things. My design constraints/environment are as follows: 1) Everything is single-threaded during static initialization (as in prior to the open brace of main) 2) The environment may be multi-threaded during nominal program execution (within {} of main) 3) I...
0
8672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9155
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9018
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8858
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2322
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.