473,614 Members | 2,351 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about a good way to make immutable objects

Hi group,

I want to have some advice about immutable objects.

I made a constructor.

function Point(x, y) {
this.x = x;
this.y = y;
}

This is a very simple one and now I want to make it immutable so that
once an object is created it cannot be modified.

I came up with 2 ways.

[1]
function Point(x, y) {
this.x = function() { return x; }
this.y = function() { return y; }
}

[2]
function Point(x, y) {
this.getX = function() { return x; }
this.getY = function() { return y; }
}

They are both immutable.
You can read x and y but cannot change them.

[1] is short and easy to use but sometimes likely to be error-prone
like
var p = new Point(2, 3);
var x = p.x; //should be p.x() instead of p.x

[2] is straight-forward but looks verbose.
I have to access the data like p.getX() .

Which way is more recommendable?
And is there a better way to make an immutable object?

Thanks in advance.
Sam

Apr 8 '06 #1
3 3560
VK

Sam Kong wrote:
function Point(x, y) {
this.x = x;
this.y = y;
}

This is a very simple one and now I want to make it immutable so that
once an object is created it cannot be modified.


Install JScript.Net and declare them as "private static final" - that's
a killer combo :-)

There was a way discovered to implement protected members in the
conventional JavaScript, you may try it:
<http://www.litotes.dem on.co.uk/js_info/private_static. html>

Apr 8 '06 #2
Sam Kong wrote:
I want to have some advice about immutable objects.
Javascript objects cannot be immutable. The object type is a dynamic
collection of name/value pairs and if the abject itself is accessible it
can have its properties modified, and new ones added at any time. So the
only way an object can be immutable (that its properties cannot be
changed/modified) is to put the object itself where it cannot be
directly accessed.
I made a constructor.

function Point(x, y) {
this.x = x;
this.y = y;
}

This is a very simple one and now I want to make it
immutable so that once an object is created it cannot
be modified.

I came up with 2 ways.

[1]
function Point(x, y) {
this.x = function() { return x; }
this.y = function() { return y; }
}

[2]
function Point(x, y) {
this.getX = function() { return x; }
this.getY = function() { return y; }
}
These are implementations of Douglas Crockford's technique for emulating
private instance members in javascript:-

<URL: http://www.crockford.com/javascript/private.html >

