Je suis développeur web freelance et propose des formations à Symfony2 ! Contactez-moi pour en discuter.

Many languages feature “optional” parameters to function arguments: if you provide a value, it will be used, but if you don’t, a default value will be used instead.

Let’s take a look in python:

def some_function(a = 4):
    print(a * a)

some_function(3)
some_function()

In the previous example, we can provide if we want a to some_function. If we don’t, 4 will be used. some_function will have a value to use for a no matter what

How to do that in Rust? Well, in Rust you have to provide all the parameters a function requests. You can, however, use “Option”s to do two things:

  • make their usage not mandatory
  • provide a default value

The non mandatory behavior is what you are already doing often if you are using Options.

fn optional_value(optional_arg: Option<u32>) {
    if let Some(value) = optional_arg {
        println!("{} = {}", value, value*value);
    }
    else {
        println!("No value is supplied, we won't compute the square");
    }
}

fn main(){        
    optional_value(Some(4));
    optional_value(None);
}

If a value is provided inside optional_arg, we do something out of it, otherwise we do something else like displaying an error message.

Default values are also easy thanks to unwrap_or:

fn default_value(some_param: Option<u32>) {
    let some_param = some_param.unwrap_or(23);
    println!("The optional parameter is {}", some_param);
}

fn main(){
    default_value(Some(4));
    default_value(None);
}

In the defaut_value function, if Some is provided with a value inside, we unwrap and use it, but if None is provided, we replace the content of some_param with a default value using unwrap_or

Another cool trick is to make the parameter a generic over Into<Option<i32>>.

When you do so, you get to call the function with a value (instead of Some(value)) or with None, and then you can

fn optional_with_into<T: Into<Option<i32>>>(value: T) {
    let value = value.into(); // now we have an option
    // then we get to unwrap our option
    match value {
        Some(value) => println!("{} = {}", value, value*value),
        None => println!("No value is supplied, we won't compute the square"),
    }
}

fn main(){
    optional_with_into(4);
    optional_with_into(None);
}

(this is possible because Option itself implements the From trait)

Our course you can also use the unwrap_or in order to provide a default value if None is provided. Don’t forget the call to into !

fn optional_with_default_with_into<T: Into<Option<i32>>>(value: T) {
    let value = value.into().unwrap_or(4);
    // …
}

That being said, the ergonomics for default values is far from perfect.

The Vasa was a Swedish warship built between 1625 and 1628. After multiple defeats in the early 1620s, it was supposed to embody the renewal of the Swedish navy and to show the strength of the country. It did not have the opportunity to shine much though: it drowned less than 5 minutes after its first launch. During the maiden voyage, there was little wind, but it was enough to knock it over. Water poured in, and it sank 32m deep, 120m away from the shore. It stayed in Stockholm’s harbor for 333 years. The wreck was found in good shape in the early 1950s since it merely, calmly, sank without prior damage.

The Vasa, Klaus Stiefel

So what went wrong? There were a few problems.

  • The first one was its client, King Gustav II of Sweden. He gave specifications (dimensions, number of cannons, etc.), while he was no expert. It was the job of the entrepreneur to make a realistic boat, not to accept anything the client asked.
  • he compressed the deadlines, pressured the constructor into delivering faster, and went to the building site only once.
  • he was the king, which made him hard to contradict.

The king was not the only problem though.

  • many of the specifications were not writen.
  • Critical specs changed over time. The king ordered 72 cannons for the ship, but this was too many to fit on a single gun deck. Since the order was issued less than five months after construction started, it was still time to add a second gundeck.
  • the ship was not well balanced because the builders lacked experience building such big ships: until then, Swedish warships only had one gundeck.
  • one of the builders died before the end (see the problem with non-written specs here?).
  • warnings were ignored. There was a rehearsal a bit before the launch, intending to show the stability of the boat. But soon, the ship started to capsize, because there was too much weigh in the high decks. The vice admiral stopped the exercise and… did nothing more to cancel or delay the launch, since he did not want to contradict the king. Later, during the maiden voyage, the captain (who was attending the rehearsal as well) did not use that information either, since he shot the cannons on one side, which started to make the boat pitch.

