Monday, January 26, 2015

OOP in Erlang. Part 1. Encapsulation

Introduction

There is a popular statement, that principles from object oriented programming (OOP) are not be applicable in functional languages and particularly in Erlang. Let's try to analyse it.
The main concepts of object oriented design (OOD) are

  1. Encapsulation.
  2. Polymorphism.
  3. Inheritance

Encapsulation

Encapsulation concept in Erlang could be found at least in process model.

Processes

Each process has it's own state, which can only be modified by handling of message sent to the process. Process is free to ignore any kind of message, handling particular ones.
One of Erlang's "design pattern" is process per message, which encourages to spawn a process for each concurrent instance in a system. In case of HTTP service requests' handling is concurrent, but having encapsulation only on that level is not enough for a good Web framework. Also good people never force client to call gen_server:call/2 for a gen_server they've implemented, they wrap such calls with functions in client API modules.

Modules

Erlang module has export attribute,  which allows to call some functions implemented in it from outside. What else is it, if not splitting to public and private functions in OOP language?
Modules can represent objects even in easier way than processes. For example, queue and proplists. One can say that there is no protection from module's function being called with wrong argument, but the same situation is in Python, where private functions are distinguished from public only by naming conventions.

Conclusion

Erlang has two levels on encapsulation, which could be combined in order to create a good design for system.


To be continued.

Friday, January 16, 2015

default value for application environment variable

Current Erlang release contains a function application:get_env/3. Until it was included into OTP, many projects had developed similar functionality of specifying a default value for application environment variable.
This function in some cases makes system more complicated in terms of understanding and configuration. Basically it transfers value of variable from node config and .app file to the code. As a result if default value is used, user of node/application has no chance to notice such variable besides analysing of documentation, which is not always relevant or event exists, or source code.
In general it's a good practice to put some reasonable default value for each variable into the .app file of application.