Shared posts

01 May 05:13

Impostos, e o que eles compram.

by Tiago de Thuin
Sim, eu sei que falar desse jeito, de um ramerrame tão chato quanto impostos, e sem ser diretamente dentro de uma grande narrativa - pró ou contra- parece estranho, nestes tempos que correm sob o signo da emoção. Mas acho que é importante, considerando-se a importância de questões relacionadas a déficits e impostos nos dias que correm, ter a percepção correta do que impostos e carga tributária são. Afinal, fala-se muito em "aumento da carga tributária" - e vai se ver, e os impostos não aumentaram, aumentou a formalização. Mas a impressão que ficou foi do aumento do imposto...

Não é problema só de impostos e carga tributária, claro. Um dos problemas mais comuns da nossa época é a reificação das estatísticas. Traduzindo o palavrão: é a tendência de pessoas a lerem estatísticas como dados da realidade bruta, mesmo quando essas estatísticas na verdade refletem todo um sistema de dados amealhados, interpretados, selecionados, e processados. Isso vale para a maioria das pessoas, pouco à vontade com números em geral, mas é um mal do século, comum a todo mundo, inclusive aos estudiosos de ciências sociais. Pode ser, inclusive, resultado da necessidade do discurso: é preciso falar alguma coisa, as estatísticas não são realmente confiáveis para serem comparadas, mas são o que temos, então falamos delas como se fossem reais. E aí alguém vem e pega o que foi falado, e usa por sua vez, e o "assumindo-se que assim seja" se perde pelo caminho, e uma comparação tortuosa vira um fato, às vezes com resmas de explicações complexas em cima. As coisas mais simples e aparentemente óbvias não são tanto assim. Por exemplo: o dia de trabalho no Brasil e nos EUA é de oito horas. Nos EUA, isso é chamado de "9 to 5." Aqui, geralmente é de 8 às 5. A diferença é que no Brasil temos uma hora de almoço obrigatória - que não é contada dentro do horário de trabalho. Mas americanos - dizem - também almoçam. E então, o que seria "certo" nessa comparação? Dizer que o brasileiro empregado formalmente tem um dia de trabalho de nove horas, descontar do tempo do americano o tempo de almoço... o mais simples, é claro, é simplesmente utilizar o tempo formal. De novo: o brasileiro tem direito a trinta dias corridos de férias. Na maioria dos países da Europa, as férias obrigatórias são de vinte e cinco dias úteis. E por aí vai...

Um desses números que parecem simples mas encerram em si todo um discurso é o da carga tributária. Gente bem melhor que eu já falou da carga tributária líquida, a diferença entre o custo efetivamente gasto pelo governo e aquele dinheiro que é só redistribuído, na forma de transferências diretas, por ele, mas o que quero falar é de outra coisa: o gasto do governo propriamente dito que é pago com "carga tributária" em cada país não é, nem remotamente, comparável. Não estou falando da qualidade do serviço, a clássica reclamação da classe média brasileira, mas de que as estruturas pelas quais as nações oferecem diferentes serviços a seus cidadãos são diferentes; a definição do que é e não é Estado é mais complexa do que à primeira feita parece. Mas diferentes de tal modo que é difícil, mesmo, reduzir essa diferença a um número. Um dos exemplos mais flagrantes: a carga tributária japonesa é bem menor do que a da França. Eficiência do modelo japonês... ou porque universidades e saúde são pagos do bolso do cidadão no Japão, ao invés de majoritariamente pelos cofres públicos, e os subsídios ao transporte são muito menores (o Estado dá, ao invés disso, às companhias de trem vastas áreas urbanas para desenvolver como imobiliária, e empréstimos a juro baixo via bancos e parabancos estatais). 

E essa comparação entre o Japão e a França nem é tão estranha quanto a comparação que se faz entre a carga tributária brasileira e a de países ricos para reclamar que o retorno "não é semelhante." Primeiro porque, como já disse na resposta ao gringo picareta, renda não é riqueza, e serviços públicos também são riqueza. Segundo porque a comparação entre percentuais não faz sentido; tente exigir comprar uma casa igual à do Bill Gates pela mesma porcentagem das suas economias que ele gastou. Terceiro pela diferença entre carga tributária líquida (que não deixa de ser um serviço público, mas para a qual não cabe falar de eficiência do estado, já que quem recebe sabe muito bem o quanto recebe). E quarto, finalmente, pela diferença de "pacotes de serviços" oferecidos pelos diferentes governos. Ah sim, um quinto: pela existência de receitas extraordinárias, não-tributárias, como são o petróleo e outros hidrocarbonetos nos países exportadores. 

Não é uma diferença pequena, circunstancial. Mesmo para empresas sofisticadas é difícil julgar entre preços de pacotes de serviços diferentes para tomar uma decisão; é por isso que muitas agências reguladoras mundo afora, e em especial os bancos centrais, exigem algum tipo de estandardização de pacotes de serviços por seus regulados, até, em alguns casos, a nível internacional. E entre os "pacotes de serviços" dos governos não há estandardização nenhuma, a tal ponto que fica difícil até julgar a diferença, de tal modo as estruturas são diferentes. Uma obra que tentasse fazer um esboço do esboço de um estudo comparativo real entre essas estruturas, sopesando cada particularidade e transformando-a num número, ou em meia dúzia, seria tão grossa (assim de deixar os calhamaços do Braudel ou do Osterhammel parecendo panfletos) quanto cheia de "assumindo-se-que." 

Longe de tentar atacar essa cavalariça de Áugias, tentei só fazer uma conta bem mais grosseira, que resumo na tabela abaixo. A conta começa na parte fácil (PIB do país per capita multiplicado pela carga tributária - o que ignora inteiramente a questão da progressividade do gasto e de quanto efetivamente um dado cidadão paga), e junta uma das coisas mais simples de se definir à parte entre os grandes gastos públicos, que é o financiamento da saúde. Porque, se vários países têm sistemas de saúde universal, como esse sistema de saúde é universal está bem longe de ser uniforme. Basicamente, se tem os sistemas como o SUS, chamados de "pagador único," em que o Estado mantém, via impostos, um sistema de saúde que é inteiramente grátis pra quem chegar e aparecer, e modelos de planos de saúde regulados e subsidiados, mas que têm, obrigatoriamente, que ser pagos pelo cidadão além dos impostos. Na prática, portanto, poder-se-ia chamar esse pagamento de imposto também - e um imposto bastante regressivo, já que não guarda relação nenhuma com a renda de quem paga. Mas o Obamacare, ou a Krankenversicherung, ou o Kokuminkenkoohoken, não entram pra estatística de carga tributária. Faz sentido: não são impostos entregues ao Estado, mas pagamento a empresas privadas. Por outro lado, são pagamentos que o Estado obriga que se faça a essas empresas privadas, que são pesadamente reguladas e imbricadas na estrutura do Estado.

A tabela abaixo, então, longe de tentar sistematizar e conceitualizar essas diferenças importantes, tem apenas uma ideia modesta de, imaginando bem ao gosto neoliberal o Estado como um "pacote de serviços," mostrar o que está incluído nesse pacote, e quanto ele custa aos cidadãos. (Em dólares, não em % do PIB - cf. "construir uma mansão que nem a do Bill Gates com a mesma proporção da minha renda.) (Os números pra PIB e carga tributária foram conseguidos na wikipédia.)


País
Carga tributária em % do PIB
Carga tributária per capita, em dólares PPP
O que é pago com impostos
O que é pago pelo cidadão médio, obrigatoriamente, hors imposto
Brasil
35,7
5.265
Saúde
Universidade pública
Educação (todos os níveis; terciária restrita)
Previdência

EUA
26,9
14.458
Previdência
Subsídio a combustíveis
Educação (até média)
Saúde (restrita)
Saúde - 3552

Alemanha
40,6
18.521
Educação (todos os níveis)
Subsídio a transportes
Saúde - 4460
Japão
29.5
11.148
Previdência
Subsídio à saúde
Saúde - 1500
Educação (todos os níveis) - 3750+
China
28,1
2.226
Educação (até média)
Subsídio a educação superior
Saúde (parcialmente)
Subsídios ao transporte
Saneamento e energia subsidiados
Saúde - 200
França
44,6
17.184
Previdência
Subsídio à saúde
Educação (todos os níveis)
Subsídios pesados ao transporte
Saúde - 1600
Reino Unido
34,4
14374
Previdência
Saúde
Educação (até média)
Subsídios à educação superior


Argentina
37,2
7625
Previdência
Educação (todos os níveis)
Saúde (restrita)
Subsídios ao transporte
Saúde - 1200




21 Dec 19:39

Book Review: House of God

by Scott Alexander

I’m not a big fan of war movies. I liked the first few I watched. It was all downhill from there. They all seem so similar. The Part Where You Bond With Your Squadmates. The Part Where Your Gruff Sergeant Turns Out To Have A Heart After All. The Part Where Your Friend Dies But You Have To Keep Going Anyway. The Part That Consists Of A Stirring Speech.

The problem is that war is very different from everything else, but very much like itself.

Medical internship is also very different from everything else but very much like itself. I already had two examples of it: Scrubs and my own experience as a medical intern (I preferred Scrubs). So when every single personin the medical field told me to read Samuel Shem’s House of God, I deferred. I deferred throughout my own internship, I deferred for another two years of residency afterwards. And then for some reason I finally picked it up a couple of days ago.

This was a heck of a book.

On some level it was as predictable as I expected. It hit all of the Important Internship Tropes, like The Part Where Your Attendings Are Cruel, The Part Where Your Patient Dies Because Of Something You Did, The Part Where You Get Camaraderie With Other Interns, The Part Where You First Realize You Are Actually Slightly Competent At Like One Thing And It Is The Best Feeling In The Universe, The Part Where You Realize How Pointless 99% Of The Medical System Is, The Part Where You Have Sex With Hot Nurses, et cetera.

All I can say is that it was really well done. The whole thing had a touch of magical realism, which turns out to be exactly the right genre for a story about medicine. Real medicine is absolutely magical realist. It’s a series of bizarre occurrences just on the edge of plausibility happening to incredibly strange people for life-and-death stakes, day after day after day, all within the context of the weirdest and most byzantine bureaucracy known to humankind.

Just in the past week, for example, I had to deal with an aboulomaniac patient – one with a pathological inability to make up his mind. He came to my clinic for treatment, but as soon as he saw me, he decided he didn’t want treatment after all and left. The next day, he was back on my calendar – he’d decided he needed treatment after all – but when his appointment came around, he chanegd his mind and left again. This happened five times in five days. Every day he would phone in asking for an appointment. Every day I would give it to him. Every day he would leave a minute or two before it began. Unsure how to proceed, I sought out my attending. He ignored my questions, pulled me into a side office, took out his cell phone, and started playing me a video. It’s a scene from his musical, The Phantom Of The Psychiatric Unit, which he’s been forcing his interns to rehearse after rounds. I watched, horrified. It was weirdly good.

If I were to write a book about this kind of thing, people would criticize me for being unrealistic. The only way to get away with it is to pass it off as “a touch of magical realism”, and this The House of God does to excellent effect.

The story revolves around an obvious author-insert character, Roy Basch MD, who starts his internship year at a hospital called the House of God (apparently a fictionalized version of Beth Israel Hospital in Boston). He goes in with expectations to provide useful medical care to people with serious diseases. Instead, he finds gomers:

“Gomer is an acronym: Get Out of My Emergency Room. It’s what you want to say when one’s sent in from the nursing home at three A.M.”

“I think that’s kind of crass,” said Potts. “Some of us don’t feel that way about old people.”

“You think I don’t have a grandmother?” asked Fats indignantly. “I do, and she’s the cutest dearest, most wonderful old lady. Her matzoh balls float – you have to pin them down to eat them up. Under their force the soup levitates. We eat on ladders, scraping the food off the ceiling. I love…” The Fat Man had to stop, and dabbed the tears from his eyes, and then went on in a soft voice, “I love her very much.”

I thought of my grandfather. I loved him too.

“But gomers are not just dear old people,” said Fats. “Gomers are human beings who have lost what goes into being human beings. They want to die, and we will not let them. We’re cruel to the gomers, by saving them, and they’re cruel to us, by fighting tooth and nail against our trying to save them. They hurt us, we hurt them.”

This is where the magical realism starts to come in:

Rokitansky was an old bassett. He’d been a college professor and had suffered a severe stroke. He lay on his bed, strapped down, IV’s going in, catheter coming out. Motionless, paralyzed, eyes closed, breathing comfortably, perhaps dreaming of a bone, or a boy, or of a boy throwing a bone.

“Mr. Rokitansky, how are you doing?” I asked.

Without opening his eyes, after fifteen seconds, in a husky slurred growl from deep down in his smushed brain he said: PURRTY GUD.

Pleased, I asked, “Mr. Rokitansky, what date is it today?”

PURRTY GUD. .

To all my questions, his answer was always the same. I felt sad. A professor, now a vegetable. Again I thought of my grandfather, and got a lump in my throat. Turning to Fats, I said, “This is too sad. He’s going to die.”

“No, he’s not,” said Fats. “He wants to, but he won’t.”

“He can’t go on like this.”

“Sure he can. Listen, Basch, there are a number of LAWS OF THE HOUSE OF GOD. LAW NUMBER ONE: GOMERS DON’T DIE.”

“That’s ridiculous. Of course they die.”

“I’ve never seen it, in a whole year here,” said Fats.

“They have to.”

“They don’t. They go on and on. Young people – like you and me – die, but not the gomers. Never seen it. Not once.”

“Why not?”

“I don’t know. Nobody knows. It’s amazing. Maybe they get past it. It’s pitiful. The worst.”

Potts came in, looking puzzled and concerned. He wanted the Fat Man’s help with Ina Goober. They left, and I turned back to Rokitansky. In the dim half-light I thought I saw tears trickling down the old man’s cheeks. Shame swept over me. My stomach churned. Had he heard what we’d said?

“Mr. Rokitansky, are you crying?” I asked, and I waited, as the long seconds ticked away, my guilt moaning inside me.

PURRTY GUD.

“But did you hear what we said about gomers?”

PURRTY GUD.

Someone once said that the point of art is to be more real than reality. The House Of God is way more real than reality. Reality wishes it could be anywhere close to as real as The House of God. This is a world where young people – the kid just out of school, the blushing new mother – die. Even normal old people – your grandmother, your grandpa – can die. But the most decrepit, demented people, the ones for whom every moment of artificially-prolonged life is a gratuitous misery and you pray at every moment that God will just let them find some peace – somehow they never die. They come into the hospital, they go back out to nursing homes, a few weeks later they’re back in the hospital, a few weeks later they’re back in their nursing homes, but they never die. This can’t be literally true. But it’s the subjective truth of working in a hospital. The Fat Man is right. I’ve been working in medicine for three years now, and I have seen my share of young people tragically cut off in the prime of life, and yet as far as I can remember I have never seen a gomer die. The magical realism of House of God describes the reality of medical professionals infinitely better than the rational world of hospital mortality statistics.

In the world of The House of God, the primary form of medical treatment is the TURF – the excuse to get a patient out of your care and on to somebody else’s. If the psychiatrist can’t stand a certain patient any longer, she finds some trivial abnormality in their bloodwork and TURFs to the medical floor. But she knows that if the medical doctor doesn’t want one of his patients, then he can interpret a trivial patient comment like “Being sick is so depressing” as suicidal ideation and TURF to psychiatry. At 3 AM on a Friday night, every patient is terrible, the urge to TURF is overwhelming, and a hospital starts to seem like a giant wheel uncoupled from the rest of the world, Psychiatry TURFING to Medicine TURFING to Surgery TURFING to Neurosurgery TURFING to Neurology TURFING back to Psychiatry again. Surely some treatment must get done somewhere? But where? It becomes a legend, The Place Where Treatment Happens, hidden in some far-off hospital wing accessible only to the pure-hearted. This sort of Kafkaesque picture is how medical care feels, and the genius of The House of God is that it accentuates the reality just a little bit until its fictional world is almost as magical-realist as the real one.

In the world of The House of God, medical intervention can only make patients worse:

Anna O. had started out on Jo’s service in perfect electrolyte balance, with each organ system working as perfectly as an 1878 model could. This, to my mind, included the brain, for wasn’t dementia a fail-safe and soothing oblivion of the machine to its own decay?

From being on the verge of a TURF back to the Hebrew House for the Incurables, as Anna knocked around the House of God in the steaming weeks of August, getting a skull film here and an LP there, she got worse, much worse. Given the stress of the dementia work-up, every organ system crumpled: in a domino progression the injection of radioactive dye for her brain scan shut down her kidneys, and the dye study of her kidneys overloaded her heart, and the medication for her heart made her vomit, which altered her electrolyte balance in a life-threatening way, which increased her dementia and shut down her bowel, which made her eligible for the bowel run, the cleanout for which dehydrated her and really shut down her tormented kidneys, which led to infection, the need for dialysis, and big-time complications of these big-time diseases. She and I both became exhausted, and she became very sick. Like the Yellow Man, she went through a phase of convulsing like a hooked tuna, and then went through a phase that was even more awesome, lying in bed deathly still, perhaps dying. I felt sad, for by this time, I liked her. I didn’t know what to do. I began to spend a good deal of time sitting with Anna, thinking.

The Fat Man was on call with me every third night as backup resident, and one night, searching for me to go to the ten o’clock meal, he found me with Anna, watching her trying to die.

“What the hell are you doing?” he asked.

I told him.

“Anna was on her way back to the Hebrew House, what happened – wait, don’t tell me. Jo decided to go all-out on her dementia, right?”

“Right. She looks like she’s going to die.”

“The only way she’ll die is if you murder her by doing what Jo says.”

“Yeah, but how can I do otherwise, with Jo breathing down my neck?”

“Easy. Do nothing with Anna, and hide it from Jo.”

“Hide it from Jo?”

“Sure. Continue the work-up in purely imaginary terms, buff the chart with the imaginary results of the imaginary tests, Anna will recover to her demented state, the work-up will show no treatable cause for it, and everybody’s happy. Nothing to it.”

“I’m not sure it’s ethical.”

“Is it ethical to murder this sweet gomere with your work-up?”

There was nothing I could say.”

After learning these medical secrets, Dr. Basch uses hook and crook to prevent his patients from getting any treatment. They end up healthier than anyone else in the hospital, and Basch becomes a contender for “Most Valuable Intern” – in typical House of God style, nobody knows if this award really exists or is just a rumor. His colleagues compete for another award, the “Black Crow”, which goes to the intern who gets the most autopsy consents from grieving families – and which the administration doesn’t realize incentivizes doctors to kill their patients. This is so reminiscent of the bizarre incentive systems in real hospitals that it hurts.

But as the year goes on, everyone gets more and more frazzled. One intern has a mental breakdown. Another commits suicide by jumping out of a hospital window (this isn’t dramatic exaggeration by the way; three junior doctors have committed suicide by jumping out of windows in the past three years in New York City alone). Dr. Basch runs through all sorts of interesting forms of neurosis. Finally, the end of the year approaches, the original crop of interns thinned-out but triumphant – and then they realize they have to do the whole thing again next year as residents, which is maybe a little less grueling but still in the same ballpark.

So they decide, en masse, to go into psychiatry, well-known to be a rare non-terrible residency. The author of House of God is a psychiatrist, so I guess this is only a spoiler insofar as you aren’t logically omniscient. When the Chief of Medicine learns that every single one of his hospital’s interns are going into psychiatry and there aren’t going to be any non-psychiatry residents in the whole hospital…

…okay, fine, I won’t spoil the ending. But suffice it to say I’m feeling pretty good about my career path right now.

II.

House of God does a weird form of figure-ground inversion.

An example of what I mean, taken from politics: some people think of government as another name for the things we do together, like providing food to the hungry, or ensuring that old people have the health care they need. These people know that some politicians are corrupt, and sometimes the money actually goes to whoever’s best at demanding pork, and the regulations sometimes favor whichever giant corporation has the best lobbyists. But this is viewed as a weird disease of the body politic, something that can be abstracted away as noise in the system.

And then there are other people who think of government as a giant pork-distribution system, where obviously representatives and bureaucrats, incentivized in every way to support the forces that provide them with campaign funding and personal prestige, will take those incentives. Obviously they’ll use the government to crush their enemies. Sometimes this system also involves the hungry getting food and the elderly getting medical care, as an epiphenomenon of its pork-distribution role, but this isn’t particularly important and can be abstracted away as noise.

I think I can go back and forth between these two models when I need to, but it’s a weird switch of perspective, where the parts you view as noise in one model resolve into the essence of the other and vice versa.

And House of God does this to medicine.

Doctors use certain assumptions, like:

1. The patient wants to get better, but there are scientific limits that usually make this impossible
2. Medical treatment makes people healthier
3. Treatment is determined by medical need and expertise

But in House of God, the assumptions get inverted:

1. The patient wants to just die peacefully, but there are bureaucratic limits that usually make this impossible
2. Medical treatment makes people sicker
3. Treatment is determined by what will make doctors look good without having to do much work

Everybody knows that those first three assumptions aren’t always true. Yes, sometimes we prolong life in contravention of patients’ wishes. Sometimes people mistakenly receive unnecessary treatment that causes complications. And sometimes care suffers because of doctors’ scheduling issues. But it’s easy to abstract away to an ideal medicine based on benevolence and reason, and then view everything else as rare and unfortunate deviations from the norm.

House of God goes the whole way and does a full figure-ground inversion. The outliers become the norm; good care becomes the rare deviation. What’s horrifying is how convincing it is. Real medicine looks at least as much like the bizarro-world of House of God as it does the world of the popular imagination where doctors are always wise, diagnoses always correct, and patients always grateful.

There have been a couple of studies finding that giving people health insurance doesn’t make them any healthier – see for example the RAND Health Insurance Experiment and the Oregon Medicaid Experiment. I’ve always been skeptical of these studies, because it seems logical that people who can afford health care will get more of it, and there are ten zillion studies showing various forms of health care to help. Insulin helps diabetes. Antibiotics help sepsis. Surgery helps appendicitis. To deny claims like these would be madness, yet the studies don’t lie. What is going on?

And the answer has to be somewhere in the bizarro-world of House of God. Real medical treatment looks precious little like the House MD model of rare serious disease -} diagnosis -} cure. At least as often, it’s like the House of God model where someone becomes inconvenient -} send to hospital -} one million unnecessary tests. Everyone agrees this is part of the story. House of God is a brilliant book in that it refactors perception to place it in the foreground.

