Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?

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

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

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).

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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?

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

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

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).

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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật