Inheritance and composition

The modern JavaScript with the ES6 syntax and the rise of the popularity like ReactJS, functional programming becomes more and more common. When using React, one of the common practice is to use composition instead of inheritance.

Because I started learning programming when the OOP was the most prevailing paradigm, I was trained to solve the problem by using OOP concepts like polymorphoism, inheritance, encapsulation, etc.

I think JS is the most interesting programming language in the modern technology. It supports server-side and client-side development. With the ES6, it supports OOP keywords like class and also using FP (functional programming) syntax like fat arrow (=>).

In OOP, the most common usage is the inheritance and polymorphoism. The following is an example of inheritance in JS,

class Shape {
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
  area() {
    return this.width * this.height;
  }
}

class Rectangle extends Shape {
  constructor(w, h) {
    super(w, h);
  }
}

class Triangle extends Shape {
  constructor(w, h) {
    super(w, h);
  }
  area() {
    return super.area() / 2;
  }
}

function main() {
  const rectangle = new Rectangle(4, 5);
  const triangle = new Triangle(4, 5);
  console.log('Rectangle area: ', rectangle.area());
  console.log('Triangle area: ', triangle.area());
}

main();

The shape area calculation can be re-written to composition instead of inheritance as followings,

class Rectangle {
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
  area() {
    return this.width * this.height;
  }
}

class Triangle {
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
  area() {
    const rect = new Rectangle(this.width, this.height);
    return rect.area() / 2;
  }
}

Therefore, Rectangle and Triangle do not inherit from Shape. In fact, Triangle uses Rectangle to calculate the area. This is the object composition, and it is same as the way of composition in React. Furthermore, one of the greatest features of JS is closure. This allows React to pass a function with specific logic as a parameter to a generic component. Thus, the generic component can be designed without the prior knowledge of the business/application logic. This will produce a result similar to method override in OOP.

Moreover, the object composition can be re-written to function composition as FP.

const rectangleArea = (w, h) => w * h; // In math, f(x,y) = x * y
const halving = (area) => area / 2; // In math, g(x) = x / 2
const triangleArea = (w, h) => halving(rectangleArea(w, h)); // In math, h(x,y) = g(f(x,y)) = f(x,y) / 2

function main() {
  console.log('Rectangle area: ', rectangleArea(4, 5));
  console.log('Triangle area: ', triangleArea(4, 5));
}

main();

Firefox or Chromium (software development)?

I was switching from Chromium to Firefox as my primary web browser recently. Then, I switched back to Chromium again.

Chrome was usually claimed that it consumes a lot of memory. And recent Firefox updates claim that it is faster and consumes less memory. That is why, I switched to Firefox. I agree that, it is much faster than before. However…

I faced a critical issue. One less important issue that I would like to mention is, Firefox does not support Google Hangout.

The critical issue I faced related to JavaScript. During the web development or even visit CircleCI (which I believe it has heavy usage of JavaScript), if the JavaScript has severe errors, whatever web browser you are using will stop respond or slow down. But, Chrome (Chromium I mean) deals the issue differently from Firefox. The whole computer will be slow down temporary (may be several minutes), then at the end, the page will be shown as “dead” and I can control over my computer again.

In the same condition, Firefox will expand the memory (possibly exponentially) due to the errors. Then the computer starts slowing down and stop respond until I do a hard reboot. Based on my observation, the memory grows and uses all the RAM. When the RAM is not available, the memory is immediately stored into the Swap. Because storing into the Swap, that is the hard drive, it is much slower for me to switch to a Terminal to kill Firefox. And even I successfully switch to a Terminal, typing the command and see the response takes approximately infinite time, yet the Swap memory usage keeps growing non-stop.

As a web developer, I prefer to use Chrome.

Closure

In JavaScript, we can create closure like this,

var foo = (() => {
  let x = 0;
  return () => {
    return x++;
  }
})();

for (var i = 0; i < 10; i++) {
  var x = foo();
  console.log(x);
}

But translating above code into C++, it cannot work as expected for the variable, unless the variable is outside the lambda function.

// In a function
int x; // variable here
auto foo = [&x]() {
  x = 0;
  return [&x]() {
    return x++;
  };
}();
for (int i = 0; i < 10; i++) {
  int x = foo();
  cout << x << endl;
}

This is because C++ variable can be only accessed in the function scope. After the function return the value, the variable is not accessible anymore.

Similarly, Python can also return the function, but it cannot work as closure like JavaScript. However, Python can create non-primitive variable such as object or list so that the variable will be accessed by reference.

def _foo():
    x = [0]
    def increment():
        x[0] += 1
        return x[0]
    return increment

foo = _foo()
for i in range(10):
    x = foo()
    print(x)

JavaScript

Previously I read an article regarding JavaScript and another one regarding HTML.

JavaScript, it is so wonderful that not only enhances the HTML interaction, (e.g. jQuery), it also makes a revolution of the system architecture design (e.g. AngularJS, ReactJS with Babel). The Babel JavaScript compiler is so amazing that it can transform the JavaScript to EcmaScript 6 with JSX feature. JSX is actually cannot be interpreted by our current web browser, but with the Babel, it makes JSX possible.

I really cannot believe that a JavaScript can interpret a statement with the syntax like this,

var div = <div>Hello world</div>;

JavaScript, not only client-side interpretation, it also runs as the server-side, such as NodeJS.

In my opinion, JavaScript becomes so popular and so powerful is because of several factors: Web technology itself, HTML specification (DOM design), and CSS specification. In order to produce a web application effectively and efficiently, programmers developed the solution from the JavaScript aspect, because this is the best way for hacking (I do not mean cyber security attack).

As the three fundamental technologies of WWW: HTML, CSS, and JavaScript, you can discover that their syntax are different, and only JavaScript is an imperative programming language; HTML and CSS are declarative programming languages. Yet, these three languages can be integrated into single HTML page. Other programming languages such as C, C++, PHP, Java, C#, etc, they are too programmer-oriented. As a result, they are too rigid during the development. JavaScript is using dynamic typing, thus, development on the JavaScript is more robust. PHP is also dynamic typing, but it is server-side scripting language. JavaScript because of NodeJS, both client-side and server-side can use it. One language rules them all.

And because of JavaScript, the rise of JSON is gradually replacing XML. It is more lightweight and highly used in Web API. Comparing to XML, JSON is much simpler, focusing on the data only. And the syntax can be easily used to differentiate the data types: number, string, boolean, array, object, and null. On the other hand XML should be parsed with a parser according to a DTD (document type definition). Moreover, MongoDB uses BSON format, which is based on JSON.

Therefore, for the web technology, JavaScript is one language that rules them all. I am no sure whether JavaScript will be highly used in desktop applications or not. But surely it cannot be used to develop system software.

TinyMCE plugin: inserttab

I wrote a small plugin for TinyMCE, to solve the “tab” problem. This is because, in the TinyMCE editor, whenever I press “tab”, it will navigate, instead of insert “\t” in the editor.

After some understanding with TinyMCE API, then I wrote this plugin.

Usage:

  1. Add the inserttab plugin button to the toolbar, in the HTML Javascript. This will show a button with “\t” image in the editor.
  2. Click the button to enable the feature.
  3. Then, whenever we press “tab”, if it is preformatted text, then it will become a real tab, “\t”, else will be filled with “&nbsp;&nbsp;&nbsp;&nbsp;”.
  4. To turn off, just click the button again.

The plugin is BSD license. It can be downloaded here.

My first Greasemonkey script

Finally, I wrote a Greasemonkey script. The script is target on a Chinese comic website. You can download the script here. I wrote the script because the links are not named in sequence. To offline read the comic, I would like to download the comic first. Then I can read the comic offline. After that, I can delete the comic.

But the name are not in sequence, I cannot download the comic using batch downloading. Thus, writing this script to produce the link, then from the link, I can download the comic with any download manager.

Before writing this script, actually I plan to wrote a comic download manager, target on any website. But suddenly I wonder why don’t I use javascript to generate the link.