Posts tagged with best practices

Normalize your values on input

Sebastian De Deyne on his blog:

Dynamic languages allow us to pass anything as a parameter without requiring a specific type. In turn, this means we often need to handle some extra validation for the data that comes in to our objects.

This is a lightweight post on handling your incoming values effectively by normalizing them as soon as possible. It's a simple guideline worth keeping in mind which will help you keep your code easier to reason about.

https://sebastiandedeyne.com/posts/2016/normalize-your-values-on-input

Read more

Commands, events, global functions and testing

Tony Messias on the madewithlove-blog:

The other day I was listening to the FullStackRadio episode 34 which is about dealing with dependencies in Active Record models. This is a very interesting topic and they suggest a few solutions for it. I liked the suggestions and I tried to implement it differently (first try and second try).

After that, I decided to talk to my colleagues about the design implementations. And they asked “why not implementing it as a command?”. At first sight I was a bit reluctant, because I’m starting to think applications are getting more complex then it really needs. Then I decided to implement it and the end result was the best one to us. Let’s discuss it a bit.

http://blog.madewithlove.be/post/commands-events-global-functions-and-testing/

Read more

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Code Golf

When starting out programming many developers are quite happy when their code just works. More seasoned programmers know that making working code is just a first step. Not improving your initial code will lead to professional suicide (not my phrasing, I'm sure I've read this in a book at some point).

In an article on his blog, Colin DeCarlo demonstrates how an initial solution can be vastly improved in just a few iterations.

From time to time a friend and I play a programming game that I consider to be a version of Code Golf. Typically, the goal of Code Golf is to solve some challenge using as little bytes as possible. In the version of the game we play however, the limitation is the use of certain language features. Specifically, we try to use as little variables, conditionals and explicit loops as possible.

...

My method to accomplishing these challenges is to first write the algorithm in the simplest, most straight forward manner and then chip away at that solution until I’ve satisfied the challenge conditions.

The focus in the article is on removing conditionals, and limiting the use of variables. Keep in mind that, in most cases, this shouldn't be your main goal. Maximizing the readabilty is what your should pursue. Don't try to be too clever or terse. In some cases limiting conditionals and variables goes hand in hand with improving readability, in other cases not. It all depends on context.

Read more

Handling composers "lock file out of date" warning

Lorna Jane Mitchell explains on her blog which options you have when you see "lock file out of date" warning.

The `composer.lock` also includes a hash of the current `composer.json` when it updates, so you can always tell if you've added a requirement to the `composer.json` file and forgotten to install it.

In that case, you'll see an error message like:

Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.

You now have three options: upgrade everything, figure it out, or do nothing.

http://www.lornajane.net/posts/2016/handling-composer-lock-file-out-of-date-warning

Read more

Messages in PHP

Matthias Noback continues his highly interesting series of posts with programming guidelines. Part four is about messages.

Besides having a type and a particular value, messages can also be categorized:
  • A command message is a request for change. One object wants to make the other object do something.
  • A query message is a request for information. One object wants to get something from the other object.
  • A document message is the response from the other object, based on the query that was sent to it.
https://www.ibuildings.nl/blog/2016/02/programming-guidelines-part-4-messages

Read more

What do you name the callback function?

Derick Bailey on his blog:

JavaScript practically requires callback functions to do anything asynchronous. Unless you’re talking about generators, you really can’t get away from them. Callbacks are everywhere.

...

I do use different names for the callback parameter, depending on the circumstance. I believe naming is important as it provides a set of expectations. If your code breaks the expectations of the name, people will be confused and it will cause problems.

http://derickbailey.com/2016/02/15/what-do-you-name-the-callback-function/

Read more

Automatically test the quality of your code on commit

A few days ago Toon Verwerft gave an uncon talk at PHP Benelux Conference about a new code quality checking tool he has been developing. It's called GrumPHP. It can automatically perform various code quality checks when you try to commit some code.