But it’s brilliant because in the end it’s not just a romp through hilarious bureaucratic mishaps. There is as much genuine human goodness and compassion in this book as there is in any rousing speech by a medical school dean. The goodness is often mixed with horror – the doctor who has to fight off hordes of autopsy-consent-form-seekers to let a dying patient spend his last few seconds in peace, or the one who secretly slips euthanasia to a terminal patient begging for an end to the pain because he knows it’s the right thing to do.

The question posed here is “what do you do in a crazy cannibalistic system where it’s impossible to do good work and everyone is dying all around you?”, and the answer is “try as hard as you can to preserve whatever virtue you can, and to remain compassionate and human”. The protagonist swings wildly between “this is all bullshit and I’ll just make fun of these disgusting old people and call it a day” and “I need to save everybody and if I don’t I should hate myself forever”, and eventually like everybody, comes to some kind of synthesis where he recognizes he’s human, recognizes that his patients are human, and tries to deal with it with whatever humor and grace he can manage.

It’s hard enough for a book to be funny, and it’s hard enough for one to be deep, but a book like House of God that can be both at once within the space of a few sentences is an absolute treasure.

III.

I talked to my father about House of God, and I told him a few parts that seemed unrealistic. He told me that those parts were 100% true in 1978 when the book was written. I looked into it more, and ended up appreciating the work on a whole new level.

