Why JavaScript and PHP rule the web

JavaScript and PHP are excellent languages. It took some time for me to really understand their power, and I hope to clarify my point of view in this post.

I believe that those languages shine and survive for being permissive and by adopting an Assumption Inversion Principle (AIP) — I’ve made up that name, you may suggest a better one in the comments. 🙂

What is AIP?

Raw JavaScript does not have any module definition structure, no statements as “import” or “include”. Symbols available for a piece of code written in JavaScript are pure assumptions. Those assumptions must be satisfied by other pieces of code, and not by itself. It is incredibly easy to change behaviours by loading new script files before the one to be changed by changing the link of its assumptions. This “change by adding” relates directly with the “O” in the SOLID principles.

Old PHP code goes the same way, your piece of code has some assumptions that some symbols are available and you simply use it. It is not the responsibility of your piece of code to link those symbols, you normally end up putting all of your script loading in something like a bootstrap system.

Import statements are bad, because they hardwire the symbols in your piece of code. Then if you need to change something, you actually need to get into the file and change it. In my opinion, “change by changing” is more prone to errors than “change by adding”. Also, “change by changing” does not scale as well as “change by adding”.

JavaScript and PHP code can also inspect its environment and adapt. So it’s possible to keep adding files that keep changing stuff depending on what has already changed or what is currently available for the script. This is pure gold in software development.

Think about WordPress plugins, you don’t need touch a single line of the core code, you just drop a new file and you can get a whole new experience out of your web site. Some plugins add features, other plugins only change behaviours. So, it either “add by adding” or “change by adding.” It’s a win-win situation, core code is hardly changed to add a feature, so you won’t get any bug from features you don’t care. For the features that you care, you get the plugins, drop them in and live with the bugs, if you happen to find a scary security bug, just disable the plugin.

I know a lot of people who criticize this way of developing and would prefer that WordPress be more object-oriented than it currently is. For what? Then we would need a plethora of new abstractions to achieve the same stuff. As code is a liability, the less code we need to achieve something, the better.

I love Haskell and its type system, it’s phenomenal. But it suffers from the same problem as other languages like Java and C# suffer. Modules are hard-wired with their dependencies and code can’t inspect its environment. I’m not saying that those languages are bad and should not be used. They surely has their own good use cases.

For a fast and distributed development effort as the web is, we simply can’t afford anything that is unforgiving or strict. The code needs to be open for changes from the outside (change by adding).

So, for the web, I don’t like new PHP code that uses modules and neither the usage of ES6. They may feel faster for developers starting out new products, but my bet is that in the long run they end up killing productivity and/or quality.

Think about it for the current project you are working on, how much could you change of it by only adding new files? What could you deliver by adding a new file: a whole new story, a feature, a bug fix or nothing?

All this permissive environment with all these code based on assumptions can turn into a real mess. That’s the reason those languages are hated by some developers, then those developers try to fix it by creating new stricter languages for the web, the end of the story is always the same: JavaScript/PHP triumphs over all. Why? Is it because of AIP?

JavaScript and PHP has some hidden properties that newcomers tend to ignore. Those hidden properties make them a perfect fit for the web. What do you think?

Am I just an old-school guy talking bullshit? Please, be kind. 🙂

Using Facebook’s Flux architectural style for game development in Unity 3D

I decided to work again in an old game project. The game is named “Shotem” and the mechanic is quite simple: coins start falling from the sky and you need to “shot them” (got it?). Tap on a coin to shoot it, you gain score if you hit and you lose score if you miss the shot or if a coin falls off the screen (in case you didn’t tap it). You have seven bullets to use, each shot (finger tap) consumes a bullet and you need to shake the mobile device to reload your bullets.

The game is still a work in progress, but I added the following video in order to show that it actually works in real life:

I’ll write the history of the development process of this game. It started in a very naive form, then I converted it to Flux style and left it alone for three months. Now I’m coming back to it and had a pleasant surprise to read the code after forgetting about it. I think Flux style made it easy to continue the project were I left it. This post is 100% opinion based. Please, take a seat.

The first version I coded was very straightforward. Each coin was a GameObject with rendering and game behavior logic. All game state were inside a Singleton and two other objects were responsible for creating coins and handling user taps. Not organized at all.

I was interested in how to code the “reload by shaking” feature. As soon as I got it working, I lost my interest in the game mechanic itself. This happened quite fast actually, Unity 3D has a very nice class to use for dealing with the mobile device gyroscope: Input.gyro.

At the same time, I got in touch with Facebook’s Flux architectural style. I tried it in some web projects and had a nice feeling about it. It seemed easier to write, maintain and understand code written in Flux style than the code written in MVC fashion. So, I decided to rewrite the code of Shotem in Flux style.

At first, it didn’t seem to fit into Unity’s way of doing things. But I worked it out and coded it anyway. It worked fine, then I left the code alone.

Three months later I’m coming back to this project and I didn’t remember that I tested Flux style in it. At first I thought: “oh no, I’ll need to delete this project and start it over, why did I do it?” Then I did read the code and look at the project structure: I was amazed at how easy it was to get things back on track, I were able to get productive again in less than five minutes! What a pleasant surprise!

Now, I feel that I should share this with the rest of the world. I appreciate feedback, so if you feel that using Flux style in game development is madness or if you feel like giving it a try too, leave a comment.

From now on, I’ll use some terms from Flux, e.g. Store, Dispatcher, Action. I won’t explain what are their meanings, so feel free to take a little detour and read the official Facebook’s Flux website to get a summary of it.

I created a Dispatcher class to register the Stores, dispatch actions, track dependencies between Stores and ensure that the Actions do not cascade. The Dispatcher, in it’s full glory, is here:

using System;
using System.Collections.Generic;

using Shotem.Actions;

namespace Shotem.Flux {

    public class Dispatcher {
     
        private Dictionary<int, Store> stores;
        private HashSet<int> calledStores;
        private ShotemAction handlingAction;
        private int lastKey;
        private bool inDispatch;

        public Dispatcher() {
            stores = new Dictionary<int, Store>();
            calledStores = new HashSet<int>();
            handlingAction = null;
            lastKey = 0;
            inDispatch = false;
        }

        public int Register(Store store) {
            int key = lastKey + 1;
            stores.Add(key, store);
            lastKey = key;
            return key;
        }

        public void Dispatch(ShotemAction action) {
            if (inDispatch) {
                throw new Exception("double dispatch");
            }

            inDispatch = true;

            calledStores.Clear();
            handlingAction = action;
            foreach (int k in stores.Keys) {
                if (calledStores.Contains(k)) {
                    continue;
                }
                calledStores.Add(k);
                stores[k].Handle(action);
            }

            inDispatch = false;
        }

        public void WaitFor(int registrationKey) {
            if (!inDispatch) {
                throw new Exception("wait out of dispatch");
            }

            if (calledStores.Contains(registrationKey)) {
                return;
            }
            calledStores.Add(registrationKey);
            stores[registrationKey].Handle(handlingAction);
        }

    }

}

The core game mechanic is encoded in three Stores: CoinStore, handling all coins in the game; GunStore, handling player’s ammunition; ScoreStore, tracking user score.

Player input may dispatch two Actions in the game: ShootAction and ReloadGunAction. To handle the physics of the game (falling coins), one Action is sent every FixedUpdate: PhysicsUpdateAction.

The Stores handle each action according to simple rules:

PhysicsUpdateAction is handled by CoinStore by spawning new coins, moving the coins in the screen and removing coins that are off the screen. ScoreStore waits for the CoinStore to finish and then updates the score by decrementing the amount of coins that were removed from CoinStore, because they have fallen off the screen. GunStore ignores this action.

ShootAction is handled by GunStore by decrementing player’s ammunition. CoinStore waits for the GunStore and ignores the action if no ammunition was used, otherwise it checks for overlapping coins in the shot area and removes them. ScoreStore waits for GunStore and CoinStore then increases the score by each coin removed or decreases the score in case an ammunition was used and no coin was removed.

ReloadGunAction is handled by GunStore to reset the player’s ammunition to seven. CoinStore and ScoreStore ignores this action.

That’s the whole game logic. Each Store is observable, the Views register themselves to receive update notifications. When the Store handles an Action that changes its state, it triggers a notification. I’ve created an abstract class Store to handle this common behavior:

using Shotem.Actions;

namespace Shotem.Flux {

    public abstract class Store {

        public delegate void StoreObserver();

        public event StoreObserver Observers;

        protected void Notify() {
            if (Observers != null) {
                Observers();
            }
        }

        public abstract void Handle(ShotemAction action);

    }

}

The listing below is the code of ScoreStore, the other Stores follow the same style:

using Shotem.Flux;
using Shotem.Actions;

namespace Shotem.Stores {

    public class ScoreStore : Store {

        private Dispatcher dispatcher;
        private CoinStore coinStore;
        private GunStore gunStore;
        private int lastKnownCoinsCount;
        private int lastKnownCartridgesLeft;

        public ScoreStore(CoinStore coinStore, GunStore gunStore) {
            Score = 0;
            this.coinStore = coinStore;
            this.gunStore = gunStore;
            lastKnownCoinsCount = coinStore.Coins.Count;
            lastKnownCartridgesLeft = gunStore.CartridgesLeft;
        }

        public void RegisterAt(Dispatcher dispatcher) {
            this.dispatcher = dispatcher;
            dispatcher.Register(this);
        }

