For those that aren't sure, Hack is a programming language developed by Facebook for HHVM that interoperable seamlessly with PHP and aims to add discipline into your code.

Hack PHP Language in HHVM by Facebook

Hack reconciles the fast development cycle of PHP with the discipline provided by static typing found in languages such as Java, while adding many features commonly found in other modern programming languages. Hack is currently used in production on Facebook after a long thorough process of refactoring their codebase.

This is the first of a two part series of blog articles, next time we will look more in depth at the power behind Hack and a lot more programming examples. But to start off with, we need a feel for what Hack is how it'll help your programming style and the benefits of using Hack.

So what makes Hack different?

Every PHP programmer is more than familiar with the day-to-day irritants that simple tasks can cause, often tackling the problem of how to best handle unexpected responses that trigger runtime errors where you're expecting a certain result but may in fact get something completely different. A pain, right?

There are plenty of other languages that are more than capable of detecting this sort of problem but as PHP is only compiled at run time and then interpreted on-the-fly, there was no way to detect potentially problematic chunks of code that may cause a runtime error and throw your application off. As pointed out by the Facebook Engineering team, this is particularly apparent in the life cycle of rapid iteration development spread across a large team where sections of code may be constantly changing.

Hack is a statically typed language meaning you need to provide a type for all of the variables declared in the application. Whilst PHP is a dynamically typed language meaning you don't need to specify any types although you are able to using type hinting on method arguments.

function increment(int $x): int {
  return $x + 1;
}
/**
 * Calling increment_array([0,1]) would return a new array [1,2]
 * whilst calling increment_array([0, '1']) will throw an error
 * as we're expecting an array of integers.
*/
function increment_array(array<int> $a): array {
  array_walk($a, 'increment');
  return $a;
}

If you're mid-way through the development of a large project and you're dreading having to go through all of your existing code - don't worry, Hack is quite generous, for now. 

To help you migrate your projects over to Hack, you can use the "gradual typing" so that you can slowly introduce them throughout your code. This means if your code doesn't have the type specified, it'll be treated as a regular dynamic type PHP variable.

How to Turn on Strict Type Checking

If you're feeling up to the task of adding type checking onto your existing code or you're starting up fresh, you can change the Hack opening tag so that all of your variables, functions and return values are checked.

// Regular start tag, we don't need a closing tag
<?hh
// To turn on strict type checking 
<?hh //strict

Once you're in strict mode, you don't need to be concerned about type hinting all of your variables.

Hack is built with a huge volume of inference logic that means local variable types can be determined by the interpreter and handled for you. Though this does mean you can't use polymorphism on your variables. Just because they can be inferred doesn't mean not to put them in. If it'll help you in the long-run, add them so you remember exactly what variable does what through your application life-cycle.

In strict mode you'll need to add type hinting on class variables, method arguments and return values.

Catching Type Errors in Hack

The HHVM runtime checker is extremely efficient such that it doesn't affect your performance but in a fact does the opposite. It achieves this by checking your code, if and only when it is called. If you've got a recursive nested object, it'll check the type checking at the deepest level, it won't iterate over your objects and validate each one.

So if you're left wondering whether you should in fact port over to Hack yet, the answer is most probably no. For now.

Hack is great as it lets you specifying your own type checking, overriding or defaulting to type checking on inherited classes, integration with XHP!

<?hh
class BaseClass {
  public function getUser(): MyUser {
    return new MyUser();
  }
}
class MyDerivedClass extends BaseClass {
  /* <<Override>> is used to specify that get_user has been inherited.
   * When that's not the case, Hack gives an error.
   */
  <<Override>> public function getUser(): MyUser {
    return new MyUser();
  }
  /* XHP is useful to build html (or xml) elements.
   * The escaping is done automatically, it is important to avoid
   * security issues (XSS attacks).
   */
  private function outputParagraph(string $text, string $style): :div {
    return
      <div style={$style}>
        <p>{$text}</p>
      </div>;
  }
  /**
   * We can take a function as the type and state what it should expect.
   * This allows us to use the PHP callable functions.
   */
  private function updateUserTime<T>((function(int): T) $callback, int $value): T {
    return $callback($value);
  }
}

Like any programming language, it is only as good as the editors and tools you use to code them. Without a doubt Facebook will have put together a real-time interpreter into an editor that will allow you to validate your code and type checking as you code, but sadly there have been no details on this yet.

A type checker is normally implemented as part of the server side platform and we should expect to see it in future HHVM releases. It works by monitoring your codebase for changes. When a change is detected, it'll scan the modified file and all its dependencies for any errors. This allows you to see a report of any errors as you're coding.

What Makes Hack Great?

If you're still unsure on the benefits of Hack, you have to remind yourself that it has been developed by the engineers and developers of Facebook. That is, performance and production on a huge scale has always been key. You'll be working with a language that you know is easy to integrate into a rapid development environment.

Another great benefit to using Hack is that it'll aid you to produce more efficient code that has a reduced memory footprint. In PHP, if you've got a simple function that takes two parameters and adds this, the PHP interpreter will have to check the types of both parameters, determine what they are and then convert them into integers. Whereas with Hack, you'd already of specified the type we are expecting so the interpreter already understands what it is working with and doesn't have to do any post-processing. When passed down to the HHVM JIT, it'll convert our code into assembly language and get the job done - at some remarkable speed too.

Next time we'll dive into some advanced programming tutorials, looking at the more complex functionality of Hack, XHP, Asynchronous requests and the integration with Nginx and FastCGI.

28
Ignite your brand, utilise user-generated content no matter where you or your audience are ›