Uncle Tom’s Cabin is credited with kickstarting the emancipationist movement and maybe even causing the Civil War. The Jungle is famous for launching a whole new era of safety regulations. House of God has a place beside them in the pantheon of books that have changed the world.

The book’s “Second Law” is “GOMER GOES TO GROUND”: demented old people will inevitably fall out of their hospital bed and injure themselves. The book has a whole funny/horrifying scene where the senior resident explains his strategy for this eventuality: He leaves their beds low enough that patients won’t kill themselves when they fall, but high enough that they’ll probably break a bone or two and have to go to orthopaedic surgery – which takes them off his hands. Later, a medical student apes this procedure, a patient falls and breaks a bone or two, and everyone freaks out and tells him that it was a joke, that of course you don’t really arrange skeletal fractures for old people just to save yourself time, what kind of heartless moron could think such a thing? This is some nth-level meta-humor: the reader probably mistook it for real advice because it meshes so seamlessly with all of the other madness and horror, yet most of the other madness and horror in the book is easily recognizable by practicing doctors as a real part of the medical system. Actually, on the n+1st meta-level, I’m not at all sure that the resident wasn’t meant to be completely serious and then backtracked and called it a joke when it went wrong. For that matter, I’m far from sure this wasn’t a real medical practice in the 1970s.

I see enough falls that I wasn’t surprised to see them as a theme, but I thought the book exaggerated their omnipresence. My father said it didn’t – there were just far more falls back in the Old Days. Now hospitals are safer and falls are comparatively rare. Why? Because the government passed a law saying that insurance wouldn’t pay hospitals extra money for the extra days patients have to stay due to fall-related injuries. I am so serious about this. This, I think, is the n+2nd meta-level; amidst all its jokes-played-straight the book treats encouraging falls as an actual in-universe joke, and yet in the real world once hospitals were no longer incentivized to let patients fall the falls stopped.

How did people become aware of this kind of thing? How did the movement against it start? A lot of it seems to be because of House of God. Everyone in medicine knew about this sort of thing. But House of God made it common knowledge.

People were scared to speak up. Everyone thought that maybe they were just a uniquely bad person, or their hospital a uniquely bad institution. Anyone who raised some of these points was met with scorn by prestigious doctors who said that maybe they just weren’t cut out of medicine. House of God shaped medicine because it was the first thing to say what everybody was experiencing. Its terms like “gomer” and “turf” made it into the medical lexicon because they pointed to obvious features of reality nobody had the guts to talk about before.

Shem writes an afterword where he talks about the reaction to the book. Junior doctors and the public loved it. Senior doctors hated it. He tells the story of going to a medical conference. Someone asked who he was, and he said jokingly “I’m the most hated doctor here”. His interlocutor answered “Oh, don’t worry, I’m sure you’re not as bad as the guy who wrote that House of God book.”

But House of God gets credit for helping start movements to cut intern work hours, protect doctors from sleep deprivation, reduce patient falls, and teach empathy and communication skills. The moral of the story is: the courage to tell the truth is rare and powerful. More specifically: the courage to tell the truth is rare and powerful not just in Stalinist dictatorships and violent cults, but in apparently normal parts of everyday First World life. All of these differently loaded terms like “culture of silence” and “political correctness” point at a fear of rocking various boats with nothing but your imperfect first-person knowledge to go on. But a tiny crack in the wall can make a big difference.

IV.

In a closing scene, Dr. Basch and all of his fellow interns – interns who had broken into tears weekly, gotten burnt out, starting seeing psychiatrists, considered suicide, all this stuff, these interns who had smashed up against the unendurable horrors of medicine and held themselves together only by the promise that it would soon be over – the minute they graduate internship they change their tune:

It looked like all but two or three [interns] would stay. The Runt and I were definitely leaving; Chuck hadn’t yet said. The others were staying. In years to come they would spread out across America into academic centers and Fellowships, real red-hots in internal medicine, for they had been trained at the Best Medical School’s best House, the House of God. Although a few might kill themselves or get addicted or go crazy, by and large they’d repress and conform and perpetuate the Leggo [the Chief of Medicine] and the House and all the best medical stuff. [Eddie] had been praised by the Leggo that he could start off the second year as ward resident, with “a free rein” on his interns. And so, saying already that the internship been “not so bad,” he was preparing to indoctrinate his new charges: “I want them on their knees from day one.”

Shem’s author mouthpiece character Berry says:

It’s been inhuman. No wonder doctors are so distant in the face of the most poignant human dramas. The tragedy isn’t the crassness, but the lack of depth. Most people have some human reaction to their daily work, but doctors don’t. It’s an incredible paradox that being a doctor is so degrading and yet is so valued by society. In any community, the most respected group are doctors. [It’s] a terrific repression that makes doctors really believe that they are omnipotent healers. If you hear yourselves saying, ‘Well, this year wasn’t really that bad,’ you’re repressing, to put the next group through it. [But] it’s hard to say no. If you’re programmed from age six to be a doctor, invest years in it, develop your repressive skills so that you can’t even recall how miserable you were during internship, you can’t stop.

Shem’s thesis is that it isn’t just about not wanting to make waves or offend the Chief of Medicine. It’s about denying your own pain by identifying with the system.

This puts me in a weird spot. My internship (I find myself saying) wasn’t so bad. I can give you some arguments why this might be true – things have gotten a lot better since The House of God was published (with no small credit to Shem himself), a small community hospital in Michigan is less intense than Harvard Medical School’s training hospital, psychiatry interns sometimes have it easier than internal medicine interns since everyone knows this isn’t a permanent deal for them.

And yet I distinctly remember one night a long time ago, coming home from high school. I had noticed that all of the adults around me said high school was some of the best years of their lives and I would miss it when I was gone, and yet high school seemed objectively terrible. I wondered if there might be some bias or bizarre shift in memory that happened sometime in people’s twenties and gave them a localized amnesia or insanity. So I very distinctly recall telling myself “My current assessment is that high school is terrible, and if you ever find yourself remembering that high school was lovely, please be aware that your memories have been hijacked by some malevolent force.”

And God help me, but every single part of my brain is telling me that high school was lovely. I fondly remember all the friends I made, the crazy teachers I had to put up with, the science competitions I won, the lunches spent in the library reading whatever random stuff I could get my hands on. It seems like it was a blast. It’s hard for me to even trust that one memory as anything more than imagination or the product of a single bad day. But although high-school-me had a lot of issues, he generally had a decent head on his shoulders, and if he says my memories have been hijacked, then I grudgingly believe him.

So was my intern year a good learning experience? I have no idea and I’m not sure anyone else does either. It’s another type of figure-ground inversion: parade of horrors broken only by the occasional triumph, or clear sailing with a few bad moments?

On my last day of internship, one of my colleagues who was moving on said “I’m going to miss hating this place”. I’ve always remembered that phrase. Now I wonder if it’s some kind of weird snapshot of the exact moment of transition, the instant when “nightmarish ordeal” morphs into “halcyon days of youth”. This is why medicine has to be written as magical realism. How else to capture a world where people reliably go from agony to Stockholm Syndrome in the space of a day, and where the transition is so intermixed with the general weirdness that it doesn’t even merit special remark?

I found myself having more emotions reading House of God than I’ve had about anything in a long time. I don’t really know why. But I think it has something to do with this resignation to the general incommunicable weirdness all around anyone who works in medicine. Somehow Shem manages to avoid the normalization of insanity that happens to every young doctor, capture the exact subjective experience and write it down in a way that makes sense. And then, having put his finger right on the unbearable thing, he makes it funny and beautiful and poignant.

I tell her. Again I tell her about Dr. Sanders bleeding out in my lap, about the look in Potts’s eyes that night before he jumped, about my pushing the KCl into poor Saul. I tell her how ashamed I am for turning into a sarcastic bastard who calls the old ones gomers, how, during the ternship, I’d ridiculed them for their weaknesses, for throwing up their suffering in my face, for scaring me, for forcing me to do disgusting things to take care of them. I tell her how I want to live, compassionately, with the idea of death clearly in sight, and how I doubt I can do that, ever again. As I think back to what I’d gone through and what I’d become, sadness wells up and mixes with contempt. I put my head into Berry’s folds and weep, and curse, and shout, and weep.

