Japan: We're losing to Apple, and here's why - <AUTHOR> http://globalvoicesonline.org/2011/10/18/japan-were-losing-to-apple-and-heres-why/

<comment><USER2> Nintendo is an interesting case that may dispel some of the stereotypes about Japanese companies and management styles.

First, the company is quite old (1889, I believe). It started out manufacturing playing cards, yet had a pretty remarkable evolution after its post-war CEO (a member of the founding family, surnamed Yamauchi) took over. While it was a top-down organization, Yamauchi recognized and encouraged some out-of-the box and risky thinking. The company at one point was invested in things like hotels and food, but started to develop a new business in the 1970s around video games. Keep in mind that in 1977 video games were not nearly as popular as they are now, and the nearest product line Nintendo had at the time was toys. Famicom/NES was launched in the mid 1980s, at a time when the videogame market was in a slump (this was post-Atari 2600). It turned out to be a massive hit, that really kept Nintendo on top of the console market until Sony came out with the PlayStation.

The Wii is another example of an innovative approach to product design. It was not designed by focus groups, as the company was worried about leaks. Rather, the design of the console and controller came from an internal group made up mostly of career Nintendo engineers like Shigeru Miyamoto (of Mario Bros. fame). Yamauchi's successor, Satoru Iwata (himself a former game developer) was also on the team. They recognized that they couldn't win the hardware arms race with Sony and Microsoft, a race that focused on specs and pleasing hardcore gamers. They thought of a different set of users, and not only kids and senior citizens waving around a Wiimote. The team even considered how housewives would react to a new console in the living room, and therefore designed a box that was sleek and stylish, and not much bigger than a stack of DVD boxes.

There's a great interview series with the Wii design team, called "Iwata asks". It talks about many of the issues they had to overcome, and the prototyping process. It was published on Nintendo websites all over the world -- I think Iwata wanted to do a little victory lap, and get on record how they came up with the brilliant ideas behind the Wii. You can start reading it here:

<http://us.wii.com/iwata_asks/wii_console/>

<comment><USER3> I think Nintendo's success primarily has to do with them employing one of, if not, the best game designers that has ever lived - Shigeru Miyamoto. By trusting and empowering him they are able to have taste, just as Jobs's taste defined Apple, Miyamoto's defines Nintendo.

<comment><USER4> Some of the best graduates from Tokyo University wind up at Nintendo. It was considered one of the best places to get a job.

Nintendo is not a company I would want to emulate. It is getting squeezed by Sony and Microsoft, and even its innovations in terms of casual gaming seem to be on the verge of going away. I consider it a colossal waste, but I guess YMMV.

Disclaimer: I thought the same when the DS came out. I was very very wrong.

<comment><USER5> Sony's network problems will haunt them for years. I think they're done in the game industry. Microsoft is lacking in innovation in every single category I can think of.

This would be the perfect time for Nintendo to crush them both.

<comment><USER6> How xbox 360 escaped the ring-of-death is baffling to me. I guess the $1billion hit they took to extend warranties either really spoke to consumers, or people just don't care if they have a 1 in 3 (or was it 1 in 4?) change of getting a dud.

<comment><USER7> They replaced several of mine for free, waiving all shipping and repair costs. I can't think of another experience I've had like that. They're also a US company, and they have the best online gaming experience... those are just a few of the reasons I can think of.

<comment><USER8> One of the reasons why one does not typically experience something like that is because most companies would go out of business if they blew that much money on a faulty product. Microsoft has other revenue streams that allow them to throw billions at any problem.

</comment></comment></comment></comment></comment></comment></comment><comment><USER9> The article kind of misses the point.

The reason why people are leaving the Japanese phones for the iPhone is because Japanese phone interfaces SUCK BALLS. And they have ALWAYS sucked. I suffered through 5 years of one phone after another being such a terrible user experience that I think it scarred me for life. And don't even get me started with Sony, who replaced the perfectly functioning joypad in their phones (which USED to be the best) with that stupid "sony" sidewheel they spent so much money developing and insisted on putting in every product, whether it made sense or not.

The fact remains, emoji ARE important. Easy text input IS important. Being able to pay for stuff at the combini with your phone IS important. It's just that having apps, and a UI that doesn't suck balls is even more important.

iPhone took YEARS to penetrate the Japanese market, precisely because it didn't have the features that customers wanted, and they spoke with their wallets, buying the Japanese models. But now that app and smartphone fever has finally landed, people are more willing to compromise.

But the point is, they SHOULDN'T have to compromise. That's just Apple deciding what people will use, even if it's the wrong thing. It's taking a little bit of good advice to such an extreme that what appears on the surface "visionary" would upon closer inspection reveal itself as insanity. Hubris has a way of creeping up on you when your power remains unchecked for too long.

Yeah, Sony used to be good, but then again they used to make good products. Once their arrogance got the better of them, their products started to suffer. My first Vaio was awesome. Sleek, light, and fast. My last Vaio was practically useless out of the box. It took me 3 HOURS to remove all the crapware they loaded into it, which slowed it down so badly that it was almost unusable. Oh, and it had that stupid useless Sony sidewheel on it, and their incompatible-because-we-said-so memory stick port too. I shudder to think of how the average user would endure with such a monstrosity.

<comment><USER10> This is so true. Example: My iphone died recently, so while waiting for the 4s to come out I used a 3-4 year old Sony Ericson lying around the office. It has so many buzzword features! It even has dedicated media playback buttons on the outside! Yet how do you call someone? It takes 6 button presses. Press down > click on first name > Call > Voice Call/Video Call/PushTalk > No Message/Create Message > Call/Call with ID/Call with no ID/Country code

That's insane. It is like no one ever tried to make a phone call with their phone when designing it.

Don't get me started on the text editing screen. It is a modal text area that flips between movement within the whole text and movement within the single word you are editing. I love Vim, and I still hate this text entry method.

This whole topic has been covered many times before, but its roots are various and you could write a book on the subject of why most firms (both japanese and non) are just so horrible at consumer software interface design.

Some people suggest that it is just that the Japanese firms were only really good at hardware, but that rings false. I've seen a lot of really horribly designed Japanese computers and mobile phones before the iPhone came out, even just judging the hardware by itself on simplicity and reliability.

<comment><USER11> Wow. I've only owned Toshiba phones (on both au and SoftBank) before I got my HTC Desire, and making a call was always a matter of clicking the 電話帳 button and selecting the name. Although I've used other people's phones plenty of times, and it was always pretty much the same. I've never used anyone's Sony Ericsson, though.

<comment><USER10> Just tapping the name actually placed the call? What an idea. Just for fun, I looked at an older Docomo model on my desk by NEC. It is even worse:

Phonebook > Search > List of ways to search, NONE of which is just "show me my phonebook".

Let's try name lookup > Enter a string to search for > Search results > Choose a result > Dial.

Let's try Group > List of Groups > First Group > Choose name > Dial

<comment><USER12> Just tried the docomo NEC (N-02A) I had lying around. Down arrow > Left right to pick the first kana of their name > select name > Press dial button. Not _that_ bad, but a far far cry from the european Sony Ericsson's smart phonebook.

Right now I have a SH-12C as my main phone, and it's basically an Android phone with a kickass screen and all the crazy japanese features jammed in it (1seg, mobile suica, 3D camera+screen, privacy veil, etc). And it's great - Google software really makes those features finally worth it. There's even an Android widget to display your Suica balance.

</comment></comment></comment></comment></comment><comment><USER13> I read this article and it was interesting. Sony can still make some beautifully designed products and even beat Apple in certain ways, the Vaio X had similar capabilities to the MacBook Air and still much lighter and well- designed. However, the greater issue is not the "design by committee" problem but the fact that the entire country is simply lost and headless. It's not only business but politics and society in general.

The reason why companies like Apple, Facebook, and Google inspire is because they do things with conviction. They are executing on vision. They don't let internal processes become ritualized. Key executives don't stick around long when the fire goes out in their soul, they move on. In Japan, nobody knows what they want to do. Japanese manufacturers feel the heat from Apple AND Samsung, they're scared of China's growing clout yet they can't figure out what they want to do.

They can't race to the bottom with an aging population with an acquired taste for high median salaries. They've lost the drive and intellectual fortitude to innovate in all but very limited areas. They don't want to relinquish the "made in Japan" brand, even though the Chinese have shown that with the right management in place, they can make products better and cheaper.

I don't know where this paralysis comes from. Maybe the Japanese think all their woes stem from some economic missteps from the bubble era and once these are righted they can happily resume their old formula for success. Maybe over two decades of stagnation and slow decline lead to a death by a thousand cuts along with the false security of high savings.

For whatever reason, Japan is simply ill-prepared to compete on any level in the global economy. Perhaps the greatest Achilles heel for Japanese manufacturers is not so much the core hardware technology but their utter disregard for the software that drives so many electronics. If you go to any electronics store in Japan you'd be amazed by the utterly useless features manufacturers try to differentiate themselves with (this camera can take pictures in the dark while shaken vigorously, this one makes your face look pretty, etc.).

When the iPhone came out I was one of the skeptics who thought the lack of things like TV reception, RFID cards (used for train passes), the lack of emoji (back then), or the ability to render ketai/mobile web sites wouldn't go down well with customers. However, in the greater scheme of things it didn't matter. Now all the feature phone manufacturers are scuttling decades worth of in-house code to work on Android.

<comment><AUTHOR> I'm the author/translator of this article. Thanks for your thoughts, which I agree with entirely.

I actually think that although the post I translated is interesting, it is in fact missing the point, in a sense. There's a deeper malaise in this country, and although there are bright spots - I'd point to home-grown companies like Cookpad, for example - the overall picture is bleak.

However, Japan has a track record of suddenly changing directions when nobody expects it. Many people thought that 3/11 would trigger a change, and were disappointed when it didn't, or at least not to a significant degree. But if you look deeper, things _are_ changing.

I'm cautiously optimistic. You really have to be. But it will get worse before it gets better.

<comment><USER14> The "overall picture is bleak" if you measure societies by flashy, marketable headline developments and gadgets. It is rather good if you more soberly consider household incomes and trade figures. Japan continues to dominate many high tech industries. Look at the 787; over a third of it is made in Japan and it's all the key hi tech bits like the carbon fiber wings.

Japan may indeed be in some sort of withdrawn middle-class ennui. They're still doing better than the US or Europe in most ways that count.

<http://www.fingleton.net/?p=919>

<comment><AUTHOR> The malaise comes not from the absolute position of Japanese companies in the world, but from the direction they're headed in.

There was a great article in the Economist a while back about this:

<http://www.economist.com/node/14793432>

Since this article was published, the situation has gotten worse. The earthquake sure didn't help, but the situation wasn't good even before that. Sure, 10% or something of the parts that go into the iPhone are developed by Japanese specialized parts manufacturers, who have skills that no-one else in the world can match. But if you look more closely, you'll see that these industries are hollowing out -- there isn't enough interest from younger generations to keep the mom&pop shops going in the long run.

The problem which many have mentioned here and elsewhere is that while Japan is unrivalled in craftsmanship ("monozukuri") -- making physical things -- exactly the opposite is true when it comes to "unphysical" things like software. That's why Japanese mobile phones have such utterly terrible interfaces, as someone else pointed out here. There is very little respect given to that side of the design process, and that's not going to change without a major shift of consciousness.

<comment><USER15> >The problem which many have mentioned here and elsewhere is that while Japan is unrivalled in craftsmanship ("monozukuri") -- making physical things -- exactly the opposite is true when it comes to "unphysical" things like software.

This is something I do not understand. Why is there a cultural aversion to creating beautiful software? As an example, Honda has some of the most beautifully designed interiors in the automotive world. Simple, elegant, functional, with quality materials. The design is often very Apple-like (at least relative to other manufacturers, though they are improving). I would think that the culture that gave us wonderful interaction with a vehicle would be able to provide a similar sort of experience with a phone. What's bizarre is that most pre-iPhone Japanese phones have the UX of a mid-90s Buick: lots of buttons, nothing really arranged properly.

To me it's just strange that they were unable to produce it, but I am not surprised at all that the iPhone is so popular. I feel like the iPhone should have come out of Japan, but didn't.

<comment><AUTHOR> Have you looked at Japanese websites? Most of them have pretty terrible design/UI. It's the same thing.

My take on this is that you have to look more broadly to understand the tendency for cluttered design in Japanese interfaces. Walk around a small neighbourhood in Tokyo and you'll see how cluttered the layout is. On small "roji" (back alleyways), Japanese like to stack potted plants outside their front doors in a pretty disorganized arrangement. Streets are generally not straight, neighbourhoods rarely follow a grid layout.

