Pages

Friday, October 31, 2014

How does Hacklang work

I must admit that I am not a fan of Facebook. Unlike 90% of the world, I do not, and have no intention of, ever owning an account. The list of reasons are long, and some of the things on that list have more to do with the people using it, rather than the service itself. Something just happens to normal people when entering the website, it's like watching one of the many talk-shows and reality programs on TV.

But although this article is about Facebook, it is not about the service that they are most famous for. This article is about a small extension to the PHP programming language, created by Facebook, called Hack, and the related Virtual Machine called HHVM. If you are a PHP programmer and either do not know about this or if you have not yet tried it, then I'll suggest you have a look at it. This extension provides features that PHP should have had ages ago. This article will not get into what Hack and HHVM is, I'll suggest that you visit the website http://hhvm.com if you are not already familiar with it.

What this article will focus on, is how HHVM/Hack acts. PHP is normally a dynamic typed language, but Hack introduces static typed features, and at the same time keeps compatibility with regular PHP. It's like mixing oil and water, and actually making them mix. The way it works, is that the VM mostly upholds the rules of PHP while the type checker upholds the rules of Hack. In other words, you can without any issues execute code that is not acceptable by the rules of static typing, but you will get errors when parsing it through the optional type checker. The errors from the type checker can also be removed by changing how strict it should be, which can be set pr. file. This allows you to mix dynamic typing and static typing, and still be able to use the type checker on the strict files.

class MyClass {
    public function test1(): void {
        $this->internal( Map{"key"=>1} );
    }

    public function test2(): void {
        $this->internal( Vector{true} );
    }

    private function internal(Map<string, bool> $param): void {
        // Code ...
    }
}

If we execute test1() from a browser, HHVM would not generate any errors. It would simply allow it. If we execute test2(), HHVM would break the request with an error. The reason for this is that HHVM follows PHP rules, which does not provide any generics. PHP however does allow one to define parameter type, which is the only thing that is being monitored for. The type checker on the other hand, would print a lot of errors here, first complaining about the wrong generics types in test1() and then complain about the wrong data type in test2().

class MyClass {
    public function test(): bool {
        return 1;
    }
}

The same applies for the return type. The above example will not conflict with HHVM. The only way to catch this problem, is by the type checker.

So the way that Hack is able to work along side PHP, is that the VM does not enforce any Hack rules. If you want to check your code for type safety, you will have to check it using the type checker. For the most part this will suffice. But the type checker is still a work in progress, and it does contain a few bugs.

class MyClass {
    public function test1(): void {
        $this->internal(Map{"key"=>new Map(array(
            "key"=>1
        ))});
    }

    public function test2(): void {
        $this->internal(Map{"key"=>Map{
            "key"=>1
        }});
    }

    private function internal(Map<string, Map<string, string>> $param): void {
        // Code ...
    }
}

Both test1() and test2() will parse the exact same value to internal(). However the type checker will only report an error on test2(). The wrong generics type in test1() will not be caught.

Thursday, October 30, 2014

PHP Traits extends OOP posibilities

OOP if a wonderful concept in programming. People have different opinions about it, but I for one love it. First of all you have all of your work divided into groups (Classes), and adding other concepts like namespaces or packages, your classes becomes sub-groups in even larger groups. It makes it easy to keep track of your work in large code bases, and it reduces the chance of things colliding, especially in environments where 3'rd party code can be added dynamically (E.g. CMS modules for an example). It also allows classes to share code with one another. If you want to create a class that adds functionally to an existing class, you can extend from that class, and adopt the already existing code into your new class. Then all you have to do, is change and/or add whatever you had in mind, without having to copy/paste the content of one class into another. At the same time, adding to and/or fixing something the first class, will automatically be appended to the second one.

But OOP does have it's limitations. For one, you can only extend from one class. So if you want to adopt code from two classes, you are out of luck. You can of course implement as many interfaces as you'd like, but interfaces only defines the structure of a class, and does not provide any pre-done work. This has now changed in PHP with the introduction of Traits since version 5.4. A Trait is something like an abstract class, the difference being that you do not extend from it, instead you sort of includes it's content within your class. It can somewhat be compared to extending objects in JavaScript via the prototype property, and you can include as many Traits as you'd like.