“. . . and in your own way, you did. Someone had to care for the gomers; and this year, in your own way, you did.”

“The worst thing is this bitterness. I used to be different, gentle, even generous, didn’t I? I wasn’t always like this, was I?”

“I love who you are. To me, underneath it all, you’re still there:” She paused, and then, eyes sparkling, said, “And you might even be better.”

“What? What do you mean?”

“This might have been the only thing that could have awakened you. Your whole life has been a growing from the outside, mastering the challenges that others have set for you. Now, finally, you might just be growing from inside yourself.

He also frames all of it in the language of psychoanalysis, which is jarring and sounds preachy. I’ve ordered the sequel, Mount Misery, about his training as a psychoanalyst. Expect a review of that soon.

04 Dec 19:53

What So Many People Don’t Get About the U.S. Working Class

by brandizzi
nov16-10-55948705

My father-in-law grew up eating blood soup. He hated it, whether because of the taste or the humiliation, I never knew. His alcoholic father regularly drank up the family wage, and the family was often short on food money. They were evicted from apartment after apartment.

He dropped out of school in eighth grade to help support the family. Eventually he got a good, steady job he truly hated, as an inspector in a factory that made those machines that measure humidity levels in museums. He tried to open several businesses on the side but none worked, so he kept that job for 38 years. He rose from poverty to a middle-class life: the car, the house, two kids in Catholic school, the wife who worked only part-time. He worked incessantly. He had two jobs in addition to his full-time position, one doing yard work for a local magnate and another hauling trash to the dump.

Throughout the 1950s and 1960s, he read The Wall Street Journal and voted Republican. He was a man before his time: a blue-collar white man who thought the union was a bunch of jokers who took your money and never gave you anything in return. Starting in 1970, many blue-collar whites followed his example. This week, their candidate won the presidency.

For months, the only thing that’s surprised me about Donald Trump is my friends’ astonishment at his success. What’s driving it is the class culture gap.

One little-known element of that gap is that the white working class (WWC) resents professionals but admires the rich. Class migrants (white-collar professionals born to blue-collar families) report that “professional people were generally suspect” and that managers are college kids “who don’t know shit about how to do anything but are full of ideas about how I have to do my job,” said Alfred Lubrano in Limbo. Barbara Ehrenreich recalled in 1990 that her blue-collar dad “could not say the word doctor without the virtual prefix quack. Lawyers were shysters…and professors were without exception phonies.” Annette Lareau found tremendous resentment against teachers, who were perceived as condescending and unhelpful.

Michèle Lamont, in The Dignity of Working Men, also found resentment of professionals — but not of the rich. “[I] can’t knock anyone for succeeding,” a laborer told her. “There’s a lot of people out there who are wealthy and I’m sure they worked darned hard for every cent they have,” chimed in a receiving clerk. Why the difference? For one thing, most blue-collar workers have little direct contact with the rich outside of Lifestyles of the Rich and Famous. But professionals order them around every day. The dream is not to become upper-middle-class, with its different food, family, and friendship patterns; the dream is to live in your own class milieu, where you feel comfortable — just with more money. “The main thing is to be independent and give your own orders and not have to take them from anybody else,” a machine operator told Lamont. Owning one’s own business — that’s the goal. That’s another part of Trump’s appeal.

Hillary Clinton, by contrast, epitomizes the dorky arrogance and smugness of the professional elite. The dorkiness: the pantsuits. The arrogance: the email server. The smugness: the basket of deplorables. Worse, her mere presence rubs it in that even women from her class can treat working-class men with disrespect. Look at how she condescends to Trump as unfit to hold the office of the presidency and dismisses his supporters as racist, sexist, homophobic, or xenophobic.

Trump’s blunt talk taps into another blue-collar value: straight talk. “Directness is a working-class norm,” notes Lubrano. As one blue-collar guy told him, “If you have a problem with me, come talk to me. If you have a way you want something done, come talk to me. I don’t like people who play these two-faced games.” Straight talk is seen as requiring manly courage, not being “a total wuss and a wimp,” an electronics technician told Lamont. Of course Trump appeals. Clinton’s clunky admission that she talks one way in public and another in private? Further proof she’s a two-faced phony.

Manly dignity is a big deal for working-class men, and they’re not feeling that they have it. Trump promises a world free of political correctness and a return to an earlier era, when men were men and women knew their place. It’s comfort food for high-school-educated guys who could have been my father-in-law if they’d been born 30 years earlier. Today they feel like losers — or did until they met Trump.

Manly dignity is a big deal for most men. So is breadwinner status: Many still measure masculinity by the size of a paycheck. White working-class men’s wages hit the skids in the 1970s and took another body blow during the Great Recession. Look, I wish manliness worked differently. But most men, like most women, seek to fulfill the ideals they’ve grown up with. For many blue-collar men, all they’re asking for is basic human dignity (male varietal). Trump promises to deliver it.

The Democrats’ solution? Last week the New York Times published an article advising men with high-school educations to take pink-collar jobs. Talk about insensitivity. Elite men, you will notice, are not flooding into traditionally feminine work. To recommend that for WWC men just fuels class anger.

Isn’t what happened to Clinton unfair? Of course it is. It is unfair that she wasn’t a plausible candidate until she was so overqualified she was suddenly unqualified due to past mistakes. It is unfair that Clinton is called a “nasty woman” while Trump is seen as a real man. It’s unfair that Clinton only did so well in the first debate because she wrapped her candidacy in a shimmy of femininity. When she returned to attack mode, it was the right thing for a presidential candidate to do but the wrong thing for a woman to do. The election shows that sexism retains a deeper hold that most imagined. But women don’t stand together: WWC women voted for Trump over Clinton by a whopping 28-point margin — 62% to 34%. If they’d split 50-50, she would have won.

Class trumps gender, and it’s driving American politics. Policy makers of both parties — but particularly Democrats if they are to regain their majorities — need to remember five major points.

Understand That Working Class Means Middle Class, Not Poor

The terminology here can be confusing. When progressives talk about the working class, typically they mean the poor. But the poor, in the bottom 30% of American families, are very different from Americans who are literally in the middle: the middle 50% of families whose median income was $64,000 in 2008. That is the true “middle class,” and they call themselves either “middle class” or “working class.”

“The thing that really gets me is that Democrats try to offer policies (paid sick leave! minimum wage!) that would help the working class,” a friend just wrote me. A few days’ paid leave ain’t gonna support a family. Neither is minimum wage. WWC men aren’t interested in working at McDonald’s for $15 per hour instead of $9.50. What they want is what my father-in-law had: steady, stable, full-time jobs that deliver a solid middle-class life to the 75% of Americans who don’t have a college degree. Trump promises that. I doubt he’ll deliver, but at least he understands what they need.

Understand Working-Class Resentment of the Poor

Remember when President Obama sold Obamacare by pointing out that it delivered health care to 20 million people? Just another program that taxed the middle class to help the poor, said the WWC, and in some cases that’s proved true: The poor got health insurance while some Americans just a notch richer saw their premiums rise.

Progressives have lavished attention on the poor for over a century. That (combined with other factors) led to social programs targeting them. Means-tested programs that help the poor but exclude the middle may keep costs and tax rates lower, but they are a recipe for class conflict. Example: 28.3% of poor families receive child-care subsidies, which are largely nonexistent for the middle class. So my sister-in-law worked full-time for Head Start, providing free child care for poor women while earning so little that she almost couldn’t pay for her own. She resented this, especially the fact that some of the kids’ moms did not work. One arrived late one day to pick up her child, carrying shopping bags from Macy’s. My sister-in-law was livid.

J.D. Vance’s much-heralded Hillbilly Elegy captures this resentment. Hard-living families like that of Vance’s mother live alongside settled families like that of his biological father. While the hard-living succumb to despair, drugs, or alcohol, settled families keep to the straight and narrow, like my parents-in-law, who owned their home and sent both sons to college. To accomplish that, they lived a life of rigorous thrift and self-discipline. Vance’s book passes harsh judgment on his hard-living relatives, which is not uncommon among settled families who kept their nose clean through sheer force of will. This is a second source of resentment against the poor.