(Shimokitazawa is probably the best example in Tokyo of this: [http://globalvoicesonline.org/2009/11/04/japan-debating- the-...](http://globalvoicesonline.org/2009/11/04/japan-debating-the-fate-of- shimokitazawa/) )

It's the same thing with cluttered interface design, except that whereas in urban layout it produces something amazingly complex, intricate and fascinating to explore, in UI design it just results in frustration and inefficiency. But I'm convinced the two come from the same source, and that you can't entirely separate them.

The beautifully designed interiors you mention come from a completely different place (mentally, not physically). I don't quite know how to reconcile the fact that the two come from the same country/culture, but I do believe they have both been here for a long long time. It's just that software somehow tends to bring out the former, whereas monozukuri brings out the latter.

<comment><USER16> Concerning websites, when you compare rakuten Japan and say UK, you see a stark difference in how things are presented. This may just be due to the UK site being done outside Japan/by foreigners, but this would hint at a some preference toward clutter for Japanese customers ?

<comment><AUTHOR> The classic case of this is Google vs Yahoo in Japan. Yahoo is more popular, and if you look at the layout, you'll see that it's much more cluttered (or at least, that there's loads more information). At one point Google caved in (in Japan) and added more buttons to their top page, but I see they've switched back to the basic logo + search bar.

Another thing to consider is that the cluttered thing is not only Japan: I've heard that other Asian countries also have a preference for clutter. I can't vouch for whether that's true, but it sounds pretty believable.

<comment><USER16> Yahoo Japan is a pretty Japanese company (dunno about the proportion of Japanese workers there). I only got a very small look at it during interview there, but google Japan seems much more westernized as far as the workforce is concerned.

It would really interesting to know who is responsible for rakuten UK (or any other country). Since prices are in JPY, I am quite confused about the meaning of rakuten UK...

</comment></comment></comment></comment></comment></comment></comment></comment></comment><comment><USER17> > I'm getting sick of these Japanese who love nothing more than to put their > country down.

Sony and many other Japanese companies once pioneered new products - and Sony was the ideal that Steve Jobs said he aimed for. In fact, it's pro-Japanese. Just not its present state.

Christensen (innovator's dilemma guy) thinks that present-day Japan suffers from large companies: the disruptions that are tomorrow's riches start out small and unpredictable. _Small_ is simply not interesting to a big company; _unpredictable_ even less so. In post-war Japan, companies were small: excited about small opportunities; and having little to lose, unafraid of risk. (In contrast, he says, Silicon Valley incumbents often populate their usurpers, such as Fairchild to Intel, when frustrated workers want to exploit something uninteresting to management. This doesn't happen in Japan.)

The enigma here is Apple. The largest company in the world, yet acts like a startup in terms of risky new products in unproven new markets that start out small:

 _launching a product without consumer research is risky._

</comment><comment><USER18> What Apple has executed is actualy mass luxury. Its goods are perceived as high value objects, where status is more important than breadth of functionality (more on this later).

Perception is very important. For instance, a discount store would stack up items and use cheap-looking layout to create the perception that they are cost cutters.

Similarly, a luxury item should be perceived as objet d' art where functionality is clear and straighforward.

Viewed from this perspective, an iPod isn't about inbuilt graphic equalizers. It is about frictionless and effortless getting-music-into-your-hands ease. I remembered that even the Queen wanted an iPod. It is obvious one would know how to use one.

It is the same with the iPhone. The less the engineers talk about dual-core, split antenna, the more they focus on how users interact with their devices. Even the app store is actually a luxury bling. It signals all the things are are potentially available "at your service" without actually cluttering up your device.

<comment><USER19> Apple doesn't really market themselves as a luxury brand. Compare a Mac ad to a Lexus ad, for example.

What you're describing isn't luxury. Having a product where "functionality is clear and straightforward" isn't luxury, and it isn't art. It's good engineering.

<comment><USER20> Apple markets itself as a luxury brand in one of the largest markets in the world: China.

"Apple's image in China now emphasizes not rebellion, but luxury --or as Wolf puts it, "exclusivity." Its gorgeous glass-walled storesare located next to high-end clothing boutiques like Armani, Versace, and BMW Lifestyle."

[http://www.foreignpolicy.com/articles/2011/08/01/red_delicio...](http://www.foreignpolicy.com/articles/2011/08/01/red_delicious_and_rotten?page=full)

</comment></comment></comment><comment><USER21> I've had a feeling for a long time that Japan (not South Korea or China or other regional countries) is on the _verge_ of a massive cultural shakeup.

I can't quite pin it down, but when you peel back the vast homogeneous conformist mass consumer oriented society, there's a really wonderfully quirky, genuinely interesting underground scene that's so vibrant, so full of energy, that it seems like it's about to burst into the mainstream in the same way the beatnick and then hippy movement did in the West.

Steve Jobs came out of that movement, who's to say we aren't about to see the birth of the next Steve Jobs in Japan? Only his parents were in a banjo kettle drum band in Osaka that played basement coffee houses and did cosplay on the weekends to super indie Manga series that explores the meaning of identity as a pop star with only digital, manufactured fans.

In the States Vietnam was the flashpoint that really caused people to gel around the question authority hippy movement, perhaps some current or future event will cause the same with the Japanese youth.

</comment><comment><USER22> Here in Japan, risk is extremely frowned upon. As a result nothing innovate comes about. Only minor improvements over the existing design.

A lot has been written about the cultural views of risk/failure and why nations like the US are kicking butt over Japan and India where you're not allowed to fail.

Japan has shown that it can stage a comeback when the nation as a whole can no longer deny it has been defeated and must reinvent itself to move forward. It happened after WWII and will likely happen in another 10 or 20 years if things continue the way they have.

</comment><comment><USER23> He says the problem is design by focus groups. Consumers know exactly what they want, but when a company produces it, they go buy something else more interesting. I've tried using focus groups back in the last century. It doesnt produce anything useful, except when you are looking for flaws in your product.

<comment><USER24> The problem is that so often users will express their desires not in the most distilled form, they will typically express them in the form of some unimplemented solution that they have arrived at via a process of mental satisficing. They don't know how to design software, or hardware, and they damned sure don't know how it works either. But they sure as hell know that if your product would "just" do this one little thing it would help them out.

The problem, of course, is that you then end up delegating design to people who lack the expertise. You can end up implementing ridiculous features if you just implement suggestions uncritically. For example, if you sell a sports car that people think should be more powerful they could express that by saying it should have a bigger engine, even though there are many ways to approach that problem (EFI programming, turbo chargers, lighter frame, different gear box, etc.) If you end up doing this a lot you end up with a big ball of mud design- wise as everyone's disparate needs and half-thought-out solutions collides with each other.

It takes a lot of effort to take the needs of customers and distill it down into a core set of functions and then tie those functions together in an elegant manner in a cohesive and highly useful design.

If you look at a lot of the "also ran" products from any given genre you will notice a trend towards a chaotic implementation of a laundry list of features whereas the market leaders tend to present a more elegant and cohesive design, even sometimes at the expensive of a handful of features.

<comment><USER25> Great point. Consumers are also heavily biased towards what they already know or see in similar devices - "oh, if it had a removable battery, I need that" or "I need it to vibrate when I type on it," and so on. They might all be valid desires by the consumer, but it doesn't mean it has to be there. Establishing the correct prioritization of features is the principle goal of these product development teams, and Apple seems to be winning there.

</comment></comment></comment><comment><USER26> Fairly mundane observations.

I liked his point that today's Japanese executives are all corporate drones, salarymen that worked their way up through the system and aren't going to boldly design anything.

<comment><USER27> That's really not fair. Some of them are competent foreigners that get thrown out when they expose yakuza cronyism.

[http://online.wsj.com/article/SB1000142405297020365880457663...](http://online.wsj.com/article/SB10001424052970203658804576634792112130906.html)

</comment></comment><comment><USER28> I wonder is part of their failure is from listening to people's reason, such as focusing on the nitty gritty features (see emoji, typing with one hand and so on) rather than on the big picture of the device and how it fits into one's lifestyle.

It's known that humans are ultimately emotional beings, they think with their feelings regardless of how rational they believe they are. The iPhone is the ultimate user experience, titillating the senses and the emotions more than any PDA out there with 1000s of convenience features. It's similar to BMW, Steve Jobs' source of inspiration for his marketing strategies. You want the device on a primal level, it's sexy, it's a status symbol, the release of every iPhone is a cultural event, a celebration of incredible UX.

I never ever get that emotional involvement when looking at the latest super- souped-up swiss-knife phone from Japan.

</comment><comment><USER29> For me the meta insight is that this kind of thinking is a huge deal for startups.

So the challenge is that as a team you are putting together something that probably everyone thinks is useless (or at least only marginally useful), and yet to have to stay focussed on the problem(s) you are addressing and take care to address them cleanly and with style.

It is actually in those places where others cannot see that some of the best ideas can be brought to fruition. Of course releasing too early can lead to disaster (ask the Color folks on that one, at least I perceived it as a PR disaster).

<comment><USER30> > So the challenge is that as a team you are putting together something that > probably everyone thinks is useless

Isn't selection bias a problem with this thinking? Yes companies that are very successful did something outstanding perhaps, going against the flow, but how much do we know about the number of companies that did stuff everyone thought was useless and it was useless and the whole thing flopped?

We hear about the success stories, I want to then also hear about every failed attempt as well, or it not an accurate picture then, is it?

To put it in other words, it is a bit like encouraging people to play the lottery by showing images of winners. "Look these guys flipped a coin, talked to their astrologer and now look, they are winners!". But what about the ones that play and lose?

<comment><USER29> _Isn't selection bias a problem with this thinking?_

It may be, although in my experience 9 - 9.5/10 startups, when measured from concept to death, fail to exit. And many of those were pursuing an idea that clearly wasn't as special as they thought it was for what ever reason (could be early, could be silly, could be too complex)

But to be a startup you have to accept those odds.

</comment></comment></comment><comment><USER31> Great insight into leadership and product decision making strategies, couched in a velour of discontent with the JP status quo.

</comment><comment><USER32> Did anyone bother to do some fact checking? As far as I can tell Android phones are massively outselling iPhones in Japan. Look at any best selling list for phones In Japan before the 4S shipped. Check again in month once the upgraders have upgraded.

</comment><comment><USER33> It's the law of nature at play. The infinite cycle of life and death. Old making way for the new. Apple will go weak one day. Some other company will come to the top. This law of nature cannot be challenged. It is inevitable.

</comment><comment><USER34> This reminds me of Malcolm Gladwell's piece about New Coke in Blink.

<comment><USER29> Should be required reading for marketeers one would think.

</comment></comment><comment><USER35> One thing he didn't mention that I've noticed is that many Japanese companies, particularly in the consumer electronics space but in other industries as well, maintain completely separate product lines outside Japan vs. what they sell here. This is (or was) especially striking with phones where you simply couldn't buy made-for-Japan mobile phones outside Japan, and likewise you couldn't find non-Japanese phones in Japan. This is why it was such a shock that the iPhone was a success here, and the entire emerging smartphone market caught Docomo and AU completely flat-footed.

There is a particularly irritating component of Japanese nationalism which holds that Japanese are unique, as in physiologically unique, among the world's population (down to having different immune systems, in fact). In seems natural for a Japanese company that it would essentially have to act as two companies, one for exported products and another for domestic ones. It's very inefficient. It's also remarkably stupid as the iPhone demonstrates - what sells anywhere else will also sell here, and vice versa (I would always get comments on my phone when I went overseas and had to tell people the model was only available in Japan, to their disappointment).

Contrast this with most other large manufacturers where they will have more- or-less the same products globally, with some localization.

Actually the solution for Japan is rather obvious and I suspect many know it: stop acting as though you're an alien race crash-landed on planet Earth a thousand years ago. Start treating the global market the same as the domestic one, and Japanese the same as Korean, Swedish, Canadian, whatever. This will be a hard lesson for the Japanese national psyche to digest, and I don't know that they're up for it. It's entirely plausible they'll spend the next 50 years making stunning breakthroughs in the fields of (nursing home) robotics and new delivery mechanisms for god-awful Japanese broadcast television.

<comment><USER36> So why would an international company have separate product lines like you mention? It is hard to believe that international businessmen would forgo the opportunity to profit abroad, simply because something is made for the local market. Could it be that Japan only products are more experimental, and when the prove successful, they are rolled out to rest of the world?

<comment><USER35> In the case of mobile phones, if they were in fact experiments they must have considered every experiment a failure, as virtually none of what you saw in the Japanese domestic market informed the design of overseas products. Yet they continued with the same basic design principles year after year. Look some of them up if you like, and you will see what I mean.

They don't see themselves missing out on any opportunity, because they are already certain that their domestic market is fundamentally quite different than every other market in the world, and must be treated as such. This is something fully within the sphere of consensus for them. They aren't behaving like rational actors, but rather like normal humans whose cultural attitudes prevent them from even examining many of their beliefs. Bring it up and you will likely be treated to an expert display of confabulation and rationalization. You can do this with any people on Earth depending on the topic, but the Japanese happened to have picked an unfortunate one.

This is why people think Japanese are xenophobic. They're not, not really. Not any more than most other cultures. But they do tend to think they are very different from everyone else in the world, for better and for worse. This essay is itself a good example, being more _nihonjinron_ navel-gazing.

<http://en.wikipedia.org/wiki/Nihonjinron></comment></comment></comment>


Last minute Kansas City HN Meetup tomorrow night? (Thur, 2/17/2011) - <AUTHOR>

Hey everybody, I'm throwing together a last minute Kansas City Hacker News meetup tomorrow night (Thursday, 2/17/2011).  I apologize for the last minute nature if this thing, but I happen to have the evening free (which rarely happens for me) and I would love to hang out with like minded folks again, as the last KC HN meetup was awesome!
I was thinking 5:30PM, somewhere around downtown, but I'm open to whatever the group wants.
So what do you guys think? <comment><AUTHOR> Alan suggested Pizza Bella, which is fairly central, has free wifi and tasty pizza.

<comment><USER2> <http://www.pizzabellakc.com/>

<http://maps.google.pl/maps/place?cid=2586352277299496039>

<comment><AUTHOR> So it's looking like Pizza Bella, 5:30ish. See you guys there!

</comment></comment></comment><comment><USER3> Sorry, can't make it to this one. I had a lot of fun at the last one, hopefully we can arrange another one in the next month or two!

</comment><comment><USER4> I could come if it was later at like 7:30pm or so. Let me know what the final time is then.

<comment><AUTHOR> Well, I don't know how late everybody will be hanging out, but I have to pick up my son later in the evening, so I won't be able to stay much past 7:30, which is why I suggested meeting earlier. Hopefully we'll be making this type of thing a regular occurrence. Not the last minute part, but the getting together monthly part :-)

</comment></comment><comment><USER5> Boo, not going to be able to make it this time. Wish I can be there tomorrow.

</comment><comment><USER6> I would love too, but I'm going to Manhattan.

</comment><comment><USER2> I'll drop by... Pizza Bella is yummy.</comment>


Bioethicist says parents who don't vaccinate should face liability - <AUTHOR> http://www.pri.org/stories/health/bioethicist-says-parents-who-don-t-vaccinate-should-face-liability-for-consequences-13929.html <comment><USER2> It feels like a reasonable idea. You're not going to get much money. Perhaps you should go after the people promoting the anti-vaccine stance instead?

Measles outbreaks are happening in a few places: (<http://www.bbc.co.uk/news/uk-wales-south-west-wales-22221704>) (<http://www.nyc.gov/html/doh/html/diseases/immmea.shtml>)

Some nurseries in some countries prohibit children that don't have vaccination certificates. That seems reasonable - you can chose which nursery to send your child to.

Andrew Wakefield is a crook. In my opinion he should have paid a huge fine. (<http://tallguywrites.livejournal.com/148012.html>)

</comment><comment><USER3> Typhoid Mary got quarantined against her will for spreading the disease, so this idea is quite similar (but not as extreme). Basically if you're harming others you're liable. There's an interesting text on old cases of healthy carriers at [http://cythereabast.wordpress.com/2007/02/20/the-board-of- he...](http://cythereabast.wordpress.com/2007/02/20/the-board-of-healths- exile-of-mary-mallon-was-it-justifiable/)

<comment><USER4> Typhoid Mary is a great example. You can quibble over the investigative technique and how they perhaps did not treat her with compassion but the fact is that she was killing people and imprisoning her was the only way to spare others. (Thankfully imprisoning is not necessarily in this case.)

</comment></comment><comment><USER5> Vaccines usually don't cause problems, but when they do it is very hard to get those statistics collected. I do have a coworker who lost her hearing due to a bad vaccine. My daughter did have a minor side effect from the measle/chicken pox vaccine. The side typical side effects from each of those vaccines are similar, but since it was a combination vaccine, I'll never know which one/both my daughter had a reaction to. The pediatricians did not care and said it's hard to get the CDC to collect feedback like this. I would argue for singular vaccines and blood test for pre-disposed reactions. In my opinion it's hard to push good science to the medical community, so approaches like this seem to go nowhere.

<comment><USER6> > My daughter did have a minor side effect from the measle/chicken pox > vaccine. The side typical side effects from each of those vaccines are > similar, but since it was a combination vaccine, I'll never know which > one/both my daughter had a reaction to.

Isn't this expected?

</comment></comment><comment><USER7> Since vaccines are not 100% effective why would it incur liability? You can't prove that the person wouldn't have gotten sick with the vaccine.

People should have the right to refuse medical treatment. Can we sue the FDA for with holding treatments that may have prevented death?

<comment><USER8> The problem is herd immunity. If you're okay with getting sick and you opt not to get vaccinated, whatever. You can get sick. The _problem_ is that by getting sick you are now able to spread your affliction onto others, and you're compromising herd immunity.

If enough people get vaccinated, it protects the unvaccinated people as well by stopping the spread of disease. So each person who withholds vaccination increases the chance that the disease will be able to spread and reach _all_ the unvaccinated.

EDIT: To give a more simple example, do you think it's okay for people to show up to work badly ill with the Flu or some other transmissible disease? What if they get the whole team sick? Is that okay?

<comment><USER7> To me vaccines provide enough individual benefit that there is no need for a social solution. Vaccines are not a case of market failure.

Especially in the United States it strikes me as insane that vaccine manufactures are by law not liable for the side effects of vaccines, yet people would propose to hold individual parents liable for not vaccinating their children. (Note: I'm not talking about crazy autism stuff, but the risks that have been proven and for which industry has sought protection)

<comment><USER9> Ignoring for the moment how totally insane our legal system is, I think it's very debatable it's the right tool to deal with side effects.

The thing is, we _know_ there are going to be side effects, some severe, some fatal. The government licenses these vaccines knowing, statistically, that X number of people will get sick, Y crippled, Z killed. But it does this because the alternative is far worse. So as long as it's not stingy, it makes sense for it to run a system (<http://en.wikipedia.org/wiki/Vaccine_court>) to pay out to those families affected, rather than the capricious legal system that won't compensate a lot of people.

As I've noted elsewhere, expose manufacturers to unlimited liability and we eventually won't have any left. We were in fact almost there when the compensation system was changed.

Also, _you_ may not be talking about "crazy autism stuff", but lawyers certainly were and would be if set loose again.

</comment></comment></comment></comment><comment><USER10> If you think vaccines are so effective then take yours, stop worrying, and leave everyone else alone.

Not everyone wants to be part of the herd. Herds get slaughtered.

<comment><USER4> Now _that_ is what I would call a depraved indifference to human life.

<comment><USER10> All science is merely a means to an end. The means is knowledge. The end is control. Beyond this remains only one issue: Who will be the beneficiary?

In 1954 this was the issue of primary concern. Although the so-called "moral issues" were raised, in view of the law of natural selection it was agreed that a nation or world of people who will not use their intelligence are no better than animals who do not have intelligence. Such people are beasts of burden and steaks on the table by choice and consent.

<comment><USER11> Off with you and your conspiration-theory articles. We don't need you here.

</comment></comment></comment></comment><comment><USER12> I am not going to argue against vaccination (which seems to be the target of a lot of conspiration theories), but I am really interested on where are the limits of this logic: are we going to "use" only vaccination or any factor that might/could increase the chances of getting somebody else sick?

</comment><comment><USER13> Who is liable when the child gets sick from the vaccine? It happens. Rarely, but in this country we are supposed to protect the minority and the freedom of choice against coersion, which this is.

<comment><USER9> The government does through an excise tax on covered vaccines and a no-fault court system to cover claims: <http://en.wikipedia.org/wiki/Vaccine_court>

And you should at least admit there are two minorities in the balance, children who's parents refuse to get them vaccinated, and children who are not immunized because they can't take them or don't develop a sufficient response. Too many of the former and the "herd affect" stops protecting the latter.

<comment><USER13> there is a difference between a minority created by inaction and a minority created by forced action.

<comment><USER9> I don't think bacteria and viri care about such differences.

</comment></comment></comment></comment><comment><USER14> The issue has to do with free will. Not much else.

</comment><comment><USER15> This is only acceptable, if vaccinations itself are guaranteed to be 100% safe. Of course then someone should be liable for any damage caused by vaccination.

<comment><USER16> Much popular misinformation notwithstanding, the balance of risk between vaccination and not vaccinating is extremely lopsided. No, vaccination is not perfectly safe. But it is safer than getting sick. And for anyone who is immune compromised (the very young, the very old, people receiving chemotherapy, those with AIDS, etc) their only protection is to have everyone else vaccinated.

The question is at what point your acting on your fringe beliefs are allowed to kill other people, and what liability you should have for it.

And no, this is not a hypothetical point. We have concrete cases of dead babies and known infection vectors. We really can say, "Your decision to not vaccinate killed that baby." In that case why shouldn't you be liable for criminally negligent manslaughter?

<comment><USER17> > In that case why shouldn't you be liable for criminally negligent > manslaughter?

Because causing death through actions which demonstrate depraved indifference to the risk to human life is murder [1], not manslaughter.

[1] [http://criminal.findlaw.com/criminal-charges/second- degree-m...](http://criminal.findlaw.com/criminal-charges/second-degree- murder-overview.html)

<comment><USER16> I think that "depraved indifference to the risk to human life" is a hard standard to meet when the person who didn't vaccinate honestly believed that the vaccine posed a larger risk to their child than their unvaccinated child posed to everyone else.

Compare to [http://criminal.findlaw.com/criminal-charges/involuntary- man...](http://criminal.findlaw.com/criminal-charges/involuntary-manslaughter- overview.html) where the equivalent is "The act either was inherently dangerous to others or done with reckless disregard for human life." The "inherently dangerous to others" standard is much, much easier to prove. And it is easy to prove regardless of the mistaken beliefs of the (ir)responsible parent.

<comment><USER4> In the general case yes, I think you are right.

It is however fairly easy to conceive of scenarios where an individuals inability to understand risks posed by their actions becomes very blurred with a _refusal_ to understand the risks.

Typhoid Mary for example was informed numerous times that she was posing a risk and the fact that they were able to re-find her after she changed her name by following her carnage should have been proof enough to her that they were probably right. I think you could make a reasonable case that Typhoid Mary had a depraved indifference to the risk to human life, even though she claimed to not believe the doctors.

Edit: If you understand herd immunity and decide that you do not care (such as eip here: <https://news.ycombinator.com/item?id=5802206>) then you surely have a depraved indifference to human life. Moreso even than Typhoid Mary could be said to have.

<comment><USER16> For Typhoid Mary, yes. But for most of the cases, you'd have a much harder standard to meet.

Here is an interesting problem. Suppose that we trace a disease through 5 unvaccinated children from the one who picked it up in a foreign country, to the one who passed it on to the baby who died. Who is liable? All 5? The one who passed it on? The one who went to a foreign country while unvaccinated?

<comment><USER4> All those who reasonably had the opportunity to provide their child with a recommended (recommended by _who_ could be debated. I would throw out the CDC as a first suggestion) vaccine that had the possibility of preventing the outbreak, but chose not to.

I think it would be better to tax or fine those who chose to abstain from vaccinating their children than to wait until an incident occurs and try to sue people. Much easier, and it does a better job of driving home the point that by refusing to vaccinate your child you are damaging herd immunity, not just potentially killing particular people.

</comment></comment></comment></comment></comment></comment></comment><comment><USER18> Diversity is good. A few children who are not vaccinated is probably in the best interest of humanity. Imagine at some point in the future a vaccine does cause genetic problems, what then? Do you want to risk 100% of the population on that?

<comment><USER19> There will always be a few unvaccinated children; some kids can't get vaccinated due to other issues. We don't need more people voluntarily exposing their own children to needless risk.

<comment><USER18> I think there has to be a level of tolerance which is justifiable by science and working around the issue by other means -- for instance only so many kids without a certain vaccine can be in the same peer group. Else you are a totalitarian and we've seen that this type of thinking produces problems.

<comment><USER20> Government-enforced mandatory vaccination is what really made inroads into smallpox, a disease which is now eradicated.

Respecting the "diversity" of opinions on the issue would have achieved the opposite.</comment></comment></comment></comment>


Marketing gimmicks from 2029 - <AUTHOR> http://www.onandtrue.com/2012/11/marketing-gimmicks-from-2029.html

<comment><USER2> I'm sorry, but I don't get it (and I work in advertising)

<comment><AUTHOR> doritos flavored bud light? what's not to get?? :)</comment></comment>


Send SnapChat snaps to Facebook - <AUTHOR> http://mysnapsocial.com/

<comment><USER2> doesn't this defeat the purpose of a temporary snapchat?

<comment><AUTHOR> Probably... but more and more people are starting to use snapchat as their camera app (for the build in captioning)</comment></comment>


Coding style and undoing indentation hell - <AUTHOR> http://www.virtualdub.org/blog/pivot/entry.php?id=238 <comment><USER2> I've seen a lot of heavy nesting caused by the belief that functions should only have one return statement. Ex:

        // Original
        function render() {
          $return = null;
          if($condition1) {
            if($condition2) {
              $return = 2;
            } else {
              $return = 1;
            }
          } elseif($condition3) {
            $return = 3;
          } else {
            $return = 4;
          }
          return $return;
        }

But I'd rather read:

        // Refactored
        function render() {
          if($condition1 && $condition2) return 2;
          if($condition1) return 1;
          if($condition3) return 3;
          return = 4;
        }

<comment><USER3> At least have an honest comparison:

       function render() {
          $return = null;
          if($condition1 && $condition2) $return = 2;
          elseif($condition1) $return = 1;
          elseif($condition3) $return = 3;
          else $return = 4;
          return $return
       }

<comment><USER4> Another example

        r = 0;
        outer: {
        foreach (x in a) {
          foreach (y in b) {
            if (condition(a, b)) {
              r = 1;
              break outer;
            }
          }
        }

        return r;

instead of

        foreach (x in a) {
          foreach (y in b) {
            if (condition(a, b)) {
              return 1;
            }
          }
        }

        return 0;

</comment></comment></comment><comment><USER5> It's probably a matter of style at some level.

I hate this style (from the article):

      if (...) {
            if (...) {
                ...
        } else {
            if (...) {
                ...
            } else if (...) {
                ...
            } else {
                ...
            }
        }

and prefer this:

      if (...)
      {
          if (...)
          {
            ...
          }
          else
          {
              if (...)
              {
                ...
              }
              else if (...)
              {
                ..
              }
              else
              {
                ...
              }
          }
      }

The first example is confusing and hard to read. The second is clean and easy to read.

As to the question of optimization, that's a different matter. Lots of tricks can be used to compress code into fewer statements on a case by case basis:

      if(pushbutton == 0)
      {
        led = 12;
      }
      else
      {
        led = 24;
      }

can become

      led = (pushbutton == 0) ? 12 : 24;

or

      led = (pushbutton * 12) + 12;

or

      led = 12 * (pushbutton + 1);

etc.

<comment><USER6> I find the first version easy to read, and the second confusing and hard to read. I believe this is a matter of what a person is more accustomed to, and I learned on the first form and lately have been using the first form more. For me the extra brace below the keywords makes it hard to find the phrase of interest, and the expanded vertical space also makes it more difficult to line up indentation levels. But these visual cues are flexible, and I could learn similar scanning tricks for the second form.

I have worked with people that were dogmatic that one form was objectively better than another form, rather than it being a matter of local optimization in the brain; I have difficult working with these people because they tend to show similar rigidity and confusion of the subjective with the objective in other areas, and such small mindedness limits what type of engineering solutions one is able to come up with.

<comment><USER7> Agreed. If I was forced to pick it would probably be the first one, but other than that I just don't care.

<comment><USER5> Did either of you pick-up the fact that the first version is missing a curly brace? :)

Hard to see. That's my point. And that's why I tend to favor the second style.

I'll use any convention if required, but if given a choice I go for styles that protect me from my own dumb mistakes as much as possible.

</comment></comment></comment></comment><comment><USER8> Don't forget that in many cases, you can replace a conditional with polymorphism. <http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism>

<comment><USER9> You certainly can, but it doesn't mean that you should.

Case in point - Linux networking code, and more specifically sockets handling part. Mr. Kuznetsov did an excellent job abstracting a lot of things behind interfaces (= blocks of function pointers), but at the same time this made it much _much_ harder to follow the code. It's basically impossible to trace the code by hand without a pen and paper.

(edit) To elaborate on the context - reading and tracing the code straight off the source files is a necessity of kernel development, routinely required for both debugging and writing new code.

<comment><USER8> Spend this afternoon figuring out GLOBAL and setting up to work with your editor.

<http://www.gnu.org/software/global/>

<comment><USER9> How would this help to understand what sk->ops[SK_READ]->foo[index](bar) exactly calls?

<comment><USER8> It lets you quickly jump to the definitions of the variables, their types, and their uses. (And then back to where you were.)

It's not going to do all of the work for you, but it'll reduce some of the cognitive load.

<comment><USER9> This is the same as ctags then, and it's completely irrelevant to the issue with over-abstracting things in the code.

</comment></comment></comment></comment></comment></comment><comment><USER9> This -

      if (!test()) {
        handle_failure();
      } else {
        // do lots of work
      }

is just another incarnation of

      if (NULL == v)

i.e. it sacrifices a natural flow of code and makes it harder to follow for something of a superficial value.

Also this -

      if (!test1()) {
          handle_failure_1();
          return false;
      }

is fine _unless_ the function needs to do a cleanup, which is pretty much always the case, and which in turn means that the { } block with grow with every _if_ and it will include a lot of redundant code.

A far cleaner and easier to follow approach is to use if-goto, whereby all cleanup code sits at the bottom of the function (where it naturally belongs) and the flow jumps to the appropriate part of the cleanup on failure. The only exception is when there's no cleanup needed, in which case it can do if- return.

<comment><USER10> I use both if-return and if-goto. In practice you need both, depending on circumstance. In much of my recent code I've managed to use a _lot_ of if- return checks at the top of functions. Another nice thing about a bunch of if- returns at the beginning is it makes a nice checklist of things that will cause the function to fail, all right up front.

<comment><USER9> > _a nice checklist of things that will cause the function to fail_

Should these be assert()s? ;)

<comment><USER11> Not sure if serious, but assert only makes sense in cases where you want to switch off the tests at some point right?

<comment><USER9> Asserts are for enforcing invariants in the code. If you replace an assert with a conditional that allows the execution to continue, you are concealing the problem and making it that much harder to track.

Practically speaking, _your_ function should not be failing because _your_ other code passed it invalid parameters. That's a bug in the former. That's why parameter validity should be asserted.

<comment><USER11> I see. I usually never let execution continue and log + exit instead, but you're right, an assert is easier in that situation.

</comment></comment></comment></comment></comment></comment><comment><USER3> The broad suggestion that indentation is somehow wrong is ill-advised.

Sure, various of the refactorings given are sensible. But the basic problem is not indentation. If something can be simplified, simplify it. If something is too long, break it into pieces. But if something _is_ tree-structured, _that is what it is_ , and it probably ought not be bent out of shape.

(Note: Fowler's refactoring 'Replace Nested Conditional with Guard Clauses' is very specific -- it does not declare that all nesting is bad.)

A tree-like-indentation structure is a perfectly good element of programming -- why try/want to change it into something else?

In fact, a good case could be made that software in its most fundamental essential conception is tree-structured -- even that engineering generally is tree-structured.

</comment><comment><USER12> At this point in my coding life (15 years in), I'm pretty strongly against if / else clauses. The readability of such code just plummets in my view.

I try to limit my conditionals to inline statements:

      $x = $y if $b;

Often joined with early returns:

      return $b if $a;

If I find myself coding an if/else branch, that's often a clue that I should refactor this chunk into a function that can use early returns to avoid nested conditionals:

so

      if ($a == FOO) {
        $c = $d;
        }
      else if ($a == BAR) {
        $c = $e;
        }
      else {
        $c = $f;
      }

becomes

      $c = get_val($a);

    	...

      sub get_val {
       my ($a) = @_;
       return $d if $a == FOO;
       return $e if $a == BAR;
       return $f;
       }

Thankfully much of my coding lately is in perl, which lets me use postfix "if/unless" as well as "and/or" to avoid having to use braced conditionals.

I also love myself the ternary operator. Basically my take comes down to "use conditionals for one-line assignments only, NOT for block execution".

</comment><comment> jack-r-abbit I'm glad I am not the only that is particular about these things. Computers may not care which order your IF statement is in... but some people completely disregard that their code is going to be read by humans too.

</comment><comment><USER13> Generally good advice, but w/r/t the first recommendation, I prefer to structure if/else clauses so that common case is handled first and the exceptional case is handled last.

<comment><USER10> As shown in the article, that first recommendation leads directly to the next step(s). In the ideal case (which actually happens sometimes in the real world!), you end up with something like this:

        if (bad1) fail();
        if (bad2) fail();
        if (bad3) fail();

        step1();
        step2();
        step3();
        step4();
        return SUCCESS;

To me, this is a very nice way to structure things when you can. You get a checklist of things that might be wrong, and then comes the wonderfully naive straightforward implementation.

<comment><USER14> Stating failures first can also be considered analogous to input validation, preconditions, or declaring the domain for which the function is undefined. Some related discussion on here: <http://c2.com/cgi/wiki?GuardClause>

</comment></comment></comment><comment><USER15> meh. when i'm looking for a bug, i tend to start in the places with lots of branching. in general, high quality code doesn't have much branching, and if you find yourself neding complicated and nested branching, there is probably a better way to factor your code.

one easy trick is to structure your code such that 'null' is impossible, by initializing to an empty value, or re-ordering the way things happen, or using exceptions or error-monad.

</comment><comment><USER16> I have to run so this is really a substandard comment for hacker news, but... Really? He advocates adding multiple exit points to a function as a way of REDUCING COMPLEXITY? The solution when you have too deep of nesting is to pull out inner parts into useful simpler stateless functions, or so I was led to believe!

</comment><comment><USER17> He's preaching to the choir in my case. I'm a big fan of busting out of functions/methods early when you already know "it's over". (sometimes this means putting the cleanup in something like a try/finally wrapper routine, though)

But, kudos: I can send this to my team instead of having to write it myself. Win!

</comment><comment><USER18> The _goto_ cleanup strategy can be improved upon by using multiple _goto_ labels, like here: <http://vilimpoc.org/research/raii-in-c/>

<comment><USER19> Or just test the resource handles you opened, and only close them if they're valid. That way, you don't have to worry about doing a goto to the wrong label, or messing up the order of cleanup.

        BOOL do_stuff_with_resources()
        {
            int success = FALSE;

            char *memBuf = (char *) malloc(256 * 1024);
            if (NULL == memBuf) goto cleanup;

            if (randBomb()) goto cleanup;

            FILE *fp = fopen("dummy-file.txt", "w");
            if (NULL == fp) goto cleanup;

            if (randBomb()) goto cleanup;

            int sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (-1 == sock) goto cleanup;

            if (randBomb()) goto cleanup;

            int shmId = shmget(0x1234ABCD, 256*1024, IPC_CREAT);
            if (-1 == shmId) goto cleanup;

            shmRegion = (char *) shmat(shmId, NULL, 0);
            if ((char *) -1 == shmRegion) goto cleanup;

            if (randBomb()) goto cleanup;

            sem_t st = -1;
            if (-1 == sem_init(&st, 0, 1)) goto cleanup;

            if (randBomb()) goto cleanup;

            // TODO: Do stuff

            success = TRUE;

        cleanup:
            if(-1 != st)
            {
                sem_destroy(&st);
            }
            if(-1 != shmId)
            {
                shmctl(shmId, IPC_RMID, NULL);
            }
            if(-1 != sock)
            {
                close(sock);
            }
            if(NULL != fp)
            {
                fclose(fp);
            }
            if(NULL != memBuf)
            {
                free(memBuf);
            }

            return success;
        }

</comment></comment><comment><USER20> If you do your indentation "wrong" and nothing breaks, then you will do your indentation "wrong". That's why I find whitespace-sensitive languages easier to read, YMMV.

<comment><USER21> The article talks about unwinding deeply nested control structures, which is equally possible in whitespace sensitive languages.

</comment></comment><comment><USER22> He's basically a step away from having several objects (let's call them handlers) which can do your handling for you. Further, they can define the set of circumstances in which they are valid.

I'm going to work with a couple of assumptions:

1) The test casts which he refactors to test*() methods are non-trivial 2) The handlers _may_ be large sets of code

Here's a way to handle one of this refactored methods:

if (!test1()) { handle_failure_1(); return false; }

if (!test2()) { handle_failure_2(); return false; }

if (!test3()) { handle_failure_3(); return false; }

handle_success(); return true;

That's a lot of potential code we're dealing with in this class.

What if:

class HandlesFailure1

      def handles_this_case(params)
         #code from test1()
      end

      def handle(params)
        #code from handle_failure_1()
        return false;
      end

end

class HandlesFailure2

      def handles_this_case(params)
         #code from test2()
      end

      def handle(params)
        #code from handle_failure_2()
        return false;
      end

end

class HandlesFailure3

      def handles_this_case(params)
         #code from test3()
      end

      def handle(params)
        #code from handle_failure_3()
        return false;
      end

end

class HandlesSuccess

      def handles_this_case(params)
        return true
      end

      def handles(params)
        //code from handle_success
        return true
      end

end

#And now the original class

class DoesSomething

      #There are ways to set this up fairly easily. One simple way it to just new it up here, but you could auto-wire it too
      handlers = [HandlesFailure1, HandlesFailure2, HandlesFailure3, HandlesSuccess]

      def do_something(params)

        handlers.each do |handler|
          return handler.handle(params) if handler.handles_this_case(params)
        end

      end

end

There. Now there's a loop and an if. Check each case and either handle or toss it out. This can also work for the case where you might want multiple handlers to handle something, just don't return on the first one.

I'm not saying it's the right way, but it's another way.

Pros: It really helps to group together the handling methods with the test methods. Very simple dispatch method

Cons: Separate classes, and harder to view all the handlers together.

</comment><comment><USER23> I agree with most of what was said, especially the use of goto! I don't like success boolean, but that's probably just me.

<comment><USER24> I used to be a big goto-error-cleanup proponent, but ultimately gave it up. The resulting code is cleaner, but the bug it's trying to treat (returning without correctly cleaning up) is still too easy. Complicated functions end up with 4-5 cleanup labels and it's hard to look at them and understand the resource acquisition order.

Generally these days I prefer functional decomposition for that (actually honestly I'm preferring C++ RAII style where you get the cleanup for free in almost all cases). That is, do something which requires cleanup (e.g. allocate memory, take a mutex, etc...), call a function to "initialize" the thing you just did, check results and free it on failure. So the allocation and cleanup happen next to each other in the code. Nest as needed for complicated resource strategies, and it scales well. No one is ever confused about what the state is supposed to be.

<comment><USER23> The problem isn't with 1 resource. It is with 2 or more, right? You successfully allocate the first, but the second fails and so you have to go back and deallocate the first. The goto strategy avoids code repetition.

RAII is the best part about C++!

</comment></comment></comment><comment><USER25> I stopped reading when he recommended if-goto.

<comment><USER26> Sure, goto was abused, but it's no worse than (or even better than) using continuations or using break and continue.

<comment><USER27> Any of those mysterious jump-to-somewhere-else code features resemble goto. Not that I don't think they clean up some nesting issues, but they're pretty much the same thing as goto.

</comment></comment></comment><comment><USER28> Someone would sure enjoy golang!

<comment><USER29> More specifically, the `defer` keyword lets you handle cleanup in the case of failure a bit more neatly.

The gotos can be replaced with stuff like this:

        foo, err := bar()
        if err != nil {
          return err
        }
        defer foo.cleanup() // or what have you

Now, right before the function returns, Go will call `foo.cleanup()` and your `cleanup()` call sits right next to the initialization code. It's a lot easier to tell whether or not you are (or someone else is) doing cleanup properly.</comment></comment>


Ask HN: Why most product launches fail? - <AUTHOR> <comment><USER2> Because most people would rather prepare for a product launch than go out and find actual users (because that's harder) and a product launch looks like productive work and talking to people is hard because they probably won't care about the product.

Good luck.

</comment><comment><USER3> because not enough research was done prior - without research, talking to customers, getting feedback before launching, you will often end up with a product no one wants. for a product launch to be successful, it has to have a "wow" effect. having a "wow" effect means solving a problem that is really annoying with a great solution - this requires a complete understanding of the problem.</comment>


Molten: A modern Python (3.6+) web framework - <AUTHOR> https://moltenframework.com/v0.5.2/index.html <comment><AUTHOR> Bogdan has put together an awesome framework with molten that I think can use a lot more visibility. With his permission, I've posted here to get more eyes on it. I'm excited to see how much attention it's getting.

For those who want to get started with molten, I've put together a boilerplate for a more full fledged production application here: [https://github.com/dternyak/molten- boilerplate](https://github.com/dternyak/molten-boilerplate)

It demonstrates:

\- OpenAPI (swagger)

\- SQLAlchemy

\- alembic

\- py.test

\- invoke (task management / CLI)

Feedback is super welcome on the boilerplate, which is partially inspired by [https://github.com/Bogdanp/molten_cookiecutter](https://github.com/Bogdanp/molten_cookiecutter)

Bogdan has been incredibly friendly and helpful while I've been learning the ins and outs (and pestering him over email). I'm sure he'll be happy to answer any questions here as they come up.

Happy hacking!

<comment><USER2> How does this compare with Connexion?

Uses Swagger/OpenAPI that then uses convention (or fully defined) packages, and methods for REST. Runs on top of Flask, and does a lot of all of the validation all from the yaml file. Plumbing taken care for you, etc. so you can focus on business logic?

<comment><USER3> I'm not familiar with Connexion (this was my first time hearing about it), but it seems, from reading its README, that the two approaches are polar opposites: in Connexion you write the schema first and that is used to hook up your API to your business logic, whereas in molten you write your API using normal Python code and idioms and an OpenAPI schema is generated from that code. As a user of Molten, you don't need to know anything about OpenAPI to be able to use it.

<comment><USER2> Molten does what I've seen in RoR land do. You decorate and document your schema. It then can spit out an OpenAPI spec, use its schema and tooling around OpenAPI.

So it becomes a choice. A decision of writing mostly OpenAPI, or writing Python via an API that is defined by someone (or a small set of people).

I'd personally rather learn OpenAPI specs as you're going to live in that world anyways, as it gives you so much tooling.

It's not hard, and you could take that yaml file and generate code for other languages in case Python's performance specifically for that API (especially it if is a microservice), runs too slowly in the real world and need a faster runtime, etc.

</comment></comment></comment></comment><comment><USER4> So refreshing to see a new Python web framework that isn't trying to hoist more event-based non-blocking IO on us.

<comment><USER5> I get that SA ORM is unfit to run on the eventloop thread, but I'm increasingly unclear if you hold your position that asyncio is bad solely because it makes SA ORM less competitive - and less of a ecosystem standard.

The alternative being just using SA Core and something like aiopg, using asyncpg, or using SA in a threadpool (unfortunately, a technique that's involved enough that the recipe for using SA isn't a 5 min "gotcha", re: flask).

I like SA. I've used it for years, and you've helped me on the forums, so I'm appreciative for the work you've done. I just don't understand why you've written off an entire style of programming.

<comment><USER4> > but I'm increasingly unclear if you hold your position that asyncio is bad > solely because it makes SA ORM less competitive - and less of a ecosystem > standard.

It's not that the ORM is less "competitive" because I am certainly able to make an async version of SQLAlchemy, it's just I don't have the time / interest / resources to do so, and as I've gone through the effort to write about in detail, it is a _bad idea_. If you want to pay me a salary to make an async SQLAlchemy I can totally do that. It would be a worthwhile effort in that it would make people happy. But also it would be a wasteful effort in terms of advancing the field of Python database programming. That's the decision I'm facing and it would be a lot easier if folks would just realize asyncio isn't getting them much overall.

It's like, suppose I make bikes. But everyone wants to get to work on pogo sticks instead. Everyone who uses pogo sticks is terminally late to work, they're getting injured all the time, they are miserable, but someone told them "hey pogo sticks are FASTER than bikes!", people were just bored with bikes so much that they didn't even bother testing this assertion, and now everyone just has discussions like "oh well I have this shiny new pogo stick, so I only broke three ribs this week! hooray!" and people have just forgotten that there is nothing wrong with bikes at all and they are in fact a lot better than pogo sticks for the task of getting to work every day (you might find pogo sticks to be more _interesting_ and _fun_ in the moment, but as a real solution to the problem, they are not any better than bikes and probably worse). Someone who makes bikes tries to point all of this out. That puts you in the position of saying, "all your arguments about bikes being better than pogo sticks for getting to work, who cares. you are just concerned pogo sticks are a threat to your bike sales". Well, yes, they _are_. But the bigger issue is that it is ridiculous everyone is killing themselves trying to get to work on pogo sticks. Somehow I feel that should not be lost.

> I just don't understand why you've written off an entire style of > programming.

I've written and tweeted about this a lot so feel free to point out the reasons that might not be clear. To recap [http://techspot.zzzeek.org/2015/02/15/asynchronous-python- an...](http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and- databases/):

asyncio is essentailly intended to provide an interface around the concept of non-blocking IO. The relational database use case, for the vast majority of uses (e.g. CRUD), gains nothing from using non-blocking IO (most databases don't even offer a non-blocking API anyway) and only complicates the application, introduces subtle bugs, and does not improve performance. The other argument made about asyncio is that replacing the OS'es task scheduler with a cooperative one defined by when IO happens to occur is "safer", because context switches are no longer implicit. The second section of the post above makes many arguments why this is not the case and especially not for modern server-side application design which is inherently multi-process.

<comment><USER5> I don't know, an asyncio ORM version seems very challenging, but if anyone could do it, it'd be someone with deep domain knowledge (like you).

Relationships as properties for example, I just don't know how you'd solve attribute access in an idiomatic way (sure it could return a future, so maybe the idea is that you'd get a future subclass that still supports operations)?

Anyway, the problem is that it's really difficult to mix sync/async code. And as soon as you've got a need for websockets, you're pretty much thrown into the world of asyncio. To use the ORM is then a threadpool issue.

Anyway, my approach has instead been to use SA Core (with aiopg). I've probably always gotten to involved with my Mappers anyway.

<comment><USER4> > Relationships as properties for example, I just don't know how you'd solve > attribute access in an idiomatic way (sure it could return a future, so > maybe the idea is that you'd get a future subclass that still supports > operations)?

I think the answer would be that you just ditch "lazy loading" altogether, in the spirit of asyncio's theme that "implicit IO is bad", you'd have to have explicit conversations with the DB. Loading attributes from relationships is one thing, but there's also the notion that other kinds of attributes can refresh themselves if they happen to have been expired, which is something the ORM does when a server-side rule or a transaction boundary that might mean the attribute changes on the database side. It's a very elegant and simple solution to the problem but if you have decided that implicit IO is bad, it means you don't really want that anymore. You'd just start treating an ORM mapped object more like an active row and you'd have yields on most operations, and you'd also want to add more coarse-grained boundaries to when state is expired and re-loaded (e.g., instead of expiring particular attributes as needed to be reloaded when accessed, there would need to be a more formal "refresh the object" kind of step).

That's one way to do it. Another way would be if an implicit non-blocking approach such as gevent could be cleanly integrated with asyncio - then object heavy database interactions could simply be inside of a block written in "blocking IO" style, and that entire block is entered as a yield. There is no technical reason this can't be done. The reason is cultural; people who like asyncio really hate implicit IO. So trying to make that work seems like it wouldn't be very worth it either.

> Anyway, the problem is that it's really difficult to mix sync/async code.

I think this is because people just aren't working on the problem. You read asyncio tutorials and they say things like, "if you really MUST use evil threads...here's this crappy executor thing we think you should never use", I'm exaggerating a bit but that's kind of the vibe they send off. Making the asyncio / thread transition could be done _very_ nicely, and there can also be integrations between gevent style and asyncio style, and finally there are many other ways to use non-blocking IO without using a full event style programming interface. The asyncio crowd isn't there yet. They are still having the endorphin high of asyncio "clicking" for them and they are rigidly dogmatic and pretty short on real benchmarks that show actual gains. I have nothing against using non-blocking IO but the next time I have to use it, I'm going to purposely build a non-blocking IO library that seamelessly makes use of threads and queues and shows how easy it is if you really need to reach out to a dozen slow web services at once to get the non-blocking IO advantages without turning your entire codebase and dependencies inside out.

> Anyway, my approach has instead been to use SA Core (with aiopg)

right, so another thing to keep in mind, Postgresql is the _only_ database that has a native non-blocking protocol. So building an async ORM is immediately limited by that - for every other database there would still be a threadpool running the socket conversation, and having every database message be a separate threaded unit is less efficient than just having the entire transactional conversation in one threaded unit (hundreds or thousands of shifts in and out of the thread pool vs. just one). There's really many reasons to not write an asyncio ORM right now.

</comment></comment></comment></comment></comment><comment><USER6>
        app = App(
        components=[
            DBComponent(),
            TodoManagerComponent(),
        ],
        routes=[
            Include("/todos", [
                Route("/", list_todos),
                Route("/", create_todo, method="POST"),
            ]),
        ],

)

Wonder what this would look like for a _real_ app and not a toy.

<comment><AUTHOR> Had the same thought, so I built [https://github.com/dternyak/molten- boilerplate](https://github.com/dternyak/molten-boilerplate)

Gets you pretty close to what a production app looks like.

Feedback welcome!

</comment></comment><comment><USER7> If the author or someone cares to share I'm curious about the decision not to build this on asyncio

<comment><USER3> Here are my reasons:

* I am not a fan of asyncio's API (`ensure_future`), docs (though I understand these two are improving in 3.8) and of the fact that it is incompatible[1] with much of the existing ecosystem of libraries (eg. the SQLAlchemy ORM or any existing libraries that talk to... anything over the network (postgres, redis, memcached, etc.) which need to be written from the ground up in asyncio style or rewritten so their protocol parsing logic is completely separate from the IO that they do (not a bad thing, mind you, but taking battle-tested libraries and rewriting them from the ground up is not the greatest idea)), tools and even builtins (queue.Queue vs asyncio.Queue).

* I don't buy into the claimed benefits of explicitly marking yield points: any sufficiently complex code will have enough yield points (`async with`, `async for`, `await`) that reasoning about concurrency in the program isn't going to be any easier than if it had implicit yield points.

* I think ergonomics matter for developer happiness and programming with asyncio is not ergonomic in the slightest.

* File IO is blocking.

Put all of those together and you end up with a system where you can't use any of the popular, battle-tested, libraries out there, where your code is more verbose for minimal gain and where seemingly benign things (reading a file, using a `for` instead of an `async for`) may greatly impact the performance of your program all for a small increase in throughput (assuming it does increase!).

[1]: [http://journal.stuffwithstuff.com/2015/02/01/what-color- is-y...](http://journal.stuffwithstuff.com/2015/02/01/what-color-is-your- function/)

<comment><USER8> 1) This is fair.

2) Explicit yield points certainly save you from most of the classic threading errors, and having to use special maps and datastructures everywhere.

3) Other than tying into (1) I guess this is a matter of taste.

4) Supposedly this refers to the `open` function? This can be solved using the `aiofiles` module, but again I suppose this ties into (1).

<comment><USER4> > 2) Explicit yield points certainly save you from most of the classic > threading errors, and having to use special maps and datastructures > everywhere.

"classic threading errors" don't apply to the users of a web framework where you are programming logic that shares nothing with other threads. Additionally, the most free-of-race-conditions monolithic application loses all of that advantage the moment it is placed in a multi-process environment, where other copies of it on the same host or other hosts are competing for the same resources. There is no non-trivial web application today that is deployed to production in a single process on a single host only. Web applications are not scaled vertically.

<comment><USER9> > Web applications are not scaled vertically.

Should be rare, but believe stackoverflow was doing that for a while.

</comment></comment></comment></comment></comment><comment><USER10> This looks very cool. Is there a reason the HTTP response codes and many other things are exposed as magic string constants?

</comment><comment><USER11> How does this compare with Flask?

<comment><USER12> It seems to come with ORM and request validation, metrics, etc. built-in. Flask is fast for getting started but you end up rebuilding most of the things this framework does on your own as your application grows.

It seems like a good middle ground between Flask (minimal and no batteries included) and Django (bloated but very powerful).

<comment><USER13> I don't see the ORM or metrics in the docs.

After a cursory look at it, this seems like an interesting, modern replacement for Flask. Types-first frameworks are interesting, as they're still very rare right now.

<comment><USER14> _" The molten.contrib package contains various functionality commonly required by APIs in the real world such as configuration files, prometheus metrics, request ids, sessions, SQLAlchemy, templating, websockets and more."_

<comment><USER13> Ah! Missed that, thank you :)

</comment></comment></comment></comment></comment><comment><USER15> Kind of reminds me of [https://github.com/timothycrosley/hug](https://github.com/timothycrosley/hug) , especially using type hints for validation of request parameters.

<comment><USER16> Also similar to Tom Christie's APIStar [https://github.com/encode/apistar](https://github.com/encode/apistar)

<comment><USER3> APIStar was a major inspiration[1]! One of the reasons I built Molten was because Tom Christie took APIStar in a different[2] direction.

[1]: [https://moltenframework.com/motivation.html](https://moltenframework.com/motivation.html)

[2]: [https://docs.apistar.com/#where-did-the-server- go](https://docs.apistar.com/#where-did-the-server-go)

</comment></comment></comment><comment><USER17> I recently started my first Falcon project, but this looks closer to what I was actually hoping Falcon would be. Definitely going to give this a spin, thanks.

<comment><USER17> OK, I've been playing with this for an hour or so now and it's magnificent. Exactly what I needed, thank you.

</comment></comment><comment><USER18> Bitdefender sees this site as dangerous? Admittedly it is quite overzealous but something you should look into!

</comment><comment><USER19> In Python 2, omitting (object) inheritance in a class definition had an actual effect. Is something different in Python 3 that makes this okay, or are we doing the less okay thing because it's cleaner?

<comment><USER20> Yes, it has no effect in python3. There are no old style classes.

<comment><USER19> Oh that's just wonderful.

Thank you.

<comment><USER21> Python 3 cleaned up a lot of other language warts like that one (though some may disagree as to whether or not they were warts). No more `super(SuperLongClassNameHere, self).method()`, no more having to teach beginners to always use raw_input() instead of input(), `0 > None` now raises an exception rather than evaluating to `True`.

I personally wish they would just make `self` implicit, but I understand that that adds a lot of magic in a language that currently doesn't have a lot.

<comment> another-cuppa > I personally wish they would just make `self` implicit

Hell no. Go use Java if you want that. If you find typing self is making you _more_ work then you're not using classes correctly. Write functions and use classes if you need them.

<comment><USER21> edit: To be clear, I mean making `self` implicit in the method signature - _not_ implicit in the method body like the way Java does it.

It's a very minor and aesthetic/cosmetic thing. No, I don't write classes for everything. I write functions for things that should be functions and classes for things that should be classes. But when I do write classes, it's annoying to remember to write `self` in the method signature, annoying to get exceptions because I forgot to add it, annoying to see it since it's just that tiny bit of additional redundant line noise when I just want to quickly glance at a method signature. And literally no other OO language does this that I'm aware of; even ones that are generally way less dynamic than Python.

But as I said, I do understand how it came about and why it is the way it is. But on the other hand, it was the exact same story for `super()`, and they did resolve that with "magic". The "magic" floodgates have also opened up a bit more with string interpolation added [1]. So now I think a more reasonable case can be made for making `self` optional. If they could do it for `super()`, they can do it for `self`. It doesn't annoy me that much, though, and I still plan to use Python for a long time even if it's never changed.

[1] [https://www.python.org/dev/peps/pep-0498/](https://www.python.org/dev/peps/pep-0498/)

<comment><USER19> Do you mean remove self from the method signature or altogether?

I think the latter is fundamentally impossible. There would be name collisions and it would be horribly ambiguous. I assume you're suggesting the former.

I can see it being plausible. I'm not sure I have a really clear case against it. I do really like that things are explicit. There's no magical place "self" emerges from. I hate this about some other languages, like JavaScript's 'attributes' collection that magically exists in a function context.

Being able to juggle binded and unbinded functions is nice. The explicit self or cls kind of forces you to declare what the intent of your function is.

Not super clear. But the ship has sailed on that issue. Not sure it could be changed in a non breaking way.

<comment><USER21> Ah sorry, I meant from the method signature. I wouldn't like the totally implicit `self` / `this` found in Java.

>Being able to juggle binded and unbinded functions is nice. The explicit self or cls kind of forces you to declare what the intent of your function is.

Sure, but we can already do that with the @classmethod decorator. They could just make it so `cls` is a variable that can be accessed from any method. If it's a class method, `cls = self`, otherwise, `cls = self.__class__`.

</comment></comment></comment></comment></comment></comment></comment></comment><comment><USER22> This looks pretty clean. I would like to see benchmarks that compare between Flask and especially Falcon, which IMO is the gold standard for fast, minimal API frameworks.

<comment><USER3> There are some benchmarks[1] in the molten repo as well as instructions for running them yourself. On my machine it ends up being faster than Flask and nearly as fast as Falcon.

[1]: [https://github.com/Bogdanp/molten/tree/master/benchmarks](https://github.com/Bogdanp/molten/tree/master/benchmarks)

</comment></comment><comment><USER23> What's the benefit / key differences compared to falcon?

[https://falconframework.org](https://falconframework.org)

<comment><USER24> Well, the front page illustrates them quite well, I think.

<comment><USER23> Errr, I'm looking for some words to answer the question, not to try to infer at an expert level by reading a large amount of detailed technical information, and I didn't see a comparison with falcon, so no, it does not.

<comment><USER3> I've used Falcon extensively for about 3 years while at LeadPages.

I would say the biggest difference between the two is Molten gives you more out of the box: input validation, doc/schema generation, ORM support, support for multipart/form-data requests (Falcon doesn't actually handle these out of the box!), etc.

<comment><USER23> So molten is batteries included essentially, whereas falcon is not.

Like flask versus Django.

Straight question, wouldn't it have been easier to fork falcon and add the batteries?

<comment><USER3> Probably not, because many of the differences are fundamental:

* Falcon revolves around the concept of Resources, i.e. classes as the primary handlers of requests; molten revolves around functions,

* Falcon supports Python 2.x,

* automatic dependency injection via type annotations is core to molten.

</comment></comment></comment></comment></comment></comment><comment><USER25> Does python 3.6 support type hinting? This reminds me of php 7+ with scalor types, and return types now. Didn't think python supported this.

<comment><USER26> Yes, Python introduced static type hinting in version 3.5

[https://www.python.org/dev/peps/pep-0484/](https://www.python.org/dev/peps/pep-0484/)

<comment><USER27> Python introduced the 'typing' module in the standard library in 3.5, and declared that henceforth the annotation syntax was for type hints.

Python introduced the annotation syntax (for everything except variables/attributes) in 3.0. The annotation syntax for variables/attributes was introduced in 3.6.

</comment></comment></comment><comment><USER28> Is this competing with flask or with Django?

<comment><USER29> I would say Flask.

</comment></comment><comment><USER30> Post title needs to have "API" in it.</comment>