Programming Features

PHP Nested Ternary Operator Order

Now let’s say we have the following pseudo-code that we want to implement in several programming language:

bool condition = true;
string text = condition == true ? "A" : condition == false ? "B" : "C";
print text;

Here is the implementation in Javascript:

let st = true;
let text = st === true ? "A": st === false ? "B" : "C";

Here is the implementation in PHP:

$st = true; 
$text = $st === true ? "A": $st === false ? "B" : "C"; 
echo $text;

As a bonus, I also try the same pseudocode in C#:

bool st = true;
string text = (st == true) ? "A" : (st == false) ? "B" : "C";

Now let’s guess what is the result of variable text? The expected value should be A, which is already correct in other languages, but PHP​ produces B. Well, this is not a great discovery but many PHP developers may be missing this after all, so I think it’s worth archiving. Parentheses may fix them but it’s making things ugly, looks like it’s better to stick with if-else statement then.


Security is hard

The recent issue about meltdown and spectre attack shows how hard a security implementation is. For a short explanation, those two attacks takes advantage of CPU’s error handling to gain access and read other non-authorized memory address. A patch has been published by each respective vendor and OS right after. However the real issue is the applied patch can bring down the performance up to 30%! And this is what I want to raise in this article.


Ignoring programmers efforts or development cost, a security implementation may or may not has a trade-off, but it’s more likely to has a trade-off rather than not.

Let’s take for example a security token for online banking. It’s a security implementation that reduce UX (user experience) by adding one step of verification. Though in this case the trade-off is worth it, that it helps the user to verify the input and prevent wrong transaction that otherwise can be too easy.

Asking user for username password everytime to login is also a UX trade-off, in which lately there is other option by “login with facebook”, “login with twitter” and so on. And in majority of trade-off, such as in latest meltdown case, is performance drop due to another step of verification.

Trade-off vs Risks

Security flaw after all, are just risks. It’s only when an attack being executed that the security flaw is a loss for one. Usually security flaw only bring negligible trade-off (performance drop) that it’s better to implement than not. Some example, preventing sql injection, xss, one-way hash salted password, using HTTPS is a common practice. They should be enforced because otherwise it’ll be too easy for the attacker to exploit the flaw and getting advantage of it.

However in case of up to 30% performance drop in latest case, how complex and how much precondition there is for a successful meltdown attack, the performance drop to risk rate can be considered high. In this case, there is an “advantage” to not fix the security flaw, and simply hoping for the attacker to either not targeting you, do not attempt with specific attack method, or simply doesn’t interested enough that they don’t want to waste with their time.

However, the risks will always be there and the attacker may be have better and better tools to exploit the flaw, while at the same time we can hope for better and better fix with lower trade-off to exists. After all, it’ll be top level management and developers that may decide whether it’ll be better to patch it right away or leave it as is.

After all, security is hard.


Why PHP is bad and why it isn’t

Nowadays programmers consider PHP as a very bad programming language. One of the example is in this comic strip, saving the princess with programming language. But why is PHP considered bad and why does it is very popular out there?

The good

In general, PHP is a good language to start learning programming with.

It’s easy to setup and start

PHP is very easy to setup, especially for beginner. Just use XAMPP (for windows) and LAMP (for linux), and drop the code in htdocs and everything will go well. Just search in google for “hello world php xampp” or “hello world php lamp” and you’re good to go.

Furthermore it’s one of the easiest language to setup shared hosting, making it very easy to make your own website.

It’s very forgivable

PHP is dynamic typing, meaning you don’t need to specify whether an variable is string, int, specific class, etc. And it’s string concatenation is different with numeric additional, making it less ambiguous than javascript’s dynamic and don’t need type conversion. It’s very easy for beginner to start with.

And PHP variables works very well with HTML. Almost all native variables can be printed to screen by using echo, while array and object need special treatment.

Furthermore, using undefined variable only resulting in notice, and can be easily suppressed. But beware, both are considered “bad habit” in programming, so take it as learning features. There are also more exceptions that usually result in error in other language, that can easily suppressed in PHP.

It’s both procedural and OOP

