MathJax

Monday, February 29, 2016

Write This, Not That!: Java 8 Optionals


The point of java.util.Optional is to free us from compulsive null-checking throughout our code base by using the type checker to force us to recognize that a value may not be present. Optionals make great return types for query methods. Transitioning from an imperative/null world to a functional/Optional world can feel strange in a vacuum. Here are some common themes taken from reviewing code over the last year.

Write this:
final MyData defaultData = ... ;
return optionalReturningMethod().orElse(defaultData);
Not that:
final MyData defaultData = ... ;
final Optional<MyData> oData = optionalReturningMethod();
if (oData.isPresent()) {
    return oData.get();
} else {
    return defaultData;
}
Write this:
final MyVariable var = ... ;
final MyData nullableData = externalMethodThatMayReturnNull(var);
return Optional.ofNullable(nullableData);
Not that:
final MyVariable var = ... ;
final MyData nullableData = externalMethodThatMayReturnNull(var);

if (nullableData == null) {
    return Optional.empty();
} else {
    return Optional.of(nullableData);
}
Write this:
public Optional<MyData> myMethod() {
    final MyVariable var = ... ;
    final MyData nullableData = externalMethodThatMayReturnNull(var);
    return Optional.map(Utilities::myTransformation);
}
Not that:
public MyData myMethod() {
    final MyVariable var = ... ;
    final MyData nullableData = externalMethodThatMayReturnNull(var);

    if (nullableData == null) {
        return null;
    } else {
        return Utilities.myTransformation(nullableData);
    }
}
Write this:
optionalReturningMethod().ifPresent(Actions::useMyData);
Not that:
final Optional<MyData> optionalData = optionalReturningMethod();
if (optionalData.isPresent()) {
    Actions.useMyData(optionalData.get());
}
Write this:
return yourOptional().map(External::nullableFromValue);
Not that:
return yourOptional()
        .map(External::nullableFromValue)
        .flatMap(Optional::ofNullable);