Other books that get at this are Hard Living on Clay Street (1972) and Working-Class Heroes (2003).

Understand How Class Divisions Have Translated into Geography

The best advice I’ve seen so far for Democrats is the recommendation that hipsters move to Iowa. Class conflict now closely tracks the urban-rural divide. In the huge red plains between the thin blue coasts, shockingly high numbers of working-class men are unemployed or on disability, fueling a wave of despair deaths in the form of the opioid epidemic.

Vast rural areas are withering away, leaving trails of pain. When did you hear any American politician talk about that? Never.

Jennifer Sherman’s Those Who Work, Those Who Don’t (2009) covers this well.

If You Want to Connect with White Working-Class Voters, Place Economics at the Center

“The white working class is just so stupid. Don’t they realize Republicans just use them every four years, and then screw them?” I have heard some version of this over and over again, and it’s actually a sentiment the WWC agrees with, which is why they rejected the Republican establishment this year. But to them, the Democrats are no better.

Both parties have supported free-trade deals because of the net positive GDP gains, overlooking the blue-collar workers who lost work as jobs left for Mexico or Vietnam. These are precisely the voters in the crucial swing states of Ohio, Michigan, and Pennsylvania that Democrats have so long ignored. Excuse me. Who’s stupid?

One key message is that trade deals are far more expensive than we’ve treated them, because sustained job development and training programs need to be counted as part of their costs.

At a deeper level, both parties need an economic program that can deliver middle-class jobs. Republicans have one: Unleash American business. Democrats? They remain obsessed with cultural issues. I fully understand why transgender bathrooms are important, but I also understand why progressives’ obsession with prioritizing cultural issues infuriates many Americans whose chief concerns are economic.

Back when blue-collar voters used to be solidly Democratic (1930–1970), good jobs were at the core of the progressive agenda. A modern industrial policy would follow Germany’s path. (Want really good scissors? Buy German.) Massive funding is needed for community college programs linked with local businesses to train workers for well-paying new economy jobs. Clinton mentioned this approach, along with 600,000 other policy suggestions. She did not stress it.

Avoid the Temptation to Write Off Blue-Collar Resentment as Racism

Economic resentment has fueled racial anxiety that, in some Trump supporters (and Trump himself), bleeds into open racism. But to write off WWC anger as nothing more than racism is intellectual comfort food, and it is dangerous.

National debates about policing are fueling class tensions today in precisely the same way they did in the 1970s, when college kids derided policemen as “pigs.” This is a recipe for class conflict. Being in the police is one of the few good jobs open to Americans without a college education. Police get solid wages, great benefits, and a respected place in their communities. For elites to write them off as racists is a telling example of how, although race- and sex-based insults are no longer acceptable in polite society, class-based insults still are.

I do not defend police who kill citizens for selling cigarettes. But the current demonization of the police underestimates the difficulty of ending police violence against communities of color. Police need to make split-second decisions in life-threatening situations. I don’t. If I had to, I might make some poor decisions too.

Saying this is so unpopular that I risk making myself a pariah among my friends on the left coast. But the biggest risk today for me and other Americans is continued class cluelessness. If we don’t take steps to bridge the class culture gap, when Trump proves unable to bring steel back to Youngstown, Ohio, the consequences could turn dangerous.

In 2010, while on a book tour for Reshaping the Work-Family Debate, I gave a talk about all of this at the Harvard Kennedy School. The woman who ran the speaker series, a major Democratic operative, liked my talk. “You are saying exactly what the Democrats need to hear,” she mused, “and they’ll never listen.” I hope now they will.

Let's block ads! (Why?)

04 Dec 19:50

Bryan Cheung's Liferay Is Doing Well To Do Well

by brandizzi

A Series of Forbes Insights Profiles of Thought Leaders Changing the Business Landscape:  Bryan Cheung, Co-Founder and CEO, Liferay… 

Bryan Cheung spent a good portion of his twenties in something of a quarter-life crisis: Once the Los Angeles native graduated from UC Berkeley in 1999, he considered careers in non-profit work, teaching, and even international law, in order to fulfill his personal desire to make an impact. “My personality profile tells me I’m an idealist,” says Cheung. “I thought, ‘It’s not fair for me to live this very comfortable life in the States’while others are struggling.”

So it may seem like a complete 180 that Cheung is now the CEO of Liferay, a very much for-profit company that provides open source portal software and services to some of the world’s largest companies, including Toyota, Allianz and Cisco. In 10 years, the firm has expanded to 550 employees, with 16 offices around the globe, and has been recognized as a leader for five consecutive years in Gartner’s Magic Quadrant – the annual survey of the portal market – even placing ahead of Oracle and Microsoft in the latest report. Liferay has been consistently profitable since 2004 with double-digit growth every year, and the team has taken zero investor funding.

Bryan Cheung, Co-Founder and CEO, Liferay

But Cheung contends that doing well and doing good are not mutually exclusive. In fact, those goals are Liferay’s raison d’etre: Cheung joined in founding Liferay with Brian Chan, Brian Kim, and Michael Young, he says, “because we realized that when you want to make an impact in the world, doing it in a non-profit fashion is of some usefulness, but doing it through a business context is actually, in many ways, more powerful.”

In the ambitious environment at Berkeley in the late 90s, most students were pursuing pragmatic careers: biology majors headed for medical school and history majors pursuing law were not uncommon. While it never sat well with Cheung to be quite so practical, due to family circumstances he studied Computer Science, “so I could get a job,” studying alongside colleagues doing research in 3D rendering and advanced operating systems. “I’m sure a lot of my fellow students, who were much brighter than I am, have gone on to do very important work,” Cheung mused. Meanwhile, Cheung graduated and spent some time at Accenture before joining a startup himself (which quickly failed in late 2000). “The practical choice didn’t immediately turn out so well,” he laughs, but it was at the startup that he met Brian Chan, who would later be a life-changing friend and partner.

Meanwhile, the nagging feeling of wanting to do more hadn’t quite gone away. “When I was young, a woman who worked at my mom’s flower shop, who was sort of a hippie, gave us a tape of a singer named Keith Green. I can still hear him saying, ‘This generation… is responsible for this generation of souls’—and he meant that very holistically. I haven’t forgotten that sense of responsibility.” A turning point came on a trip to Turkey in 2002. It was there Cheung met a young engineering student whose plan was to work hard at a master’s degree in order to return to his native Kazakhstan to help in that country’s development. This snapped Cheung out of his self-described “martyr complex.” “I had the perspective of, ‘Well, I shouldn’t have it better off than anyone else, so I should live like people who are poor.’ But I realized the more noble path would be to use the benefits and advantages I’ve been given to help others stand on their own feet.”

Cheung considered the options before him. He applied to law school, intent on studying international law and diplomacy. Then one day Chan called, asking Cheung if he’d be interested in starting a company, together with some friends, that would “make a lot of money to give a lot of money away,” donating to disaster relief, supporting orphans, or helping other non-profits. Did Cheung want to join? “I wasn’t so interested in writing checks,” says Cheung. “I wanted to be on the front line, and actually be the one making the direct impact.” But Cheung decided to join Chan doing professional services, sales and marketing, deferring law school for a year. “I still would love to have lived in New York, but I’m happy I dodged the law school bullet.”

Over time, the initial focus on giving away money shifted, as the Liferay team realized that the business itself could be a vehicle for making an impact, by contributing skills and software and by helping apply business principles to non-profit endeavors. “We talked to a lot of non-profits,” Cheung says. “We learned that, A) they’d rather have us build their websites than to go die in a jungle somewhere, and B) that a lot of these organizations struggled with fundraising, marketing, things like that, which often got in the way of doing the work that they wanted to do.” When the partners realized they could offer good back-end support to non-profits, they re-doubled their efforts with Liferay.