PHP can serve procedural code, and OOP one. It’s very common to start learning programming with procedural, and learning OOP next, and it’s easier in same language.

Furthermore, PHP is a C-like syntax programming language, and there are many good languages in C-like syntax, like Java, C# and javascript. It’s C-like syntax is better than python (which is also a good starting language) “if” you aim to move later to those language.

Frameworks and tutorials are abundant

With many framework and tutorials out there, someone can search any problem or topics that they currently worked at, and finding many pages of google results. It’s very easy to find answers to PHP problems nowadays.

Furthermore, many PHP framework are using MVC (Model View Controller) pattern, which is one of the most common pattern in web programming. Learning them can help transition to other good languages using MVC pattern, such as Java MVC spring, C# Asp.Net MVC, NodeJs MVC frameworks and many more.

Furthermore nowadays PHP has composer, which is good to handle library as packages, which is almost all new languages use. And PHP has many CMS which make creating webpage like wordpress CMS easy.

The bad

So why is PHP considered bad? Well you need to at least good in programming to know it’s limitation and bad side.

It is not strong, static typed

PHP starts as dynamic, weakly typing language, helping to customize HTML pages ages ago. Up to this day, it still support dynamic typing, while supporting some type hinting at arguments and property level. While dynamic typing is good to start learning programming, it’s not good at complex business process.

However, being interpret language means the type hinting can only trigger when executed. So we won’t get any type error up until the portion of code is executed, as opposed to Java/C# where it can be caught compile time.

Moreover, PHP7, even after getting scalar type hinting for string and int, still not having generics for array. Without any means to type checking array, it’s harder to do type checking and enforce reliability, especially in business process (accounting).

It doesn’t have multithreading options by native

Without using additional components “PThreads”, PHP doesn’t have any options to emulate multithreading. It isn’t that PHP cannot do multithreading, however the problem lies in how “PThreads” works. It copy the current “process” state (loaded classes, etc) into another process and execute them concurrently.

In my experience with PThreads for PHP 5.6, (maybe I just lack configuration, correct me if so) PThreads use bigger memory than other programming languages, notably C#, Java and NodeJs. Moreover it’s harder to catch exception and to debug process spawned by threads.

So it doesn’t support multi-core process

In case of heavy background process or batch processing, most of the time multi-core support is a requirement.

It doesn’t have memory-persistence cache

PHP is run-and-forget scripting language, which load all it’s needed reference class on beginning of request (and during execution for lazy loading one), and to flush them later. The process takes time, and while PHP7 doing JIT to cache some of it’s code, it’s still not efficient because they need to be loaded for every request.

In contrast with PHP’s scripting, NodeJs and C# Asp.Net MVC (haven’t use java, but should be similar) run a server, and keeping the loaded classes (scripts) in memory, making them more efficient.

It’s dynamic typing takes too much memory

Looks like it’s mitigated in PHP 7, however in PHP 5.6 below, the dynamic variable in PHP takes too much memory. It’ll soon be a hassle when working with big variables, big file or many records of data.

And even if PHP7 is more efficient, it still can’t beat C/C++ level of memory usage per variable. And arguably, so do as in comparison with static typed language, such as Java and C# and the currently rising golang.

It’s data access doesn’t support multiple-result sets

Apply for MySql at least (looks like it supported in PostgreSQL). PHP cannot return multiple tables in one query. Let’s say that you have one procedure that returns 3 select queries, PHP MySql driver can only return one.

Many of it’s library support is configured at installation level

Some of the native library for PHP is configured during installation (gcc make and phpize). Some of the examples are zip (–enable-zip), thread safety (–enable-zts) for pthreads. It makes binding configuration to app repository level harder and reduce portability.

In conclusion

PHP is a good language to start programming with, easy to setup and have many libraries / framework / CMS. However in case of advanced use by expert programmers, PHP doesn’t really meet up the requirement.

Choosing the right tool for the job

This morning I read the following article: The myth of the “right tool for the job”. The short summary for that article is: do not choose programming language based on the task / project, but choose based on popularity, documentation and ease of learning. While that statement is not completely wrong, it’s also not perfectly right.