trait Snipped1 {
    public static function printMessage() {
        echo "Prints a text!";
    }
}

trait Snipped2 {}

class Example {
    use Snipped1, Snipped2;
}

Example::printMessage();

The class above will contain all the content from both Traits. Also unlike when extending two classes, all static content in Traits, like static properties, will have their own instance pr. class that uses them. So changing the value of an static Trait property from one class, will not change the value in other class, using the same Trait.

One thing that Traits does not do, is parse their type to classes using them. Content that you include from a Trait, will be treated as if it belongs to the class itself. This means that you can't use something like instanceof to check whether or not a class uses a Trait. There are ways to check, but these ways are slow and not very handy. And there is nothing wrong with this, it is meant to work this way, because classes does not implement or inherit from Traits, they simply copy/paste their content.

Personally I did not find Traits very useful at the beginning, mostly because if they are used wrong, they can create a lot of chaos in your code. Much more than chaotic inheritance. But after playing around with them, I found that they can be handy if you include interfaces. By using an interface to define a class structure and then add a Trait with some partial code, you will have what can be considered an abstract class divided into two parts. One containing the partial code and one containing the details about how a class should look.

interface ISnipped {
    public function printMessage();
    public function secondMethod();
}

trait Snipped {
    public function printMessage() {
        echo "Prints a text!";
    }
}

class Example implements ISnipped {
    use Snipped;

    public function secondMethod() {
        // Do something
    }
}

$example = new Example();

if ($example instanceof ISnipped) {
    $example->printMessage();
}

The above example can be compared to the example below
public abstract class Snipped {
    public function printMessage() {
        echo "Prints a text!";
    }

    public abstract function secondMethod();
}

class Example extends Snipped {
    public function secondMethod() {
        // Do something
    }
}

$example = new Example();

if ($example instanceof Snipped) {
    $example->printMessage();
}

Both examples provide much the same structure, but using Traits we can adopt from more than one. All we have to do, is implement more interfaces and add more traits.

Monday, October 27, 2014

Wordpress

A while ago, I was hired to extend a web site for a small company. The web site had been build by one of their graphics designers, who did not normally work with programming. As a result, this site had been built using Wordpress, because this was the easiest system for this non-programmer to start with, while he at the same time had to learn the basics of HTML, CSS and PHP. The custom work that he had done was not the best, but still quite impressive considering the time frame and the fact that he did not know anything about coding when he started. But this article is not about designers turning programmers. It is a small overview of Wordpress, and about some of the reasons why I would never build anything with in, unless I am forced to.

Starting on this site, I did not know anything about Wordpress. All that I knew was that it used to be a small blog system, which apparently had grown larger over time. I started reading some of the documentation, and it did seam like something worth looking into. I especially liked the idea of their action and filter callbacks. However, once I got started, I became less impressed.

First of all Wordpress is missing a lot of rules. Sure they have their Plugin.php file, but there is no rules as to what this file should contain. If you compare it to Drupal, which have a module file containing hooks with strict naming schemes, Wordpress introduces the same policy as PHP, where no standard for anything exist. Now I do like PHP, but it would be a lot better, if they implemented parts of Hack into it. Static Typing for one.

Their plugin system is also very minimal. If you need to add some additional tings to the existing blog system, then this is fine. But if you need to add some extensive work into Wordpress, you will need to integrate this directly into the "Theme" files. Also while talking about the Theme files, I think that the people behind Wordpress has misunderstood the word "Theme". These files actually makes up most of the system. They work as bootstrap of some sort, they contain a lot of the site logic as well as the Themes. All in all, they act much like MVC wrapped into one single "Theme" file.

The worst part of Wordpress, some of which was mentioned above, is their action and filers system. The idea is great, but it is extremely pure designed. This is the part that would have benefited the most by some stricter rules. One of the things that one should avoid when working with PHP, is their dynamic caller functions "call_user_func" and "call_user_func_array". Requests that normally takes nanoseconds to load, will take milliseconds and sometimes seconds, when introduced to the above functions. And this is only by a few calls pr. request. Wordpress has integrated this into the entire core of the system. Even before the initialization is done, these functions has been called numerous times. After that, even more calls is done by more of Wordpress's functions, by themes and by plugins. Depending on what you have installed and enabled, you can end up in 3 digit calls to these extremely slow functions. This is the worst design that I have ever seen in any framework for any language, and I cannot stop thinking about those poor CPU's that has to process all of this unnecessary code.