        public int Score { 
            get; 
            private set; 
        }

        public override void Handle(ShotemAction action) {
            dispatcher.WaitFor(coinStore.DispatcherIndex);
            dispatcher.WaitFor(gunStore.DispatcherIndex);
            int coinsDelta = lastKnownCoinsCount - coinStore.Coins.Count;
            int cartridgesDelta = lastKnownCartridgesLeft - gunStore.CartridgesLeft;
            lastKnownCoinsCount = coinStore.Coins.Count;
            lastKnownCartridgesLeft = gunStore.CartridgesLeft;

            switch (action.Type) {
                case ActionType.SHOOT:
                    // Add points for each coin that is destroyed with a shoot
                    // Remove a point if used a cartridge and did not hit a coin
                    if (coinsDelta > 0) {
                        Score += coinsDelta;
                    } else if (coinsDelta == 0 && cartridgesDelta > 0) {
                        Score -= 1;
                    }
                    break;

                case ActionType.PHYSICS_UPDATE:
                    // Remove points for each coin that is destroyed with a physics update
                    if (coinsDelta > 0) {
                        Score -= coinsDelta;
                    }
                    break;

                default:
                    return;
            }

            Notify();
        }

    }

}

Setup code is done in a Singleton GameObject’s Awake method, I called it StoreHub because I use this to get the reference to the Stores from other Views:

using UnityEngine;

using Shotem.Flux;
using Shotem.Stores;
using Shotem.Actions;

namespace Shotem.Views {

    public class StoreHub : MonoBehaviour {

        void Awake() {
            Dispatcher = new Dispatcher();

            GunStore = new GunStore();
            GunStore.RegisterAt(Dispatcher);

            CoinStore = new CoinStore(GunStore);
            CoinStore.RegisterAt(Dispatcher);

            ScoreStore = new ScoreStore(CoinStore, GunStore);
            ScoreStore.RegisterAt(Dispatcher);

            ActionGenerator = new ShotemActionGenerator(Dispatcher, CoinStore, GunStore, ScoreStore);
        }

        public Dispatcher Dispatcher { 
            get; 
            private set; 
        }
        
        public CoinStore CoinStore { 
            get; 
            private set; 
        }
        
        public ScoreStore ScoreStore { 
            get; 
            private set; 
        }
        
        public GunStore GunStore { 
            get; 
            private set; 
        }
        
        public ShotemActionGenerator ActionGenerator { 
            get; 
            private set; 
        }

    }

}

ShotemActionGenerator is a helper class to create Actions and send them to Dispatcher, nothing fancy.

The View classes are also simple, for example, the game may play three different sound effects when the GunStore is updated: when a bullet is shot, when user tries to shot without ammunition left and when the gun is reloaded:

using UnityEngine;

using System.Collections;

using Shotem.Flux;
using Shotem.Stores;

namespace Shotem.Views {

    public class GunSoundsView : MonoBehaviour {

        public AudioClip ShootClip;
        public AudioClip ReloadClip;
        public AudioClip EmptyGunClip;
        private GunStore gunStore;
        private int lastKnownCartridgesLeft;
        private AudioSource audioSource;

        void Start() {
            audioSource = GetComponent<AudioSource>();
            gunStore = FindObjectOfType<StoreHub>().GunStore;
            lastKnownCartridgesLeft = gunStore.CartridgesLeft;
            gunStore.Observers += OnGunStoreUpdate;
        }

        private void OnGunStoreUpdate() {
            int cartridgesLeft = gunStore.CartridgesLeft;
            if (cartridgesLeft == lastKnownCartridgesLeft && cartridgesLeft == 0) {
                audioSource.PlayOneShot(EmptyGunClip);
            } else if (cartridgesLeft < lastKnownCartridgesLeft) {
                audioSource.PlayOneShot(ShootClip);
            } else {
                audioSource.PlayOneShot(ReloadClip);
            }
            lastKnownCartridgesLeft = cartridgesLeft;
        }

    }

}

Another view shows the quantity of ammunition remaining, which are just children GameObjects with Renderers that I enable or disable based on the GunStore state:

using UnityEngine;

using Shotem.Flux;
using Shotem.Stores;

namespace Shotem.Views {

    public class CartridgesLeftView : MonoBehaviour {

        private GunStore gunStore;
        private Renderer[] bullets;

        void Start() {
            bullets = GetComponentsInChildren<Renderer>();
            gunStore = FindObjectOfType<StoreHub>().GunStore;
            gunStore.Observers += OnGunStoreUpdate;
            OnGunStoreUpdate();
        }

