Archives for posts with tag: destructors

This is part 3 of a series on patterns for writing safe constructors (and destructors) in C# and Java. Start reading at part 1: Exceptions in Constructors.

As seen in part 2, using the Open / Close pattern decouples object creation and resource allocation safely. However, for this solution to work we need to rely on the user of the object to stick to the correct sequence of actions, or we need to explicitly enforce the correct sequence with invariants.

Static factory methods reduce the potential problems we introduced in part 2. This is achieved by combining object creation and calling the Open method. Many of the problems listed at the end of part 2 simply disappear.

Read the rest of this entry »

Advertisements

This is part 2 of a series on patterns for writing safe constructors (and destructors) in C# and Java.

As seen in Part 1, we can have a problem if a constructor throws an exception after allocating a resource. There is no trivial way of releasing the resource after the constructor bails out. Part 2 discusses the most common pattern to avoid this situation: moving the allocation of resources into an Open() method.

Read the rest of this entry »

What happens if a constructor throws an exception? Is a new object still created? Do we even need to care?

Yes, a new object is created. It won’t be initialized properly and we usually won’t have a reference to it. And yes, we do need to care. That half initialized object may block important resources.

The examples in this series are in C#, but everything can be applied to Java and other similar object oriented languages.

Read the rest of this entry »