Friday, 29 July 2016

Getters and Setters not Needed

Since I first learned of property descriptors in JavaScript I've had a certain feeling of guilt. Let me explain. In .C# the good practice is to use Properties for the access to any kind of public data (not only for "processed data": calculated, filtered, logged..., but also for just trivial data fields). We do the same in Java with get/set methods. I mean that in C# we write:

public string Name { get; set; }

//this automatic property is syntax sugar for:

private string name;
public string Name
  return name;

 set{ = value

So one would expect that we would write code in JavaScript like this:

var person = {
    get name() {
        return name;
    set name(newValue) {
        name= newValue;

//or like this

Object.defineProperty(person, "city", {
   get : function(){ return city; },  
   set : function(newValue){ city = newValue; },  
   enumerable : true,  
   configurable : true});

but I think nobody does this, so why? are we doing something wrong just out of lazyness?

No, we are not doing anything wrong, it's just that JavaScript is a different beast, and what is necessary in C# or Java is useless in JavaaScript. The reason for using properties even for just data fields is to isolate calling classes of changes in that class. If in the future that data field needs to be calculated or some additional checks need to be done, changing from a data field to a property will break the customer class. If it was in a different assembly, we'll have to compile it again. This is clear in Java, where a getter/setter is just a method, but it's the same in C#, cause a property is transformed by the compiler in one (or two) method. Changing from a data access instruction to a data retrieving or setting method invocation is a breaking change in a static language. So, using properties makes our code resistent to change.

In JavaScript this is not a problem. First, everything gets interpreted/jitted each time the program runs. Second, even if during the execution of one program we decided to replace a data field with a data accessor property the flexibility of the runtime will allow us to do so. Assuming the code accessing that datafield has already been jitted, it will have to be replaced by the jitted version of the new accessor descriptor invokation, which will have some performance impact, but I guess it should not be a problem.

So, feel free and happy to not use data accessors when all we need is a data holder.

No comments:

Post a Comment