I dare you to use PHP for highly reliable, complex business process

Dynamic type makes developing reliable business process hard, because many times you don’t know which kind of variable being processed. This seems possible with HHVM and PHP7 due to type hinting, however the lacking of generic, runtime validation, and ability to re-assigning different type to same variable is making it harder. Consider the following code:

$var1 = new \ComplexObject(); 
$var1 = "Hello World";

I agree that it is a very bad code snippet. However it is possible in PHP and do not produce any error. Meanwhile in static typed language like C# or Java you will get compile error. Yes, compile error which validate variable types in compile times and produce error if the type is somehow not valid (except type casting).

Why compile-time type validation would that matter compared to runtime validation in PHP? The runtime validation in PHP won’t produce error if the code / function / module isn’t being triggered during process. That means to validate the type hinting at specific function, you’ll need to run all process that use the part of code to check whether the type is valid or not. Meanwhile compile time validation will produce error even if the part of code is not used anywhere.

So in short, if you need highly reliable, validated business process, then static typed, compiled language like Java or C#is better than dynamic typing like Nodejs or PHP.

Developing template-based process in Java or C#?

C# or Java is static typed language, so any template-based or string pattern process will be hard to develop. For example, the following code is a part of swagger JSON specification:

        "type": {
            "type": "object",
                    "type": "number",
                    "example": 1
                    "type": "string",
                    "example": "Information"
        "description": {
            "type": "string",
            "description": "Description",
            "example": "This is the description of Programming Language"

The code is swagger code for part for fields of object. If you tried to parse and process the JSON object in Java or C#, you’ll get a headache due to static typed. Meanwhile you’ll get native support when parsing that code in nodejs, or in PHP you can easily decode the json string to PHP objects.

Real time messaging service

I haven’t use Erlang so I don’t know how superior it is in term of messaging (chat) service. Whatsapp using Erlangfor their messaging service, so it’s somehow good at the job. For this case I’ll promote nodejs over Java, PHPor C#.

Nodejs is non-blocking single process server, meanwhile Java or C# is blocking single process server. PHP is the worst here, it spawn another thread or process for each request. So everytime a data is sent to PHP service, it’ll spawn another thread, loading all classes then begin processing the data. It take too much flow over single simple process.

Java or C# is good, however the non-blocking Nodejs is the superior one here. Nodejs will able to handle more requests in lower performance cost.


Some languages are good for some task, while the other are good for other kind of task. Finding the best language for specific task it not optimal. However deciding not to use programming language which is bad at the task is many times better than sticking to existing, used language in your environment.

Methodology / design pattern / development driven apa yang paling bagus?

Saat sedang melihat-lihat group programming di facebook, saya pernah melihat beberapa job opportunity dengan slogan seperti berikut: “Perusahaan kami menerapkan agile dan scrum!”. Banyak juga bahasan mengenai “agile” lebih baik dari waterfall, adalah metodologi terbaik. Tidak sedikit pula junior programmer atau analyst atau project manager baru di kantor-kantor yang bersikukuh bahwa team harus mulai menerapkan agile dan scrum. Hal yang sama juga berlaku pada TDD (Test Driven Development). Benarkah scrum + TDD adalah metodologi yang terbaik?

Sebelum saya melanjutkan dengan pembahasan yang lebih detail, akan menekankan hal yang menurut saya pribadi paling penting dalam pengembangan applikasi / system:

Pergunakan tools / cara apapun yang dirasa terbaik untuk menghasilkan applikasi yang bekerja dengan baik, dan mudah diubah. “Make it works, and changeable!”

Individuals and interactions over processes and tools

Salah satu manifesto yang cukup penting dan sering dilupakan dalam agile adalah “individuals and interactions over processes and tools“, atau bisa disingkat sebagai “people over process“. Sebagai programmer / developer / analyst, terkecuali kamu adalah ConcernedApe yang men-develop indie game “Stardew Valley”seorang diri dulunya, kamu akan bekerja dalam team, berinteraksi dan membuat keputusan-keputusan bersama.

Preferensi setiap orang berbeda-beda, dan metolodogi tertentu bisa bekerja di satu kelompok orang, bisa juga tidak berfungsi di kelompok orang lainnya. Bagaimana kamu dan team developer bisa bekerja dengan baik adalah yang terpenting, proses / metodologi adalah “alat bantu” yang bisa digunakan untuk mencapainya. “Scrum user story“, “Kanban board” tidak lebih dari hanya alat bantu untuk bekerja dalam team.

Bila dalam beberapa situasi tools tersebut tidak dapat digunakan dalam team, misalnya mayoritas tidak mengerti cara pakainya, atau tidak merasa ada manfaatnya, atau misalnya projectnya cukup kecil sehingga tidak diperlukan, maka carilah alternatif tools yang lebih dapat bermanfaat bagi team. Misalnya post-it notes di cubicle kerja masing-masing, atau minutes of meeting yang di-share dalam email, atau bug tracker.

Pernah saya berdiskusi dengan seorang project manager yang cukup berpengalaman, mengapa beliau tidak menerapkan daily standup meeting, yang umumnya adalah senjata pemungkas di scrum. Beliau menjelaskan bahwa teamnya bekerja secara remote di berbagai daerah yang berbeda, sehingga daily standup meeting tidak dapat dilakukan. Selain itu, tidak selalu ada hal yang dapat di-share dalam daily meeting, sehingga beliau menerapkan rule weekly report, dan contact langsung apabila ada (laptop, mouse rusak misal atau approval) yang diperlukan. Itu adalah contoh “people over process“.

Management juga tidak akan serta merta mengubah metodologi yang sedang berjalan secara tiba-tiba, untuk mengadopsi scrum secara mendadak. Perubahan itu terlalu beresiko, apabila team tidak terbiasa dan banyak yang tidak mengerti, maka perubahan hanya akan membawa musibah daripada manfaat. Terkecuali memang ada kebutuhan untuk meningkatkan metodologi development, jangan memaksa management untuk berubah demi ego sendiri atau “hanya karena scrum lebih baik”.

Metodologi sebaik apapun tidak akan berguna bila team tidak dapat menghasilkan applikasi yang berfungsi dengan baik

Scale it!

Salah satu hal yang menarik yang saya cermati adalah tidak banyak orang yang menyadari bahwa metodologi yang berbeda bisa diterapkan dalam skala yang berbeda pula, dalam satu organisasi. Misalnya project manager dan customer menggunakan iterative waterfall untuk memecah-mecah feature development ke dalam project-project, sebagai team bisa saja development dilakukan secara agile / scrum.

Atau hingga dalam skala personal sebagai programmer, kamu bisa saja memecah task list yang diberikan menjadi iterasi2 yang bisa menghasilkan feedback dalam 2 minggu (iterasi standar scrum), dan melaporkannya ke project manager / team lead secepatnya.

Don’t forget to make it changeable!

Saya berani bertaruh, tidak ada development plan / requirement yang tidak berubah saat development. Perubahan requirement adalah sangat wajar dan sangat mungkin terjadi. Di luar negosiasi finansial yang memang bukan ranah developer, mengembangkan applikasi agar bisa mudah diubah-ubah sesuai dengan perubahan requirement adalah penting. Applikasi yang mudah diubah juga penting agar dapat menambahkan fitur dengan mudah di kemudian hari. Hal ini juga tersirat dalam agile manifesto, “Responding to change over following a plan“.

Lalu bagaimana dapat mengembangkan applikasi yang mudah dikembangkan / diubah? Salah satunya adalah dengan membuat “low coupling, high cohesion” modul (class / function). Dan TDD dapat membantu mengembangkan kode yang low coupling tersebut. Namun dengan efek samping development time yang meningkat hingga 2x dari biasa dan kompleksitas dalam unit test, tidak semua team dapat menggunakan TDD (namun pastikan menggunakan TDD bila memungkinkan).

Ada 2 pemahaman lain yang juga dapat membantu mengembangkan kode “low coupling high cohesion”, yaitu Single Responsibility Principle, dan Dependency Injection. Keduanya adalah bagian dari SOLID principle, yang menurut saya lebih bermanfaat dari ke-3 pemahaman lain dari SOLID principle.


Pergunakan development method yang paling cocok dan bermanfaat untuk team. Kembangkan applikasi yang berfungsi, bisa digunakan dan mudah untuk diubah. Kembangkan kode yang “Low coupling High cohesion” agar applikasi dapat diubah dengan lebih mudah.

Markdown preview di Visual Studio Code

Buat github contributor, pasti pernah pakai markdown (terutama Ternyata di visual studio code ada feature untuk live preview markdown file loh. Semua editan di .md file ter-reflek otomatis di panel preview, jadi tidak perlu susah-susah untuk ngecek apakah format penulisannya sudah ok apa belum. Dengan fitur ini sebagian besar formatting bisa di-lihat langsung.

Caranya hanya dengan klik kanan file .md, lalu pilih menu “Open Preview” dan halaman preview akan terbuka.

Open markdown preview menu

Node await is synchronous

Starting from node 8, or node 6 with babel, we can use a feature named async await. It makes programming asynchronous code in synchronous way. For example, let’s say a function getNumberis returning Promise with resolve, we can call the function using await like this:

async function processNumber(){
  var number = await getNumber();
  number = number + 2;
  return number;

Async function will always return Promise, even though it isn’t described in code. Pretty neat huh, now that we can treat the promise as function that return something (synchronously). However, as I had previously assumed, await statement is executed synchronously.

I am using the test scripts at the following github repository. The code in app.js is using Promise.all, while the code in app2.js is using async await. In both code, they will execute same function, called execThings.

var execThings = function(i){
	return new Promise(function(resolve){
		var curIndex = i;
			console.log(curIndex, model);
		}, 120 - ((i * i) - (2 * i) + 5));

This function is accepting a numeric parameter, then it will resolve an incrementing number, defined in model.num. For the sake of some randomness and asynchronous process, I use setTimeout with randomized timeout based on input argument. When executed, here is one of the result:

12 { num: 0 }
13 { num: 1 }
14 { num: 2 }
15 { num: 3 }
16 { num: 4 }
17 { num: 5 }
18 { num: 6 }
19 { num: 7 }
11 { num: 8 }
10 { num: 9 }
9 { num: 10 }
8 { num: 11 }
7 { num: 12 }
6 { num: 13 }
0 { num: 14 }
5 { num: 15 }
1 { num: 16 }
4 { num: 17 }
3 { num: 18 }
2 { num: 19 }
[ 14, 16, 19, 18, 17, 15, 13, 12, 11, 10, 9, 8, 0, 1, 2, 3, 4, 5, 6, 7 ]

The top list is the log for each promise when executed. The bottom array is the Promise.all result. As we can see here, that Promise.all is executing all functions simultaneously, because the log is in unordered index. But the result is sorted according to executed promise. In the result, index 0, with value 14 is also in index 0 of Promise.all result. Index 1, same with result index, valued 16, and so on.

Now when executing app2.js (I’m using babel due to still using node 6), the result is:

0 { num: 0 }
1 { num: 1 }
2 { num: 2 }
3 { num: 3 }
4 { num: 4 }
5 { num: 5 }
6 { num: 6 }
7 { num: 7 }
8 { num: 8 }
9 { num: 9 }
10 { num: 10 }
11 { num: 11 }
12 { num: 12 }
13 { num: 13 }
14 { num: 14 }
15 { num: 15 }
16 { num: 16 }
17 { num: 17 }
18 { num: 18 }
19 { num: 19 }
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

As we can see here, async await is executed in synchronous process. The index is sorted neatly and the result is also as expected. And when executing the app2.js, it takes around 5 seconds, due to waiting for timeout delay. Meanwhile app.js is executed in up to 1 second.


Despite being very convenient, be aware that async await feature in node 8 or above (or babel) is being executed synchronously. Meanwhile the more complex Promise.all is execute the same process asynchronously. If you have a long-running process that need to be executed in parallel, Promise.all is the answer. However if you certain that the process is still very fast when executed synchronously, it’s okay to use async await since it’s more readable.

Again, you can get the complete test scripts in this  github repository.