That’s pretty much project management 101, but this story is a good reminder of some best practices you may want to enforce on your projects. It’s easy to see what others don’t do right, but maybe there are areas of improvement for you as well ?

  • Write accurate specifications beforehand, or at least make sure people agree on what to build
  • Don’t change specifications halfway. In the agile software development world, changes are OK, but not in the middle of a sprint
  • Listen to people. Managers are often clueless :p while people who do things have a lot to say about what can be improved
  • Talk about problems. Do it early
  • When things are not OK, do what you can at your level to correct things
  • Test a lot

More about this on Wikipedia.

J’ai récemment eu l’occasion de coacher des développeurs débutants. Ça a été l’occasion pour moi de faire le point sur des notions de base mal comprises, et peut-être l’occasion pour vous d’apprendre de choses !

Ma présence touchait à sa fin, et l’éventail des sujets qu’il restait à aborder est trop grand pour une formation. J’ai donc suggéré l’achat de quelques livres, que vous trouverez reproduite et étendue ici. En effet, dans une boite précédente, nous avions accès à une petite bibliothèque technique, grâce à laquelle j’ai appris plein de choses. J’ai profité de mon passage freelance pour garder l’habitude de m’acheter environ un livre technique tous les 1/2 mois. Si vous ne pouvez/souhaitez pas les acheter vous-même (certains coutent un bras), peut-être pourrez vous également demander à votre boss de faire l’achat de quelques titres ? Cela profitera à toute l’équipe.

Il n’y a pas que le travail dans la vie ! Souvent, les développeurs sont des passionnés. C’est pourquoi j’ai profité de cet article pour conseiller quelques titres qui m’ont bien amusé.

Vous trouverez donc des suggestions sur:

Lire la suite »

I was at Rustfest this weekend. As expected, it was a great conference ! Lots of things to learn, and great people to meet.

I could not attend the workshops (nor the Impl days), but this cool community puts so many things on Github that I’m gonna be able to do them anyway, see for instance:

Also, the videos are on the web already, and you can download lrlna’s zine about memory

What follows is a summary of the talks I liked the most.

Tech:

Non-tech:

Yew, JavaScript without JavaScript

Denis Kolodin talked about Yew, the rust framework he develops.

As a web developper, this is really exciting : we can have both the power and safety of Rust, with the reach of web applications ! Yew looks a lot like doing React development with Redux.

Let’s take an example : imagine we want to create a counter, with 2 buttons to increment/decrement the value. We would:

  1. Create a model
pub struct Model {
    value: i64,
}
  1. Create the messages
pub enum Msg {
    Increment,
    Decrement
}
  1. Implement the message handling
impl<CTX> Component<CTX> for Model
where
    CTX: AsMut<ConsoleService>,
{
    type Message = Msg;
    type Properties = ();

    fn create(_: Self::Properties, _: &mut Env<CTX, Self>) -> Self {
        Model { value: 0 }
    }

    fn update(&mut self, msg: Self::Message, env: &mut Env<CTX, Self>) -> ShouldRender {
        match msg {
            Msg::Increment => {
                self.value = self.value + 1;
            }
            Msg::Decrement => {
                self.value = self.value - 1;
            }
        }
        true
    }
}
  1. Create a view that displays the value and the buttons, and sends the messages on a click
impl<CTX> Renderable<CTX, Model> for Model
where
    CTX: AsMut<ConsoleService> + 'static,
{
    fn view(&self) -> Html<CTX, Self> {
        html! {
            <div>
                <nav class="menu",>
                    <button onclick=|_| Msg::Increment,>{ "Increment" }</button>
                    <button onclick=|_| Msg::Decrement,>{ "Decrement" }</button>
                </nav>
                <p>{ self.value }</p>
                <p>{ Date::new().to_string() }</p>
            </div>
        }
    }
}