A better design would have been to implement either a strict procedural design, allowing only functions to be parsed, which can be executed without any additional resources. Or implement a strict OOP design by using interfaces, much like how callbacks works in Android.

If you just need a small blog site with few visitors and if you hate your server, then by all means, use Wordpress. But if you want a serious site with many visitors, if you love your server and if you'd like to have some nice coding standards, I would suggest using another CMS or build one using one of the many frameworks available. Wordpress is a mess, there is no standards of any kind, most of your work will have to be implemented using different hacks to work properly and it will rape your server daily.

Thursday, October 9, 2014

Microsoft Windows? Why?

I have not been a Windows user since XP was the new big thing, and even before that time, I was not a big fan of Windows. Why? Well Windows have always had a thing where it was trying to push every single one of my buttons, which often resulted in hardware pieces (Mouse, Keyboard, Monitors, etc.) being thrown across a room. This ended up becoming to expensive, and I decided to give Linux a try instead, which have saved me a lot on hardware purchases.

But living in a Microsoft world while being the guy known to have IT knowledge, it is not so easy to get rid of Windows 100%, although you might not use it at home. Once in awhile, people you know will come to you with their Windows problems. Most of the time I tell them to use a system that I want to support, if they require me to do so. I did not switch away from my Windows problems just to take on every one else's.

But for some reason I did not say no when I friend of mine came to me to get help formatting he's laptop. I thought that since Windows is now at version 8, a lot must have changed since the old XP. A quick format and a few driver installs would properly not take up to much of my time, especially since all the drivers was stored on a USB pen drive. But just as I remember it, things are never that easy with Windows. The installation went fine, the newly installed Windows booted without issues, only a few driver installs remained. I plugged-in the USB pen drive and opened 'My Computer', just like I would do on my Linux machines, which takes about half a second to load USB devices. But Windows did not load it, instead it pops up with a small yellow driver install notification in the button right corner? Well okay. But then it fails to locate a driver? A simple UNIVERSAL Mass Storage device with a Microsoft msdos partition table containing a Microsoft Fat32 file system, fails to load on a brand new Microsoft Windows 8 operating system?

I plugged-in the USB pen drive into my own laptop, running on Fedora 20, and my file manager opened right away, displaying the content of the drive. Now which of these operating system is known for being so user friendly?

I cannot specify how I managed to get this drive working. I spent about an hour playing around in the control panel, unloading/loading drivers, plug/unplugging the USB pen drive, trouble shooting and much more. Finally at some point, for some reason, it started working. But I would really not call this user friendly, especially since this is just one small example of the many issues one will stumble upon, when working with Windows. This operating system takes to much of once time on ridicules tasks like this and it increases your blood pressure to a very dangerous level. Why people keep insisting on using it, I really don't know. I find *nix systems like Linux, OSX and such, much more friendly to work with. Use those and you might even live longer.

Wednesday, February 12, 2014

Android Resources

This is not a guide or an article. It is mainly an observation that I can no longer ignorer. The issue is that most Android developers have a habit of working out custom solutions using the few tools that they know, rather than looking to see if Android has a pee-built tool for that specific task.

In this case, the issue is regarding Android's Resources class. Let's say that we want to create a dynamic string using placeholders. If you try to google this, you will mostly find the same solution on each page that you visit. I have written this solution below.

<resources>
    <string name="dynamic_string">Let\'s insert the number %1$d</string>
</resources>

Integer numberToInsert = 1;
String dynamicString = String.format( getResources().getString(R.string.welcome_messages), numberToInsert );

The problem here is that there is no point in including String.format into this, because Resources.getString is already able to do this for you.

Integer numberToInsert = 1;
String dynamicString = getResources().getString(R.string.welcome_messages, numberToInsert );

If you took a look at the documentation for this method, you would see that it does not only take [String] as an argument. It actually takes [String, Object...], where each Object parsed will be used to replace the placeholders of the string.

Please have a look at the Resources Documentation. This class contains a lot of useful tools for when working with the resources in Android. Many of which is not seen being used very much, if even at all.