From: John Carter Date: 2005-10-20T06:32:16+09:00 Subject: DbC, const and freeze. Hmm. I tend to do Test Driven Development and Design by Contract. I find the two approaches mesh very very well indeed. Now in C++ I also use "const" very heavily. It works very very well. It not only enforces certain design decisions, more importantly it documents them. If you hunting a bug that is mystikally changing a data value, a well "const"'d C++ program allows you to ignore so much code and rapidly zoom in on the real problem. I was just thinking about the Object freeze method. Now that is quite a powerful assert really. It asserts that this object needs not and must not ever change. A bit more powerful than "const" in away. In fact too powerful. What I really want is something like the C++ void myFunc( const obj& foo) { // I know foo won't get mangled by this routine... } or in Ruby... def my_func( foo) foo.freeze ensure foo.unfreeze end Accept there is no unfreeze. This would work, but is a bit expensive... def my_func( foo_p) foo = foo_p.clone.freeze end It also misses the notion of "const" methods. In C++ you are only allowed to invoke const methods of a const object. For example, look at this hole... irb irb(main):001:0> a = [[1,2],[3,4]] => [[1, 2], [3, 4]] irb(main):002:0> a.freeze => [[1, 2], [3, 4]] irb(main):003:0> a << [9] RuntimeError: can't modify frozen array from (irb):3:in `<<' from (irb):3 from :0 irb(main):004:0> a[0]<<1 => [1, 2, 1] irb(main):005:0> a => [[1, 2, 1], [3, 4]] irb(main):006:0> Even though "a" was frozen, I still could modify the things "a" contained. Although Ruby has a C++'ish distinct between public and private methods, it doesn't allow you to use that with "const" to identify which things this class owns and freeze when this object is frozen. Hmm. I suppose I could override freeze and freeze my instance variables and then myself. That would do. Any other ideas on getting the effect of C++ "const" in Ruby? John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand Carter's Clarification of Murphy's Law. "Things only ever go right so that they may go more spectacularly wrong later." From this principle, all of life and physics may be deduced.