and that’s pretty much it ! It works well with stdweb and cargo web.

… have a look at the examples (I took the counter example there), and enjoy how easy it is to do javascript without writing javascript.

Immutable data structures and why you want them

A great talk with a great slide deck. I’m a bit sad @bodil talked mostly about the data structures, I’d have loved to hear more about the necessity for their immutability.

Anyway, if you wanna learn stuff on

…go watch the talk ! She provides an impressive reading list of papers regarding RRB trees :

After skimming through a few of them… I know I’m gonna need more time during lunch breaks this week to dive deeper on the topic 🙂

She also dropped some cools remarks:

  • nobody is gonna use a library with a bad documentation. Sounds obvious ? It is. And yet as developpers we don’t like to write docs anyway, but we should work on that.
  • I can’t wait for the moment I’m gonna use The « Haskell Defence » in an argument, aka « immutable values make it easier to reason about your program »

Building reliable infrastructure

@spacejam talked about how to introduce verifications in complex architectures… and he introduced tons of great tools that can help us, software developpers, write better applications, with an amazing set of references.

The issue with everything we build stems from our brain : everything we know is subject to bias, and everything we build reflects these biases (see Rationality: From AI to Zombies (confonting assumptions)). Since our code reflects our biases, our automated tests do as well…so our tests tend not to be as effective as they could be.

A solution: don’t write tests. Write expectations instead, and have the machine generate random test cases.

There is a for that, called proptest.

It gives non-determinism in test execution, but with replayability (if a test case crashes, it does not simply crash randomly : you can relaunch it). It is used in im-rs, where there are tons of examples.

Another option is Model based testing:

  1. write a simplified model of a system
  2. apply random sequences of operations on both the implementation and the model
  3. if the model and implementation behave differently, it means we’ve found a problem
  4. the library will rerun the test, dropping out operations until it finds a minimal failing sequence (the machine just wrote a regression test for you!!!)

There’s a crate for that: model

Another option is fault injection. You make your system crash, and see how behaves. Sounds obvious ? Well the problem is not solved anyway. « in 58% of the catastrophic failures, the underlying faults could easily have been detected through simple testing of error handling code. », according to Yuan et al., OSDI 2014. Again, there are crates for that :

There were things about jepsen and TLA+, but by now if you are interested you should at least watch the slides.

He did not cover how to build such architectures, but provided some great references:

Learning how to learn

Link to the slide deck

In 2015, @vaidehijoshi learnt computer science on her own through her project basecs: study a CS topic every week for a year, and publish a blog post. She created her own curriculum through those 52 articles. It had unexpected side effects ! The writen baseCS turned into a podcast, and a video serie.

One the main lesson is that learning new things is extremely hard. So she studied the psychology & science behind learning. It led her to Richard Feynman, a famous phisicist who had a Nobel prize. Unsurprisingly, he also taught physics, but… he was also an artist, a philosopher, a bongo player, and many other things you don’t expect from a Nobel. Like, he particularly liked to break safes.
The thread through all his achievements is that he was super great at learning and understand things he was unconfortable with.

Let’s talk about how he learnt, and then I’ll summarize why it works well.

The Feynman Technique

Feynman left what is now called the Feynman Technique for learning, which has four steps:

  1. Identify the subject, the thing we want to learn

write down everything we know, and add things to this repository

  1. Explain it to someone who’d knw nothing about the topic (teach it as if it was to a 5yo child) => It forces you to use plain, simple terms

« When we speack without jargon, it frees us from hiding behind knowledge we don’t have ». We are pushed to go the the heart of a concept. Brevity is important and necessary, because childs don’t have a long attention span. Do not fear using diagrams. They were one of Feynman’s most important tools.

  1. identify any gaps in your understanding. Arguably the most important, it’s where the learning happens.

  2. Organize & simplify into a narrative. Use simple sentences for story telling, analogies…