        private void OnGunStoreUpdate() {
            int cartridgesLeft = gunStore.CartridgesLeft;
            for (int i = 0; i < cartridgesLeft; ++i) {
            	bullets[i].enabled = true;
            }
            for (int i = cartridgesLeft; i < bullets.Length; ++i) {
            	bullets[i].enabled = false;
            }
        }

    }

}

There is a View to show the score, one to show a tip to remind the player to reload the gun when it’s empty, another to handle the renderers of each coin visible in the screen, etc. The entire game is made in the same solid base, or may I say “solid flux“. Data always flows in a single direction without cascading, there is always an Action that enters the system and triggers something, nothing happens if no Action is dispatched.

I don’t know if this design can scale to a big game project, as the style as it is now depends on it running in a single core. But, none of my games are that intense, so I will try to finish this game with Flux. I guess that using Flux will also make it easier to create automated tests of the game mechanic, as it is self-contained. Maybe I’ll post some follow up thoughts on it.

Below is an overview image of the current flux of the game. I decided to call “Inception” the layer that generates the Actions, Flux do not give it a name.

Thanks for your time,

C, C++, Java, Haskell?

I’m excited and distressed with my OpenGL adventure. At the same time that learning OpenGL makes me pleased, it also makes me irritated: I’ve dedicated much time learning Haskell and got involved in a way to really like the language and the community. But, doing something in OpenGL was very hard and lonely. There are very few content about it and the majority are already obsolete.

I did put Haskell at the corner for some time and refreshed my C knowledge to learn modern OpenGL, with shaders and buffer objects. The reason was simple: I didn’t manage to do anything in Haskell that actually worked and had no clue if the problem was with my code or with the libraries I was using.

Well, to make a moving camera in a 3D world was difficult, even in C. But, I’ve found lots of good stuff on the internet to help me do it. Using all this help, I’ve managed to make it work.

I’ve decided to get back to Haskell to apply this knowledge I just got.

Oh dear! To make everything fit together and with the right types made me sweat some t-shirts. If I wasn’t so stubborn, I wouldn’t do it. I’ve switched OpenGL by OpenGLRaw because the OpenGL package has no binding for “glUniformMatrix*”; also switched GLFW by GLFW-b because the first one has a dependency with OpenGL package.

I read a post at InfoQ asking if the C language was still suitable. Made me think on lots of stuff, including on to abandon Haskell and get back to pointers, manual memory management, hairy strings, …

Perhaps it’s because I’m new to this world, but I feel kind of unproductive while programming in Haskell. My impression is that, unless it’s something very well consolidated and used by lots of community members, a lot of time will be spent going after libraries that usually are just a binding for one written in C. When that’s not the case, just to take a breath of the library’s API, I need to read some papers trying to remember all the magic about Functors and Monads (I think I’ll need some books to really understand Arrows!).

To understand pointers and memory management in C was difficult too. But back then I was a young boy at the world of programming, my knowledge was very limited, it was based a lot on punching the code until it did what I wanted. I can’t accept this anymore, I need to understand what I’m doing.

I remember I had good reasons to change C for Java. After a while using Java, I started to see the cons of the language too. My undergraduate work was dedicated to point the reasons of this change and the promising future of languages like Haskell.

I believe that this negative feeling happens with every language that you spend some time learning. The propaganda and the first steps are wonderful. You imagine a new world where everyone is rich and can enjoy all the beauties of life. With time, you realize that it’s not like that: every decision the language has made means positive and negative points to us, programmers. I’ve experienced this with C, Python, Java and now with Haskell.

Java has chosen the O.O. way: even if it’s a static function or a global variable, the class wrap will be there. Haskell picked the pure functional way: even I/O operations are wrapped within a monad.

This is not bad at all. The use of monads to model sequential computation was a great discovery that led to a lot of other solutions. All the choices made brings with them some pros and some cons. (Just take caution with the extremism [e.g. Singleton].)

I’m distressed because I don’t know what to pick:

  • C looks flexible but with complexities I’m not wishing to have. C11 may have fixed some (e.g. ), but GCC has no support for it yet;
  • I feel productive in Java but the inherent overhead and the need of a JVM makes me angry;
  • C++ I don’t know well, but I think I’d prefer going into C than this one. Java has shown me good reasons to say no to O.O. But, even GCC is using C++, maybe I’m missing something. The libraries for C++ looks great (e.g. GLM, Boost);
  • Haskell is my favorite, but it’s starting to bother me little, this feeling of being stuck, without delivering anything, makes me tense. Maybe I need to give some more time for it to really kick in. I don’t know if this commitment will worth it or I could make a better use of it enhancing my skills in another language.

The performance difference between C and Haskell don’t bother me much, because I’m not going to do micro-optimizations so early.

The ultimate answer is something like: it depends on your project, choose the right language for the right project. Well, I have no project at all, but I want to get deeper into game development.

What should I do?