Editorials

Immutable Objects

Immutable Objects
I came across a Java question a couple days ago asking how to substitute the values from a to b, and b to a, without using a third temporary variable. In short, how to transfer the contents without doing something like

C=A
A=B
B=C

How could you do this without using a third variable? The question had a lot of answers with formulas allowing the data to be copied from one to the other directly through bit masking techniques and other such fancy tricks.

My mind went back to the discussion on using Immutable Objects in the book “Foundations of Object-Oriented Programming Using .NET 2.0 Patterns” by Christian Gross (Amazon).

Here is how this could work out in a C# or Java class.

public class myClass
{
private _a int;
private _b int;

public myClass (int initA, int initB)
{
_a = initA;
_b = initB;
}

public int A { get { return _a; } }
public int B { get { return _b; } }

public myClass Reverse()
{
return new myClass(_b, _a);
}
}

This little class doesn’t really answer the question without using a third variable. In truth, return new myClass(_b, _a) does create a new variable…except it is now a class instead of an int value.

So, why would you use Immutable objects in the first place. The biggest reason is the reliability of your code. Using reference objects that may be updated, you can have un-expected results. Also, in a multi-threading environment, Immutable objects perform nearly as well as mutable objects, and have characteristics that are more thread safe.

Wiki has a good explanation if you wish to do more research. There are lots of things to consider when using Immutable objects such as how big the object is that you are using, how much memory it consumes, how often it is modified, and much more.

Drop a note to btaylor@sswug.org if you have comments you would like to add.

Cheers,

Ben

$$SWYNK$$

Featured White Paper(s)
All-At-Once Operations
Written by Itzik Ben-Gan with SolidQ

SQL supports a concept called all-at-onc… (read more)

Featured Script
fn_TablifyString
Returns words from a text string in table form. Words defined as contiguous ASCII alpha chars. Returns words only; a modifie… (read more)