1

I was looking at this thread on Stack Overflow and thinking about the functional programming I've been learning, and how immutability is so key there, and it occured to me that maybe some language has gotten the idea to have variables start out "null", then go to a "building" state, and finally become the same as any other immutable when initialization is done.

Is this a valid concept and/or has it been tried or experimented with at the language level?

It might look something like this:

string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
s.Freeze() // now it's immutable

It's just a thought.. maybe it's not a good one, but it seems like a hybrid of two things that seem to be opposing one another.

6

4 Answers 4

2

You are confusing concepts, in your code the string variable "s" is immutable all along and in no moment it ceases to be immutable.

String s new String(); // Strings are ummutable

    for x = 1 to 10
      s = s + "z"   // you are destroying an object, creating 
                    // another one and assining it to the 
                    // reference. You are not changing the 
                    // internal state of the String.
      s.Freeze()    // It makes no sense. The only way to avoid 
                    // assigning a new value to a variable is 
                    // converting it into a constant. But then you can only
            // assign an initial value when you declare it. 

Immutability means not being able to alter the internal state of an object via properties, settters or methods.

In Java, the String class is immutable, meaning it has no setters or other method of changing its state.

The class StringBuffers is mutable, it has an Append() method and others that change its internal state.

The String class being immutable doesn't mean you cannot over-write the a String object, and assing other string to the reference.

That being clear, you can certainly program a class whose setters raise and IllegalStateException if you try to set a value after you have "frozen" it.

public class FreezableThing {
    private String name="";
    private int number=0;
    boolean frozen = false;

    public boolean isFrozen() { return frozen; }

    public void setFrozen(boolean frozen) { this.frozen = frozen; }

    public String getName() { return name; }

    public int getNumber() { return number; }

    public void setName(String name) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }
        this.name = name;
    }

    public void setNumber(int number) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }       
        this.number = number;
    }

}

...

2
  • thanks for helping me clear up my concepts, very good answer Commented Jul 4, 2013 at 13:25
  • This is not a universal view. In C++, s = s + 'z' is shorthand for s.operator=(s.operator+(z)). operator+ creates a new object from two constant source objects, but operator= definitely modifies its left hand side.
    – MSalters
    Commented Jul 5, 2013 at 7:37
1

The pattern you describe looks a lot like a constructor in object-oriented programming; while fields are not necessarily immutable, it is common practice to build your objects to be immutable except for the constructors, e.g., in a hypothetical OOP language:

class NumberSequenceString {
    private string val;

    public function __construct(top) {
        val = "";
        for (i = 1; i <= top; i++)
            val = val + (string)i;
        val = val + "z";
    }

    public getVal() { return val; }
}

var myString = new NumberSequenceString(10);

(I took the liberty to make your code sample a bit more interesting: instead of repeating "z" 10 times, it now spits out the string "12345678910z"; the code required to build this string is just complex enough to demonstrate nontrivial processing later).

However, most functional programming idioms take a different route; instead of distinguishing between the "uninitialized", "constructing" and "immutable" phases of a variable's life cycle, they just eliminate the first two: a variable's life cycle starts when it is defined, and the definition already provides the only value it will every have. This is possible because the functional programming idiom favors powerful expressions over statements, which means that the value you're assigning can itself be constructed in just one expression; instead of using iterative loops with a mutable counter variable, functional programmers think in terms of map and reduce. Your example in functional style would look something like this:

function makeSequenceString(top) {
    return range(1, top).map(toString).reduce(+) + "z";
}

const myString = makeSequenceString(10);

Or, more idiomatically, in some sort of pseudo-Haskell/ML/F# kind of syntax:

makeSequenceString top = (reduce (+) (map toString [1..top])) + "z"
myString = makeSequenceString 10

Note that the part that constructs the value is just one big expression, and the makeSequenceString function does absolutely nothing but evaluate the expression and return its value. And since we're assigning that value immediately as part of the definition of myString, there is no point in the program at which myString is uninitialized or "being constructed" - as soon as it exists, it has a value, and that's the only value it will ever have (at least as long as the programmer sticks with a purely functional style).

1

The work on typestate introduced ways for a type system to keep track of what operations are permitted on a piece of data as the state of the data changes over time. The original paper used typesafe to safely initialize and finalize variables. Later work applied typestate to high-level properties, such as keeping track of whether a file is open or closed. Plaid uses typestate.

In a language with typestate, objects have a type at each program point. Functions can alter the types of the objects that they access. The language's typing rules ensure that variables are always used in a way that's consistent with their type, so that attempts to use an uninitialized variable or read from a closed file are caught at compile time.

1

The problem with your approach is static type safety:

string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
if (rand()==0) s.Freeze() // now it might be immutable

And the explicit solution to this is a pair like String/StringBuilder. One is immutable and long-lived, the other is used in construction and shortlived. Your "Freeze()" becomes the assignment from the builder to the immutable object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.