Sick and tired of defending code quality over and over again? GrumPHP will do it for you! This composer plugin will register some git hooks in your package repository. When somebody commits changes, GrumPHP will run some tests on the committed code. If the tests fail, you won't be able to commit your changes. This handy tool will not only improve your codebase, it will also teach your co-workers to write better code following the best practices you've determined as a team.
https://github.com/phpro/grumphp

The slides of Toon's talk can be found on speakerdeck.

Read more

Getting rid of null

Matthias Noback published the second article in his programming guidelines series. This time he explains why using null in a function isn't a good idea. In my opinion it's great advice that most devs can immediately apply in their projects.

It's certainly a good idea to get rid of the uncertainty and vagueness that null brings to your code. Besides, most of the time when you encounter an actual null value in your program, you probably weren't expecting it. You just call a method on it, thinking that it is an object and PHP will rightfully let your program crash.

...

Every particular null situation requires a different solution, but at least I'll list several common solutions for you.

https://www.ibuildings.nl/blog/2016/01/programming-guidelines-php-developers-part-2-getting-rid-null

Read more

Video and slides of the 3th PHP Antwerp meetup

Yesterday our local user group, PHP Antwerp, held it's third meetup. There were two excellent speakers and a bunch of familiar faces.

Gabriel Somoza

First up was Gabriel Somoza who talked about his project Baleen. It's goal is to provide an intuitive framework to migrate almost anything. You can view his slides on Speakerdeck.

The second speaker was Marco Pivetta, better known on the interwebs as Ocramius. He is a member of the Doctrine core team. His talk was about best practices when using Doctrine. His slides can be found on GitHub. Here's the video of the talk:

https://youtu.be/j4nS_dGxxs8?t=6m44s

Spatie, of which I'm a partner, sponsored the meetup. Before Marco's talk I got the opportunity to talk a bit myself about why my company is sponsoring the local user group. My short talk can be viewed on YouTube.

The organisers announced that the next meetup will be held at the end of March. If you're living in the vicinity of Antwerp, you should definitely attend.

Read more

Writing your own test doubles

Adam Wathan posted another excellent article on testing on his blog. This time he talks about creating test doubles. Adam demonstrates that creating your own fake can result in a much more readable test than using mocks or spies.

You'll learn to create an InMemoryMailer like this:

public function test_new_users_are_sent_a_welcome_email()
{
    $mailer = new InMemoryMailer;
    Mail::swap($mailer);

    $this->post('register', [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => 'secret',
    ]);

    $this->assertTrue($mailer->hasMessageFor('john@example.com'));
    $this->assertTrue($mailer->hasMessageWithSubject('Welcome to my app!'));
}

That seems like a pretty readable test to me. Read (or view) the whole tutorial here: http://adamwathan.me/2016/01/25/writing-your-own-test-doubles/

Read more

The wrong abstraction

Sandi Metz on her blog:

If you find yourself passing parameters and adding conditional paths through shared code, the abstraction is incorrect. It may have been right to begin with, but that day has passed. Once an abstraction is proved wrong the best strategy is to re-introduce duplication and let it show you what's right. Although it occasionally makes sense to accumulate a few conditionals to gain insight into what's going on, you'll suffer less pain if you abandon the wrong abstraction sooner rather than later.
http://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction

Read more

Reducing complexity

Matthias Noback, author of "Principles of Package Design", published the first article in a new series on programming best practices on the iBuildings blog. The subject of the first article is reducing complexity.

Inside your method or function bodies, reduce complexity as much as possible. A lower complexity leads to a lower mental burden for anyone who reads the code. Therefore, it will also reduce the number of misunderstandings about how the code works, how it can be modified, or how it should be fixed.
https://www.ibuildings.nl/blog/2016/01/programming-guidelines-php-developers-part-1-reducing-complexity

Read more

How to become a great engineer

Philip Walton, an engineer at Google, wrote a wonderful article that every developer should read. He talks about front-end engineers, but most tips are applicable to back-end engineers as well. A few quotes:

Taking the time to figure out why your hack works may seem costly now, but I promise it’ll save you time in the future. Having a fuller understanding of the systems you’re working within will mean less guess-and-check work going forward.
Solving problems on your own is a great way to learn, but if that’s all you ever do, you’ll plateau pretty quickly. Reading other people’s code opens your mind to new ways of doing things.
In my experience, writing, giving talks, and creating demos has been one of the best ways to force myself to dive in and fully understand something, inside and out. Even if no one ever reads what you write, the process of doing it is more than worth it.
Be sure to read the full article here: http://philipwalton.com/articles/how-to-become-a-great-front-end-engineer/

Read more

Converting big PHP codebases to PSR-2

It is known by now that every codebase large enough (in terms of lines of code or people collaborating to it) should follow any code standard. Here at Coolblue we weren’t different and were using our own coding standard.

But codebases evolve. And our codebase – that has been supporting one of the most visited ecommerces in The Netherlands – needed to be upgraded to a coding standard that’s a little bit more up to date.

This is the process we follow to move into PSR-2.

http://devblog.coolblue.nl/tech/converting-big-php-codebases-to-psr2/

In the past months we converted several of our old projects to PSR-2 with Fabien Potencier's coding standards fixer and had zero issues doing so. Hurray for standardized code.

 

Read more

What web developers should know about SSL but probably don't

In 2015 web developers understand more about SSL than they ever have. If you read Hacker News you should know: What about the rest?
https://certsimple.com/blog/obsolete-cipher-suite-and-things-web-developers-should-know-about-ssl

Read more

Fake the PHP version when running Composer

Mr. Composer, Jordi Boggiano, has posted an overview of composer features that have become available in the past year. A very nice one is config.platform.

The `config.platform` option lets you emulate which platform packages you have available on your prod environment. That way even if you have a more recent PHP version or are missing an extension locally for example, composer will always resolve packages assuming that you have the packages you declared installed.
That'll come in handy when you have a local php 7 environment and an older version installed on the server.

Read more

Making call_user_func_array more readable

There's a lot PHP 7 love going around these days, but PHP 5.6 has it's fair share of nice features too. One of those features is the splat operator. It looks like this: ....

The splat operator can capture a variable number of arguments.

function logThis(...$messages)
{
    foreach ($messages as $message) {
        echo $message.PHP_EOL;
    }
}

logThis('one', 'two', 'three');

You can still use regular arguments as well:

function logThis($firstMessage, ...$otherMessages)
{
    echo "superimportant: {$firstMessage}".PHP_EOL;

    foreach ($otherMessages as $message) {
        echo $message.PHP_EOL;
    }
}

logThis('one', 'two', 'three');

Another usage for the splat operator is argument unpacking:

$messages[] = "one";
$messages[] = "two";
$messages[] = "three";

logThis(...$messages);

The operator can also help replacing usages of call_user_func_array to something more readable. Consider this contrived example where all calls to a class are forwarded to a dependency.

class ClassA
{
    protected $classB;

    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }

    public function __call($method, $args)
    {
        call_user_func_array([$this->classB, $method], $args);
    }
}

Using this splat operator this can be rewritten to:

class ClassA
{
    protected $classB;

    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }

    public function __call($method, $args)
    {
        $this->classB->$method(...$args);
    }
}

Do you know some other cool usage of the operator? Let me know in the comments below.

Read more

A better way to style the output of console commands

When creating output from a Symfony based console command you might have created a title using code like this:

$output->writeln('');
$output->writeln('<info>Lorem Ipsum Dolor Sit Amet</>');
$output->writeln('<info>==========================</>');
$output->writeln('');

Starting from Symfony 2.7 there's a nice way to style the output of console commands. This code produces the same output as the example above

$io = new SymfonyStyle($input, $output)
$io->title('Lorem Ipsum Dolor Sit Amet');

There are styles for titles, sections, questions, tables, and so on. Take a look at the documention to learn what's possible.

Read more