Here is how he would explain atoms work, in a sentence:
« all things are made from atoms – little particles that move around in perpetual motion, attracting each other when they are a little distance apart, but repelling upon being squeezed into one another »

Feynman was nicknamed « The Great Explainer » (« the best teacher I never had », bill gates)=> maybe one of the important aspects of learning is to be able to teach things
Another is component is curiosity: he had a notebook « Notebook of things I don’t know about ». In his bio, Genius, he said he tried to find the essential kernels of each subjects.

This methodology:

  • tests our understanding
  • challenges our assumptions. Often, we you start learning a topic, you don’t know what you don’t know. « I’m smart enough to know that I’m dumb », said Feynman.
  • Reinforces what we do know
  • teaches us to be better explainers. By reframing stuff we know, and forcing us to teach things simply, we know that we know something once we are able to do that. Even for particularly complex topics.

Also, it makes knowledge accessible. People get interested to stuff when you explain it to them simply. Tech needs more great explainers !
As a side-effect, it makes our industry more diverse and inclusive.

Supercharging Rust Communities

Matt Gathu (@swissgathu) talked about what made the rust communities such a success.

  • Flat governance. There is no chain of command, no hierarchy. Teams are more or less independant. As a consequence, things get to move very fast, because there is not the bureaucracy of having someone to approve of a choice
  • Diversity & Inclusivity as a goal. Be deliberate about diversity and inclusion.
  • Having a roadmap allows to have a shared vision
  • Collective decision making. In the « RFC decision process », everyone has a say. Decisions are not made behind a closed door, you can always know why a given choise has been made.
  • Having a Code of Conduct. It’s a conscious effort to make sure everyone would be safe. People have joined because other communities were toxic to them.
  • Retrospectives. Take time to reflect on what you did: what is going right ? what can we improve ? This let’s you iterate faster.

It was also noted in another conference that the Rust’s language itself is really good due to the presence of great docs, a build system, package manager, memory safety…

An intro to rust

19 février, 2018

I recently gave an introductory talk about the Rust language, to experienced programmers who did not know the language. The presentation can be seen here and downloaded on Github. This article is a short summary of what I described.

The idea was not to enumerate features, but to highlight some of the cool things that have made this language so popular and growing quickly with a lot of enthusiasm.

I chose to focus on the 4 following elements:

  • Tools
  • Borrow checker
  • Community
  • Integrations with other languages

There are more of course, but hey, attention and time are limited resources, tech talk are no exception. Lire la suite »

I had a hard time learning rust at first. I didn’t quite know where to start, I focused on the wrong resources and lost some time. Here are my suggestions about everything you may need in order to learn and work with rust: where and what to learn, how to properly install the compiler, what tools you need and how to use them.

Lire la suite »

Parsing XML in Go

21 février, 2017

There is no example about how to use XML with Go on GoByExample, so here is how to do it. We’ll use the encoding/xml package for the standard library.

Lire la suite »

I’m using Markdown as a markup syntax for many things: the syntax is indeed really simple to use, it lets me focus on the content I need to write, and it can later be converted to HTML for « real life » display once I’m done. In the open-source community, it has become largely spread, and many developpers use it, like me, for non code-related stuff, like keeping notes or writing their journal. Lire la suite »

La plupart du temps, pour tester si une clé est présente dans un tableau, il faut utiliser array_key_exists. Pourtant on trouve encore des empty et isset à sa place, en pensant que ces 3 fonctions sont interchangeables : ce n’est pas le cas. Fin 2016 on trouve encore des confusions, donc cet article me servira de référence pour les futures revues de code 🙂

Lire la suite »

C’est bientôt Noël. Et si vous vous faisiez le cadeau d’apprendre quelque chose de radicalement nouveau, comme un nouveau langage de programmation ?

Lire la suite »