A surprise: .map() will filter the original optional to Optional.empty() rather than wrap a null value with an Optional. Nerds, note that this means java.util.Optional is not actually a monad (like how the "functions" of software developers aren't the functions of mathematicians). We'll see how this goes. We're denied some of the beauty of the math of category theory (which is studied in spite of having the most boring name in existence) in exchange for not needing to tack on a .flatMap(Optional::ofNullable) ourselves.

Write this:
public Optional<TheirSubSubData> subSubData(TheirData data) {
    return Optional.ofNullable(data)
            .map(TheirData::getSubData)
            .map(TheirSubData::getSubSubData);}
Not that:
public TheirSubSubData subSubData(TheirData data) {
    if (data != null) {
        final TheirSubData subData = data.getSubData();
        if (subData != null) {
            return subData.getSubSubData();
        }
    }
}

return null;
Note that if Optional were a full-blown monad, we would need to have a .flatMap(Optional::ofNullable) after each of these .map() calls.

Write this:
public class MyClass {
    private final FieldType field;

    public MyClass(FieldType constructorArg) {
        if (constructorArg == null) {
            throw new NullPointerException();
        }
        this.field = constructorArg;
    }
}

// or

@lombok.RequiredArgsConstructor
public class MyClass {
    @lombok.NonNull private final FieldType field;
}
Not that:
public class MyClass {
    private final Optional<FieldType> field;
    public MyClass(FieldType constructorArg) {
        this.field = Optional.ofNullable(constructorArg);
    }
}
Wanting to use Optional fields for a class is a strong signal that you actually have a subclass.

Finally, if you find yourself using a lot of Optional::flatMap, just be cautious. It's easy to use .flatMap() as a crutch for not properly breaking down your code. If the reason you're using .flatMap() instead of .map() isn't 100% obvious, call over someone else to see if your code makes sense or you're just too deep inside your own head.

Friday, February 26, 2016

Liking dislike

The Dislike button may be the best outcome of Donald Trump's candidacy.

If I had to guess why the Like button alone reigned supreme for so long, it would be that Facebook didn't want to encourage hate or a culture of negativity. It's strange that they held so long to this belief when so many Facebook employees are also Facebook users, as it was immediately obvious that you didn't need a button to express disapproval or a negative message.

The Dislike button is not a grand technological achievement, nor is it non-obvious. The first thing most people want when they see a Like button is a Dislike button. Reddit and the Big List of Problems are built on both up- and down-votes. Facebook was making a conscious decision to keep it off the page.

The altruistic guess at motives is that they want to foster an atmosphere of positivity (ha!).
The cynical guess is that if one movement gets really popular, the only way you can fight back is to write comments (hoping they're read, which still add attention) or spend even more time to come up with a counter-campaign. Given that Facebook is built around a machine designed to keep you scrolling and clicking as long as possible, the cynical explanation is that the Dislike button is far too great a time-refund to its billion-plus user base.

My serious guess is that Facebook introduced the Dislike button to allow people to register their opposition to Donald Trump. It took a force that was so galvanizing but so distasteful, so molded to fit the cracks of what a Like-only world leaves behind, to get Facebook leadership to realize that the disenfranchisement of upvote-only was getting them a world they deserved. The hopeless feeling you have seeing nonsense with likes. The inability to quickly set the record straight. So for once, we have an improvement to Facebook as a whole. Let's hope it sticks.


Monday, February 22, 2016

Chinese vs. English: Stroke Order

Chinese writing is cool. All characters are meant to fit in an equal-sized box. There are no spaces to break up words. Many characters are made from two other characters smushed into the same-size box. And clearly, these characters are complex compared to what we see in English.

Here's what English-speakers don't appreciate, or at least what I didn't appreciate until I started writing Chinese characters: Stroke order matters. Stroke order goes a long way towards forming the character correctly and making it "look" right. Stroke order helps manage the total space of the character within the box and it helps stay consistent with the proportions of angles and line segments within the characters. You might not appreciate it when learning to write 十 (shí, "ten"), or even 不 (bù, "no" or a generic negation), but you definitely appreciate it when writing a character like 我 (wǒ, "I"). Stroke order can make all the difference.
Just try drawing 我 some other way. I think you'll find this stroke order funnest, fastest, and most effective.
Source: wenlininstitute.org
My Chinese friends have commented that my Chinese handwriting is good (when I remember how to draw the characters at all). There's a counterintuitive explanation I hold for this: my handwriting is good because I am a beginner. As a beginner to Chinese characters, my knowledge of characters is not yet built-up enough to know when a sloppily written version of one character becomes another character entirely. My knowledge of only a few dozen characters, knowing there are yet thousands more, causes me to pay attention to penmanship.

English has 26 letters. Multiply by two for capitals. Add 10 digits. Now add in that we put in spaces between our words and that we pick up frequencies of letters and tuples of letters (rarely a q without a u, common suffixes -ing, -er, -ed, etc.). Just a smattering of punctuation added on top. A lifetime of English allows me the luxury of sloppy penmanship, secure in the knowledge that other English speakers will aggressively prune my hastily-spewed chicken-scratch into something intelligible.

Many software developers cite their poor penmanship as a source of pride. For me, this is related to the cryptic signatures doctors leave on prescriptions. The sloppier the penmanship, the harder to duplicate, and therefore the more status afforded to the owner of the hand. I saw to it that the signature I would develop for credit card receipts would skirt any pretension to legibility. But now I'm studying Chinese, so let's take another look at stroke order for English letters. A quick Google search turned up the following:

From superenglishkid.com
There are a few other competing stroke orders for English letters (noted by this Quora answer), because there are so few characters compared to Chinese that we can usually puzzle our way from intention to representation as writers and back again from representation to idea as readers.

What I found common to the few English stroke-order diagrams was that they heavily favored downward strokes for many characters. When I write A, V, v, W, or w, the diagrams start each stroke at the top, whereas my strokes have developed an up-and-over or down-and-around quality, linking the first two strokes of A and V into one and turning my W/w into one continuous stroke. It's kind of fun to try to follow this other stroke order. The capital M in the above diagram really sticks out to me. My M is a left-down stroke, a single stroke for a half-height 'v' in the middle linked to the right downstroke as a finisher. The above diagram shows M as four strokes, the first two setting up left and right goal posts. I can't help seeing something similar to the Chinese way of writing diverse characters into repeatable square boxes.

It's been a joy to continue studying English and Chinese. The languages are so distant from one another. The greater the distance, the greater the appreciation for human thought and reasoning that transcends expression.

Friday, February 19, 2016

Why tonal languages can be tricky

Tonal languages are hard for westerners not because we lack tones in the West, but because tones carry extra-semantic meaning. Superimposing this extra-semantic meaning where it isn't needed is disinformative but deeply ingrained in the way we speak.

Tones suggest to other English speakers that we asking a questions, being sarcastic, begging, and more. You can say the same sentence in several ways, and some parts of what you're varying are tones. So it's not that we don't hear tones, it's that we don't recognize tones as having to do with distinguishing one syllable from another but deciding whether someone is happy, upset, or confused. In English, tones are melodies. In Chinese, they're verses.

misspandachinese.com

Wednesday, February 17, 2016

Hearing sounds vs. hearing language

We don't hear languages the same way they hear sounds. It's not possible. We translate the sounds of spoken words and phrases to their meaning far faster than we realize. Let me prove it.

You know you think faster than you can talk.

You hear faster than you talk, also. Watch a video at 2x speed and you can still follow along just tine. It takes training of hearing familiar patterns of sounds over and over again.

My most convincing experience was my flight to Beijing. I hadn't been studying Mandarin very long, but I was listening closely to the conversations around me and to the Mandarin translations of the announcements, hoping to identify a word here or there. That's where it hit me that not only did I not understand the words, I couldn't even play them back to myself in my head.

The capacity of human short-term memory is commonly cited as 7 "thingies" plus or minus 2. I've heard more recent research suggests this capacity is much more towards the lower end of that range. How can we communicate when we have such a limited short-term memory? Look at any of these sentences. How many have more than 7 words? How many have more than 7 syllables? But are you having a hard time following? Not really. The reason is that we've built up a lifetime of experience using our language. We expect certain phrases to follow others, certain words to follow others, and certain syllables to follow others. The real information conveyed by our language is the series of surprises against that baseline of expectations. As a native English speaker studying Mandarin, I didn't have that any more. I don't even have cognates.

What about music? We can remember melodies longer than 7 notes, along with their rhythms. This is even more true if we have a grounding in music theory, which partially plays a role in compressing the universe of sounds into a chromatic scale of 12 notes followed with patterns of intervals, chords, chord progressions, phrases, etc. This grounding of theory gives our puny human brains the amazing ability to repeat complex melodies verbatim when truncating these sounds to this limited scheme.

Given that we aggressively chunk language into concepts during routine conversation, we can safely move beyond thinking or even reading in words (subvocalization). Speak to communicate. Read to comprehend. Think to explore. The expression in words is not the thought, but how we communicate the thought. The organization of the thought in our minds will depend its relationship to the other thoughts in our minds. Given the physical structure of neurons, this makes sense.


Since we don't think in words to begin with, don't limit yourself to thinking only in words. Think also in diagrams and animations (the right video games can be tremendously good for the brain). Think in terms of other senses.

Monday, February 15, 2016

"We have a big-ass gym."

She was courteous, beautiful, and professional. I managed to avoid laughing; I couldn't, however, suppress a big-ass smile at the Beijing Kerry Hotel receptionist's suddenly-familiar phrasing while describing the hotel's other amenities. She's correct: "big-ass" appropriately describes the size of their gym. I didn't have the heart to explain her moment of incongruity.

This receptionist speaks good English. She's probably heard that Americans are informal by Chinese standards. I'm probably not the first person she's described the gym to this way. Previous patrons also probably stifled a laugh and most of a smile, but their eyes likely lit up. She may have marked this response as a moment of rapport. She might also just think that American businessmen really like their gyms.
We arrived at the hotel at around 9:30pm Beijing time. I fumbled around for a tip for the bellhop, who I tried to refuse. I would have carried my own bags but I wanted to accept the tea they offered me at the front desk. After fumbling for some time with RMB that all seemed exactly the wrong denominations, I settled on a $5 bill. I flipped through the TV channels for a few minutes to see if I could pick out any characters or syllables, then set an alarm and went to bed.

The hotel was luxurious. Major chords were the elevator chimes. Do-not-disturb signs are operated by a switch instead of a placard hung on the door. I discovered this when a note informed me I had left the do-not-disturb signal on, preventing the servicing of my room. There were a lot of switches on the wall.

The room's toilets were push-button operated for flushing, bidet-ing, and drying. There were even buttons for raising and lowering the seat. The thought, unbidden, arrived in my mind as "and here we are in America, raising our own seats like chumps!"

I wasn't able to find an alarm clock in the room, so I installed an alarm clock app on my laptop instead. The bathroom mirror had a built-in digital clock. My stay was at the height of luxury, and not what I expect is the normal standard of living in most of China. Or most of America, for that matter.

Friday, February 12, 2016

Base ten is an obstacle to international harmony.

A rough approximation of the dollar cost of an item in Beijing would be to divide it by six. This should be much easier than it is, but for the brutish choice our species has made to use ten as the base for international commerce.

The philistine critics among are surely waggling their manual digits in support of this accident of biology enshrined beyond its post. Let me parry their defiance of common sense with a solution for counting to twelve on one's fingers. If you refuse to grant arguments beyond this seeming convenience, this should prove a switch to twelve at least yields no ground as far as the mathematically illiterate are concerned:


(not my video)

Now for the sophisticates among you, I submit to you these grand properties of twelve as a base: We enjoy the convenience in our digital (that is, base-ten lives) of dividing easily by 2, and 5. The astute among you will see that the dozenal revolution is asking us to sacrifice convenient division by 5, but hear me! The rewards are great, for in return, we receive easy division by 3 and 4.

Division is easiest for the proper divisors of the radix.
For ten, this means 2 and 5.
For twelve, this means 2, 3, 4, and 6.

In base twelve we replace the convenience of division by 5 with the convenience of division by 6 and introduce convenient division by 3 and 4 as well.

In the meantime, dividing everything by 6 was a bit of an inconvenience while in China. I'm still withholding my support of the metric system until it switches from base ten to base twelve.

Wednesday, February 10, 2016

Windburnt on the Great Wall

My Saturday in Beijing, 8 of us hired a tour guide. We went to the Forbidden City, the Great Wall, a jade factory, a copper-something-pretty-stuff factory, a silk factory, and a tea place.

The advice people gave me about visiting China (wear masks and avoid pickpockets) was not very necessary. The pollution was noticeable but not apocalyptic. People on the street seemed to wear them more for warmth than for health. Avoiding pickpockets at the Forbidden City was trivial, as the bitterly cold weather meant we pretty much had the place to ourselves. We were told this was Beijing's coldest winter in 30 years, and that Saturday when we were outside playing tourist was supposed to be the coldest day. I didn't pack gloves, but I did, thankfully, pack a ski mask. I got a pair of North FakesTM gloves for ¥20 ($3) on the street that did an okay job for the rest of the day.

The tour guide gave us a lot of facts about the Forbidden City. He wanted us to guess how many rooms there were in the Forbidden City (9,999. Nine is a lucky number). With the same enthusiasm, he asked us to guess how many concubines the emperor would have. The Forbidden City is a very large moated area. Concubines would live just outside the walls. Houses that were aligned with the north/south axis of the city would bring good luck to the inhabitants, and concubines would live there. After several large concubine count guesses from the group and Kevin (our guide) responding "more" or "less," I offered, "Zero! The emperor loved his wife very much."

I got pretty windburnt on the Great Wall. Although the temperature was colder there than it was at the Forbidden City, we were at a section that was pretty much just stairs straight up the mountain. My FitBit said I had something like 275 floors for the day (and 20,000 steps). Two others and I reached the top. The other five didn't get quite so high and patiently sipped coffee, awaiting our return. I noticed the coffee shop advertised an "American Latte." I imagine that was to properly set expectations for Italian tourists. The Great Wall had a great amount of graffiti on it. I was embarrassed to see English graffiti, even though it was alongside Chinese, Russian, and several other languages. It's just not classy. Graffiti your own country, filthy tourists! The mountains near the Great Wall rise more steeply than the Cascades. The Wall was a great way to climb up and get a good view of the surroundings. It also made the pollution situation clear. The temperatures were just a few degrees above zero (booger-freezing) and the humidity was maybe 10-20%, but towards the city it still looked foggy and slightly yellowish. That is smog, and it's sad. One of our Beijing contacts told us most masks are placebos and thinks within about 20 years they should be able to clean it up. I hope he's right and I agree with him. On the plus side, I made it up the Great Wall without breaking a sweat.

Monday, February 8, 2016

Digital life inside the Great Firewall

My week in Beijing was a week without my smart phone, a week without Facebook, a week without texts, and a week without Gmail; so, in spite of the pollution and the anarchy of their dog-eat-dog rules of the road, my trip to Beijing was very relaxing.

I was able to send email through my work laptop, so I used that to send daily messages to keep my mom from worrying too much.

The Beijing locals seem to be well-connected. WeChat in China seems to be about as pervasive as Facebook here.

While it was comfortable to return to my friends, family, and language, I did not relish the reintroduction of Facebook.

The "welcome home" from my News Feed. I missed you too, America.
My week without social media reminded me of when I took a break from a toxic relationship. That feeling of weight off my shoulders...it clarified everything. The relationship was over. It's not supposed to be that comfortable to be without something that's supposed to be so important. So, Facebook News Feed: I don't need to scroll through you any more. You're not a positive presence in my life. You are a machine that is designed to keep mankind scrolling, clicking, and commenting for as long as possible. You're a time-waster. Freedom is sweet.