Is it really as bad as it looks?

Hi, I have a question

Do you ever not?

“Learning never exhausts the mind.”

Leonardo DaVinci? I’m proud of you. Go ahead.

Thank you. I’ve been reading all these horrific news stories about the Olympic games and Rio…

Oh that. Yeah, I’ve been getting asked that question regularly lately.

Is it really that bad?

Yes and no. There is a lot of sensationalism out there. But it’s bad and, at least to us Brazilians, not at all unexpected because Rio is widely known as a hellhole among us.

Years ago, when the games were announced, most of us in Brazil expected the worst. Rio is widely perceived by Brazilians as a hellhole.

I spent a whole month there once because of work and it left a strong mark in me. I’ve seen people being mugged, a dead body was left outside my hotel one night, I was in the middle of a shooting between rival gangs, and – crème de la crème – one day some big shot drug trafficker was killed in jail and what followed was, to me, surreal. The city is beautiful though.

What happened?

All thoughout that day, people kept telling me about the news of this guy who got killed. I could not care less, to be honest. But at the end of the day I finally understood when I tried leaving the office and people said I was nuts. I wasn’t allowed to go because the drug gangs issued a curfew on the city.

A. Curfew. On. The. City.

At times like that, commerces close their doors all over the place and the police completely disappears.

That’s insane! How is anyone safe during the games?!

Well, here’s where I point out that it’s probably not as bad as you’d think.

Wait what

Hold on. First of all, it is not in the gangs’ interest to attract international attention. They already have full control over the city, the police, etc. It’s in their best interest to wait the games out and then continue with business as usual. I doubt there will be problems with the drug traffic.

Second, there will be 50,000 security personnel there. FIFTY THOUSAND. And again, it’s in the powers that be’s interests that foreigners have a good time there. It will suck for people from Rio who will be hounded by the police and the army, though.

Just a couple of weeks ago the Brazilian Congress passed a special law granting de facto immunity to members of security forces who happen to commit crimes against civilians during the games. It’s going to be fun.

Wait what? Immunity De facto. What the law does is transfer the authority of judging these cases to militaty justice. In practice, it means immunity. And the reason for the law was exactly to allow the police and the army to trump people’s rights in order to keep the peace. It’s so very Rio.

And terrorism?

Yeah, I don’t know. As we’ve seen these past weeks, you don’t need much to kill people. A rental truck is enough. So yes, there might be something. Then again, 50,000 security personnel. I’m guessing there might be easier targets out there. In short, I don’t know but I don’t think the risk is high enough to worry about it.

What will be horrible is already happening and mostly hidden from foreigners. It’s the human rights abuses against the poor. That to is very Rio. They’re make every effort to hide the poor and prevent them from being seen, no matter the cost. Thousands have been forcebly relocated already.

And in the end, what for? The city (and its people) won’t come out better after the games than before.

It’s depressing

Indeed.

How do I add an unknown attribute to an element in ReactJS?

There’s this project I’ve been working on in ReactJS and Chrome and I needed to use a <webview> component. In case you’re not familiar with <webview>, it looks something like this –

 <webview src="https://robteix.com"></webview>

One of the coolest features of <webview> is the ability to isolate scope or partition it. When you use a partition, all cookies, local and session storage, etc, will be stored separately from other partitions. All you need to do is add the partition attribute. So I had something similar to this inside one of my components –

return (
 <webview id="foo"
 src="https://somewebsite.com/"
 partition="persist:foobar" />
);

To my surprise, multiple <webview> s were sharing the same session data. Not good. A quick glance in the app storage directory told me that no partition was being created. What’s wrong?

We can look at the HTML output for hints –

 <webview id="foo" src="https://somewebsite" class="MyComponent__component___3U2KV" data-reactid=".0.0.0.2:$MyComponent.0" tabindex="-1"></webview>

No partition to be found. The reason is React doesn’t know what to do with that attribute and as a result it is not output. There are good reasons for this, but the main one is that properties may (and often do) work differently accross browsers and React needs to be able to deal with this.

But how can we add the attribute that we need then? You could add some JavaScript to get the element but that’s not very reactive. The reactive way to do this is to leverage ref, which can provide a reference to an element.

 <Element ref={somevar} />

In this code, somevar will hold a reference to <Element>. Better yet, just use a function instead.

 <Element ref={function(e) { e.Something(); }} />

Or in ES6 syntax.

<Element ref={(e) => e.Something() } />

Which finally takes us to our problem: how do we add the partition attribute? Easy peasy.


return (
 <webview id="foo"
 src="https://somewebsite.com/"
 ref={elm => elm && elm.setAttribute('partition', 'persist:foobar')} />
);

And that’s it, a simple way to add unknown attributes to elements in React.

Clashing method names in Go interfaces

I wrote about how the Go and C# compilers implement interfaces and mentioned how C# deals with clashing method names but I didn’t talk about how Go does it, so here it is.

Two interfaces with the same method name that need to behave differently is very likely a sign of bad API design and we should fix it instead. But sometimes we can’t help it (e.g. the interfaces are part of a third-party package). How do we deal with it then? Let’s see.

Given two interfaces

type Firster interface {
    DoSomething()
}