Business at the L.A.-headquartered company started growing. At the time, many portals were focused on integration and infrastructure but lacked a strong set of out of the box features that added immediate value. The Liferay team saw an opportunity. By incorporating forums, message boards, blogs and wikis, as well as document-management features, Liferay sought to provide everything a company would need to create an engaging, dynamic website or intranet. Since the product was free to download, Cheung says, universities, government agencies and even some “cutting-edge financial services companies” were using the software—without Liferay’s knowledge, until they would call or email out of the blue. When they did, Liferay offered professional software services to support them, and that funded the business. Then, in 2009, Liferay launched its Enterprise Subscription service.. Today that accounts for 90% of its revenue, up from less than 10% five years earlier.

At the same time that revenues and profits are growing, Liferay’s commitment to communities is, too. Through a foundation, Liferay sets aside 10% of its profits to support global causes, particularly in ways that are empowering and self-sustaining. Employees are encouraged to volunteer at approved non-profits, and are given five days a year to do so. Liferay’s international presence—in South America, China, Japan, Singapore, and Australia, among other places—exists not only to secure new customers, but, as Cheung says, it “puts more eyes out in the world to see where we can get involved.”

For instance, on a recent business trip to Asia, Cheung and some Liferay employees visited an orphanage in China for disabled children; Liferay spent time with the orphans and spoke with their leadership about how portal technology might help people develop an emotional connection with the orphans and get them adopted. Cheung also met with a group fighting human-trafficking—meetings that he admits are probably not “typical for a CEO.” But, he adds, “I’ve had the good fortune of being able to—through my role at Liferay—do a lot of these very front-line-changing things and make that direct impact.”

Liferay believes supporting non-profits is most effective when that support leads to self-sustainability, not dependency. In a Guatemalan village this year, for instance, Liferay donated the money, and sent employees as volunteers, to build a well. “This means that little girls don’t have to go to the river now to get water,” says Cheung. “They can stay in school, get educated, and have better outcomes for future generations.”

On the business side, Cheung foresees even more personalization in the portal space. He admires companies such as SAS,  the privately-held software company headquartered in Cary, North Carolina, which is consistently ranked one of the best places to work in America.

As the Liferay team seeks new business opportunities, other social causes continually come across the radar screen, both locally and abroad. Diverse needs such as urban renewal in South Los Angeles and the Sudan refugee crisis—through non-profits World Impact and Samaritan’s Purse—are just two causes to which Liferay has donated. North Korea’s food and fuel crisis is another area in which Cheung, a Korean-American, has a particular interest.

Cheung is realistic about how much of a difference one software company can make. “I don’t pretend we’re going to single-handedly ‘fix’ all the issues out there. But we do our best to contribute, and ultimately find that it’s all for our own good, to satisfy our souls. In that sense, we’re hardly altruistic.”

Regardless, Cheung and the Liferay team are in the right place to tackle some of these issues—although it took a while for him to see that. A few years ago, he says, “I thought, ‘You know, maybe my life is starting to look like the way I always imagined it to be.’”

Bruce H. Rogers is the co-author of the recently published book Profitable Brilliance: How Professional Service Firms Become Thought Leaders

Let's block ads! (Why?)

04 Dec 19:50

Writing an HTTP server in Prolog – things james does

by brandizzi

I’m taking a class now on programming languages where I’m learning all about the different styles of languages and how they can all be useful, as well as a class on computer networks where I’m learning all about how the internet works and how computers communicate with each other across networks. I had the idea last week to try to combine what I’m learning in the two classes and implement one of my networking assignments with the new languages I’m learning in my programming languages class, Prolog. In this post I’ll talk about why I chose to do this, how I did it, some of the problems I ran into along the way, and what I learned through the process.

For the past couple weeks in the programming languages class we’ve been focusing on logic programming and Prolog. In case you haven’t heard of logic programming (I hadn’t), it’s a kind of programming that encourages a totally different way to think about writing programs and solving problems than what most programmers today are used to. The language we are using to learn about logic programming, Prolog, is built on two pretty basic kinds of statements: facts and rules. A fact is something that’s always true, and a rule is something that is true if a set of conditions (which are just more facts and rules) are all true. The basic way you use Prolog is by giving it some facts and rules and then asking it questions. This seemed so strange and different to me at first that I couldn’t imagine Prolog ever being a practical choice for a project.

I’m not going to go too far into how Prolog works, partly because that’s not what this post is about, and partly because Bernardo Pires has a great blog post that gives a nice introduction to the language.

In my networking class I’ve studied all kinds of networks and protocols in it and it’s been really cool to actually start understanding how all of our devices communicate efficiently with each other. My last assignment was to write a simple HTTP server in C++, something that would have sounded crazy to me a year ago, but it’s actually not nearly as complicated as I thought it would be!

Meet Sockets

The bulk of the server centered around just a few functions that are part of the Berkeley sockets API: socket(), bind(), listen(), and accept(). (There are more but these are the main four that were relevant to this simple server.) Julia Evans has some pretty cool illustrations on this kind of stuff that you should check out. What’s awesome is that these functions are actually fairly simple to understand:

  • socket() creates and gives you a new socket, which is a thing that your OS uses to communicate with other computers.
  • bind() gives your socket an address that’s somewhat analogous to a street address; it gives other computers a place to connect to.
  • listen() tells your OS to start listening for things that want to connect to your socket.
  • accept() accepts a connection on your socket and gives you a new socket that you can use to communicate with whatever connected to your original socket. This is often a web browser like Chrome/Firefox/Safari, some other HTTP client, or really any kind of program that needs to communicate with other programs over a network.

See, there’s not that much to it! Once you’ve got a connection established to another computer through a socket, you can pretty much treat that socket just like a file and use the read() and write() system calls to communicate. Pretty cool, right? What’s even cooler is that these functions exist and work pretty much the same way in a bunch of different languages, even Prolog!

At the same time that I was working on the HTTP server for my networking class, I was working on a Prolog project for my programming languages class and stumbled across these same socket programming functions (well, predicates in Prolog, not functions) in the GNU Prolog documentation. This got me pretty excited because I actually knew what they were! By this time, I was actually starting to warm up to Prolog, so after I finished the two assignments, I decided that it would be fun to try to combine them and write my own simple HTTP server in Prolog.

Getting Started

The first step was to decide how much functionality I wanted this server to have. Should it thoroughly implement HTTP/1.1? Should it do nothing but send a few bytes to every client that connects to it?

Because I didn’t want to spend more than a couple of days on this project, but still wanted it to make it somewhat complete, I decided on something in between: It would be able to accept a connection from a client, read in and parse an HTTP request, find the requested file, construct a valid HTTP response, send it back to the client, and close the connection.

Requests and Responses

The first thing I chose to implement was a set of rules for parsing HTTP requests and constructing HTTP responses, which are both essentially just strings with information about what’s being sent from one program to another. I tried to make these rules as simple as possible and do the bare minimum amount of work to do what I needed. For the requests, that meant doing nothing but extracting the path to the requested file so that we know what to send back to the client.

This code may look strange at first, but what’s going on is very simple. Basically, it’s saying parse_request(Request, Path) is true if Path is the path requested in Request. The first line of an HTTP request is in the format “GET /path/to/some/file.html HTTP/1.1”, (where “1.1” is whatever HTTP version is being used) so parse_request is just saying that Path is the bit of the request that comes after “GET /” and before ” HTTP/”. Pretty simple, right? Now on to the responses.

Here, you can see construct_response(Body, Response) putting together an HTTP response by concatenating the status line, “HTTP/1.0 200 OK\r\n”, one header, and the given body of the response into Response. For this simple server, we’re only implementing one response status code, 200, but there are tons of other ones for indicating all kinds of things. If I were to add support for more status codes, this is where I’d do it.

Reading Files (and Requests) in Prolog

The next thing I needed to learn about was reading files in Prolog. I’ve done this in other languages before, so I had a basic idea of what needed to happen, but wasn’t sure if it would work the same way in Prolog. To find out, I went to the list of built-in predicates in GNU Prolog and Ctrl-F’d for “open”. I was happy to find a built-in open() predicate that works just like the Unix system call by the same name. The tricky part was reading in the contents of the file. Like in functional programming languages, the concept of a loop just doesn’t make sense in Prolog, so I knew that there would need to be some recursion involved here and eventually arrived at this code for reading the contents of the file:

After read_file opens the file at Path, it jumps into the recursive rule read_file_helper, which continually reads in and concatenates bytes to the file contents until it reaches the end of the file. I recalled from my networking class that socket I/O is very similar to file I/O in most languages, and was happy to learn that Prolog is no exception. My rule for reading in HTTP requests from the client is almost identical to my rule for reading files, except that HTTP requests end in two carriage-return line-feeds, rather than an end-of-file.

I’m using two new ideas here in read_request. The first is naming my request reading rule and its recursive helper the same thing. I’m allowed to do this here because the two have different arity. They are conventionally referred to as “read_request/2” and “read_request/3”, respectively. The second thing is the underscore in place the Stream variable and the request prefix in the second definition. The underscore here says that I don’t care what is in those places. I don’t need to use the socket stream here and I don’t care what comes before the carriage-return line-feeds in the request, so they’re replaced with underscores. Note that the underscore has a special meaning in Prolog because it doesn’t require that they are equivalent.

Putting it all together

With these helpers defined I was able to start on the main rule for running the server. This is where we get to use those standard socket interfaces I mentioned earlier.

In the first three lines here we’re creating a new socket and binding it to localhost:3000. Then it starts listening at that address and lets the user know. I added the flush_output line because I was having some problems with the message not being written right away. Next, socket_accept waits for a client to connect and creates input and output streams that let us read from and write to the client connected at that socket. After that my helper rules read and parse the request and then get the requested file and construct an HTTP response to be sent to the client. Once all of that is finished, the socket is closed.

Problems

For the most part, this was a generally frustration-free project, but there were a few challenging points that slowed me down along the way.

The main problem I ran into was that while testing the server, I would often get an error when I tried to run it, saying that the address was already in use. This confused me for a while because I wasn’t getting it consistently, and I knew I wasn’t running any other servers on my machine on that port. After a bit of digging, I found an option that’s available in most implementations of socket interfaces that tells the OS to let other processes re-use the requested address. This option wasn’t being set when I called socket_bind, and the GNU Prolog documentation didn’t seem to indicate a way to do so.

To the source code! The next logical step, after Googling the problem without much success, was to go to the GNU Prolog source code and see how socket_bind was implemented and maybe find an undocumented way to set that address reuse flag. To my surprise, I found that it was being set, right there in the source code where I could see it. But if it was being set, then where was my problem coming from? I quickly learned that the address reuse flag was a relatively recent addition to the GNU Prolog source and hasn’t yet been included in a stable release. This was a bummer for me, but I was happy to have gotten to the root of the problem.

Conclusion

That’s it! A super basic HTTP server in Prolog. It doesn’t fully implement HTTP 1.0 or even support multiple connections, and It’s certainly not going to replace any of the servers that I use for my projects any time soon, but it was a lot of fun to write and I feel like I have a better understanding of socket programming and Prolog after writing it.

This address reuse flag problem was a bummer, but it felt really cool to figure out the reason for the issue by digging into the language’s source. If I were to redo this project, I would use SWI Prolog, which seems to be more actively maintained and has a socket interface that gives users that option to set that address reuse flag.

This post was partly inspired by a lot of Julia Evans‘ recent posts, which are all super cool and you should check them out. You can read the full source code on Github. I’m still very new to both socket programming and to Prolog, so feel free to let me know if there’s anything I could have done differently!

Did you like this? Tell your Friends!

Let's block ads! (Why?)

27 Nov 22:22

Toluca Lake (Los Angeles part 2)

by boulet
16 Nov 09:11

Saturday Morning Breakfast Cereal - The Troll Toll

by tech@thehiveworks.com


Hovertext:
How does this never come up in fairy tales?

New comic!
Today's News:
15 Nov 11:46

#Art (via timurse)



#Art (via timurse)

15 Nov 11:45

Shell

by Reza

shell

15 Nov 11:44

Saturday Morning Breakfast Cereal - One Wish

by tech@thehiveworks.com


Hovertext:
Leprechauns give one wish, genies give three. How come no gives two wishes?

New comic!
Today's News:
15 Nov 11:42

Kevin Finds Drugs

by Reza

kevin-found-drugs

15 Nov 11:41

A sad fate

by CommitStrip

strip-transfert-sur-cle-usb-english650-final

15 Nov 11:39

09-06-2016

by Laerte Coutinho

15 Nov 11:36

06-06-2016

by Laerte Coutinho

15 Nov 11:35

Saturday Morning Breakfast Cereal - Why I Couldn't Be a Math Teacher

by tech@thehiveworks.com


Hovertext:
If I were you, I'd focus less on algebra and more on seeking public office.

New comic!
Today's News:

Hey geeks of London and MIT! We're just starting to get the ball rolling on next year's shows, and submissions are now open. Both shows will be open theme!

15 Nov 11:33

Comic for November 13, 2016

by Scott Adams
15 Nov 11:31

Until The End Of Time

by Brian
15 Nov 11:31

Photo











15 Nov 11:30

How to Select a T-Shirt

by Scott Meyer

This is one of the few comics that where I can remember exactly where I was and what I was doing when I came up with the idea. As with many comics, the idea for the third panel came to me first. It is one of the best ideas I’ve ever had.

While making custom Infini-Tees for people didn’t work out, I am proud of the fact that I gave it a shot, and seeing my shirts on Wil Wheaton and Adam Savage was a big thrill.

And before you ask, no, I’m not making them anymore. As I said a few commentaries ago, it was just too challenging making acceptable likenesses of people I’d never met. The problem was even worse on the Infini-Tees, because the image was repeated six times at different scales.

 

You can comment on this comic on Facebook.

As always, thanks for using my Amazon Affiliate links (USUKCanada).

15 Nov 11:28

Saturday Morning Breakfast Cereal - Work/Life Balance

by tech@thehiveworks.com


Hovertext:
The important thing is to find the low low bar that works for YOU.

New comic!
Today's News:
15 Nov 11:28

Saturday Morning Breakfast Cereal - Humans are Special

by tech@thehiveworks.com


Hovertext:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHH!

New comic!
Today's News:

Wednesday Goddamn Book Reviews

Words on the Move (McWhorter)

John McWhorter is a national treasure. This is a quick book giving a number of interesting explanations of ways language changes over time, as well as ways in which people have lamented its change over time. It’s not a controversial concept among linguists, but it bears repeating to the wide world, and in any case, McWhorter does it so well.

Power to Save the World (Cravens) This is going to be my default “here’s the argument in favor of nuclear power” book for people who are willing to spend some brain power doing their research. The one big flaw is that she underestimated the speed at which renewables would rise. I don’t think this negates any of the arguments she makes, but there are a few sections in the book that won’t age well.

The Language Hoax (McWhorter) Another great McWhorter book. This is a rejection of the public understanding of the Sapir-Whorf hypothesis, which (in short) states that the structure of a group’s language has a great influence on their way of viewing the world. McWhorter argues that, in fact, the structure of language is more or less random between groups. A delightful bit of curmudgeonly scholarship, more or less saying “linguistics is really interesting without this bullshit thing everyone in pop science seems to believe!”

11 Nov 16:40

Vontade de doce

by Will Tirando

vontade-de-comer-doce

11 Nov 16:39

Exposição

by Will Tirando

troquei-o-carro

11 Nov 15:52

Cuando no puedes abrir la puerta por si estás dentro @Omphalos


11 Nov 15:51

Se os ha ido de las manos Coca Cola @itsabysky


11 Nov 15:50

Things

by Justin Boyd

Things

Still scared of holding a balloon outside.



bonus panel
11 Nov 15:50

Which full-stack developer are you?

by CommitStrip

strip-nous-sommes-tous-full-stack-english650-final

11 Nov 15:45

Photo



11 Nov 15:44

Saturday Morning Breakfast Cereal - Punishment

by tech@thehiveworks.com


Hovertext:


New comic!
Today's News:
11 Nov 15:43

Photo