- where the x and y values that you are interested in are not properties
of the object at all but instead variables/parameters preserved within a
closure (See:-

<URL: http://www.jibbering.com/faq/faq_notes/closures.html > )

Once the x and y values of interest are preserved within the closure
they cannot be accessed and changed by code outside of the closure, and
so only the 'getter' methods created within the constructor can access
them.

This does not make the object immutable, it just allows control over the
access to the values. However, it doesn't look like it is actually the
unachievable immutability that you are after but instead the control of
the access to the x and y parameter values.
They are both immutable.
You can read x and y but cannot change them.

[1] is short and easy to use but sometimes likely
to be error-prone like
var p = new Point(2, 3);
var x = p.x; //should be p.x() instead of p.x
Yes, naming the 'getter' method 'x' does make the method itself look
like a value property. Generally method names should be chosen to say
something about what the method does, and prefixing 'getters' with "get"
and 'setters' with "set" is so common and obvious that using any other
name seems perverse (assuming code written by/for English speaking
programmers).
[2] is straight-forward but looks verbose.
I have to access the data like p.getX() .

Which way is more recommendable?
The latter. Verbosity is not something that should be shunned. Code
should be as easy to understand as is practical, for the sake of ongoing
maintenance/development, particularly by other programmers. If you feel
you need name/code size reduction for delivery that can be machine
applied post-development.
And is there a better way to make an immutable object?


There is no way of making an object immutable in javascript (except to
put the entire object where it cannot be accessed (inside a closure)),
but that is the best (only) way of controlling the access to the values.
On the other hand, the extent to which it is necessary to emulate
private members in javascript is questionable; most of the time you will
not be writing larger, complex, systems in javascript, or even working
with large teams of javascript programmers of differing skill levels. It
may be sufficient to know yourself, and/or properly documented, that a
property should not be changed by external code, and so never be writing
code that does so. Naming conventions, such as the common "all property
names with initial underscores should be _considered_ 'private'", may be
enough to negate the issue.

Being able to do something is not in itself a reason for doing it.

(Incidentally, in the event that you are not sufficiently familiar with
class-based languages to see why VK's use of "static" in his response to
your question flags him as an irrational half-whit who does not
understand what he is talking about and should not be listened to at
all: he is an irrational half-whit who does not understand what he is
talking about and should not be listened to at all.)

Richard.
Apr 8 '06 #3
Hi, Richard,

Richard Cornford wrote:
Sam Kong wrote:
I want to have some advice about immutable objects.


Javascript objects cannot be immutable. The object type is a dynamic
collection of name/value pairs and if the abject itself is accessible it
can have its properties modified, and new ones added at any time. So the
only way an object can be immutable (that its properties cannot be
changed/modified) is to put the object itself where it cannot be
directly accessed.
I made a constructor.

function Point(x, y) {
this.x = x;
this.y = y;
}

This is a very simple one and now I want to make it
immutable so that once an object is created it cannot
be modified.

I came up with 2 ways.

[1]
function Point(x, y) {
this.x = function() { return x; }
this.y = function() { return y; }
}

[2]
function Point(x, y) {
this.getX = function() { return x; }
this.getY = function() { return y; }
}


These are implementations of Douglas Crockford's technique for emulating
private instance members in javascript:-

<URL: http://www.crockford.com/javascript/private.html >

- where the x and y values that you are interested in are not properties
of the object at all but instead variables/parameters preserved within a
closure (See:-

<URL: http://www.jibbering.com/faq/faq_notes/closures.html > )

Once the x and y values of interest are preserved within the closure
they cannot be accessed and changed by code outside of the closure, and
so only the 'getter' methods created within the constructor can access
them.

This does not make the object immutable, it just allows control over the
access to the values. However, it doesn't look like it is actually the
unachievable immutability that you are after but instead the control of
the access to the x and y parameter values.
They are both immutable.
You can read x and y but cannot change them.

[1] is short and easy to use but sometimes likely
to be error-prone like
var p = new Point(2, 3);
var x = p.x; //should be p.x() instead of p.x


Yes, naming the 'getter' method 'x' does make the method itself look
like a value property. Generally method names should be chosen to say
something about what the method does, and prefixing 'getters' with "get"
and 'setters' with "set" is so common and obvious that using any other
name seems perverse (assuming code written by/for English speaking
programmers).
[2] is straight-forward but looks verbose.
I have to access the data like p.getX() .

Which way is more recommendable?


The latter. Verbosity is not something that should be shunned. Code
should be as easy to understand as is practical, for the sake of ongoing
maintenance/development, particularly by other programmers. If you feel
you need name/code size reduction for delivery that can be machine
applied post-development.
And is there a better way to make an immutable object?


There is no way of making an object immutable in javascript (except to
put the entire object where it cannot be accessed (inside a closure)),
but that is the best (only) way of controlling the access to the values.
On the other hand, the extent to which it is necessary to emulate
private members in javascript is questionable; most of the time you will
not be writing larger, complex, systems in javascript, or even working
with large teams of javascript programmers of differing skill levels. It
may be sufficient to know yourself, and/or properly documented, that a
property should not be changed by external code, and so never be writing
code that does so. Naming conventions, such as the common "all property
names with initial underscores should be _considered_ 'private'", may be
enough to negate the issue.

Being able to do something is not in itself a reason for doing it.

(Incidentally, in the event that you are not sufficiently familiar with
class-based languages to see why VK's use of "static" in his response to
your question flags him as an irrational half-whit who does not
understand what he is talking about and should not be listened to at
all: he is an irrational half-whit who does not understand what he is
talking about and should not be listened to at all.)

Richard.


Your explanation is very helpful.
Thanks.

Sam

Apr 8 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

48
3461
by: Andrew Quine | last post by:
Hi Just read this article http://www.artima.com/intv/choices.html. Towards the end of the dicussions, when asked "Did you consider including support for the concept of immutable directly in C# and the CLR?" Anders' reply included this comment: "The concept of an immutable object is very useful, but it's just up to the author to say that it's immutable."
14
2131
by: JoeC | last post by:
I have been writing games and I also read about good programming techniques. I tend to create large objects that do lots of things. A good example I have is a unit object. The object controls and holds everything a unit in my game is supposed to do. What are some some cures for this kind of large object or are they OK because they represent one thing. If not what are better ways to design objects that behave the same way. Would it be...
9
1680
by: n00b | last post by:
Hello everyone, I just had a question about deleting objects in C#. For example if I have a string array and I wanted to make it grow by one size adding the string "dd" to it. string array = new string {"aa", "bb", "cc"}; string temp = array; array = new string; array = "dd";
0
8197
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8142
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8640
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8287
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7114
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5548
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4136
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2573
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1438
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.