type Seconder interface {
    DoSomething()
}

We implement them like this

type MyStruct struct{}

func (ms MyStruct) DoSomething() {
    log.Println("Doing something")
}

We can run this little test here to verify that MyStruct implements both interfaces.

But what if we need DoSomething() to do something different depending on whether MyStruct is being cast as Firster or Seconder?

Go doesn’t support any kind of explicit declaration of interfaces when implementing methods. We can’t do something like, say

type MyStruct struct{}

func (ms MyStruct) Firster.DoSomething() {
    log.Println("Doing something")
}

func (ms MyStruct) Seconder.DoSomething() {
    log.Println("Doing something")
}

That won’t work. The solution is to wrap MyStruct with a new type that reimplements DoSomething(). Like this

type SeconderWrapper struct {
    MyStruct
}

func (sw SeconderWrapper) DoSomething() {
    log.Println("Doing something different")
}

Now when we need to pass it to a function expecting Seconder, we can wrap MyStruct

ms := MyStruct{}
useSeconder(SeconderWrapper{ms})

That will run the DoSomething() from SeconderWrapper. When passing it as Firster, the original DoSomething() will be called instead. You can see this in action here.

Interfaces in Go and C#

I make no secret of the fact that I love Go. I think it’s a wonderfully designed language and it gave me nothing but pleasure in the years I’ve been working with it full time.

Now however I am working on a project that requires the use of C#, which prompted me to realize something.

When people ask about Go, most people talk about channels and concurrency but I think one of the most beautiful aspects of Go is its implementation of interfaces.

To see what I mean, let’s define a simple interface in Go.

type Greeter interface {
    Hello() string
}

Now say we have a type that implements this interface

type MyGreeter struct {}

func (mg MyGreeter) Hello() string {
    return "Hello World"
}

This is it. myGreeter implicitly implements the Greeter interface and we can pass it along to any function that accepts a Greeter.

func doSomethingWithGreeter(g Greeter) {
    // do something
}

func main() {
    mg := myGreeter{}
    doSomethingWithGreeter(mg)
}

The fact that the implementation is actually important, but we’ll get to that. Let’s first do the same thing in C#.

interface Greeter
{
    string Hello();
}

And then we create a class that implements the interface.

class MyGreeter
{
    public string Hello()
    {
        return "Hello world";
    }
}

We quickly find out that the compiler doesn’t like this.

public static string doSomething(Greeter g)
{
    return g.Hello ();
}

public static void Main (string[] args)
{
    MyGreeter mg = new MyGreeter ();
    doSomething (mg);
}

The compiler complains that it cannot convert MyGreeter to type Greeter. That’s because the C# compiler requires classes to explicitly declare the interfaces they implement. Changing MyGreeter as below solves the problem.

class MyGreeter : Greeter
{
    public string Hello()
    {
        return "Hello world";
    }
}

And voilà, everything works.

Now, we might argue that it is not much different. All you have to do is to declare the interface implemented by the class, right? Except it does make a difference.

Imagine that you cannot change MyGreeter, be it because it’s from a third-party library or it was done by another team.

In Go, you could declare the Greeter interface in your own code and the MyGreeter that is part of somebody else’s package would “magically” implement it. It is great for mocking tests, for example.

Implicit interfaces is an underrated feature of Go.

Update: someone on Twitter pointed me to the fact that C# not only also has implicit interfaces but that this is the default state of things. That is true in a literal sense, but it’s not the same thing.

Imagine in our C# above, we have a second interface.

interface IAgreeable
{
    string Hello();
    string Bye();
}

(Yes, I was also told that in C# we should always name interfaces like ISomethingable. I disagree but there it is.)

We then implement our class thusly

class MyClass : Greeter, IAgreeable
{
    public string Hello() {
        return "Hello world";
    }
    public string Bye() {
        return "Bye world";
    }
}

It now correctly implements both interfaces and all is well with the world. Until, that is, the Hello() method needs to be different for each interface in which case you will need to do an explicit implementation.

class MyClass : Greeter, IAgreeable
{
    string Greeter.Hello() {
        return "Hello world from Greeter";
    }
    public string Hello() {
        return "Hello world from !Greeter";
    }
    public string Bye() {
        return "Bye world";
    }
 }

And then the compiler will call the appropriate Hello() depending on the cast.

public static string doSomething(Greeter g)
{
     return g.Hello ();
}
public static string doSomethingElse(IAgreeable g)
{
    return g.Hello ();
}
public static void Main (string[] args)
{
    MyClass mg = new MyClass ();
    Console.Out.WriteLine(doSomething (mg));
    Console.Out.WriteLine(doSomethingElse (mg));
}

This will print

Hello world from Greeter
Hello world from !Greeter

Personally I consider two interfaces with clashing method names that need to behave differently a design flaw in the API, but reality being what it is, sometimes we need to deal with this.

Github's Swift Style guide

Github has published a Swift Style Guide:

When you have to meet certain criteria to continue execution, try to exit early. So, instead of this:

if n.isNumber {
    // Use n here
} else {
    return
}

use this:

guard n.isNumber else {
    return
}
// Use n here

Feels very Go-like.