How Tests Improve Code Structure pt 1

Hunger Tracker needs to persist data past the closing of the app.  Knowing nothing about Android I googled “android write to file” and used the first reasonable looking thing that came up.  This was sufficient to let me write to and read a file, which was good enough for a first try and powerful enough for me to release version 0.1.  But as I planned the next step I ran into problems.  The read function I found required me to specify the number of chars I wanted in advance.  I couldn’t spot the end of the file so I grabbed a fixed number of entries every time.  I could extract the data as strings but couldn’t figure out how to make a proper scrolling list (even though I’d done one in the Udacity tutorial).  Attempts at fixes felt muddled and high friction, which is usually a sign I’m afraid of losing data, either to a hard drive failure or to a introducing a bug and failing to detect it.

Step 1 in fixing this was setting up my github account so I had proper version control.  Step 2 was testing.  I spent a long while figuring how to properly test the kind of android class I was using (“android unit testing” being a surprisingly unhelpful search term), and then some basic tests of “The text fields that should be there, are they there?”.

The next step was to test the data storage.  But I couldn’t figure out how to unit test that.  If I tested whether the app was writing to the correct file I needed to look for the exact same file.  But that means updating the test every time I change the name of the file, which I didn’t want to do.  Plus seeing if the correct thing is written to it is ugly.  Tests should be atomic (meaning it doesn’t matter what order you run them in), but the file is persistent, meaning I either need to clear it every time or factor in what previous tests have done.  Plus I would have to shape the test around the exact storage format the app was using, but again that means making the test dependent on an implementation detail.  I could trigger writing and then reading and make sure the display element was correct, but that’s testing two different things and a unit test should only test one.

What I finally worked out was that the handling of persistent data was not actually a core function of HungerTracker’s MainActivity.  What I needed to do was separate out those functions into a separate class, and then use mock objects to make sure the expected calls were made.  E.g. instead of the app writing to a file and the test looking at the exact file and verifying the writing, the app calls the HungerTrackerWriter object.  The test swaps out the real HungerTrackerWriter with a fake one, and monitors that the expected call is made.  This leaves the HungerWriter proper tests blissfully unaware of the implementation details while still verifying that the app is doing what was expected.

[Technical details: somewhere I read that the android junit framework handled mocks easily. This was something of an exaggeration. It has built in mocking for a lot of Android specific classes, but nothing for user created classes. There are many well regarded Java mocking libraries, none of which provided comprehensive instructions that worked for me. Apparently they integrate weirdly with Android? My first round of mocking was hand-written, just so I could work on test code. I never did get the best regarded library, Mockito, working, but I eventually cobbled together a set of build instructions that made EasyMock work]

You might think that making that big a change in order to make something more testable is the tail wagging the dog, but as I was doing it something magic happened.  Those problems with reading exactly as many entries as there were and putting them in a list (as opposed to reading exactly 10 and dumping them in a string) were suddenly much easier to conceptualize.  What seemed so muddled when it was part of HungerTracker was suddenly easy to think about when it was part of HungerTrackerWriter.

If you are super curious, here is the code before the refactor, here is the code after, and here is the test code with mocks.

Prostaglandin, omega-3s, and health

My cat has lost weight since going on a special “I’m inbred and my kidneys don’t want to kidney” diet.  He’s also wheezing a lot.  My vet has recommended fish oil to get him some extra calories, and to fight the wheezing, if the wheezing is something something allergy something something prostaglandin.  She didn’t explain it very well, so I’m consulting with Dr. Internet.

Prostaglandins are lipids that send signals from a cell to itself or its close neighbors.  Prostaglandins take their name from the prostate gland, signifying the fact that they are produced and have effects in almost every tissue of the body.  This is what happens when you name things after the first place they’re discovered.  “Local signalling” covers a lot of ground, including constricting blood vessels, dilating blood vessels, inducing a fever, making you more sensitive to pain, digestive muscle contraction, digestive muscle relaxation, airway contraction, and airway relaxation.  So they could definitely either cause or cure my cat’s wheezing.

What about fish oil?  Prostaglandins are made from fats, but less so from omega-3 than any other fat, and their prostaglandins are less active than others.  Fish oil is rich in omega-3s, but it’s not the only source, as soylent has been working so diligently to demonstrate.  That’s an argument for swapping omega-6 for omega-3, but it doesn’t mean adding additional omega-3s will be any help.  What is an argument for straight up supplementation is that all fats are converted to prostaglandins by the same enzyme, which exists in limited quantities regardless of the amount of fat available.  Omega-3’s slow conversion rate effective blocks the conversion of the more inflammatory omega-6s.  So while I don’t see any reason fish oil would do better than other sources of omega-3s, this certainly seems like a plausible treatment with limited downsides.

Now is as good a time as any for a general omega-3 vs. omega-6 lesson.  3 and 6 are different in ways I can’t be bothered to look up because it doesn’t matter; your body absolutely needs both of these to survive.  Presumably we adapted, more or less, to whatever ratio was available in the evolutionary relevant time period.  Unfortunately 6s have a much longer half life than 3s before going rancid, and everything in our modern food system pushes this- olive oil bred for shelf life, cows are fed grains, which have more omega-6s than grown plants because they don’t want their seed energy going bad either.  The end result is that the intake ratio of omega-6:omega-3 is extremely different than what our bodies expect, and this causes various problems, like maybe prostaglandin-mediated allergies and inflammation (source).

Video Games for Good

Extra Credits is a video series on game design and the game industry.  It has interesting insights I don’t see elsewhere, but it is also… low density.  You could compress most episodes into a single written paragraph and lose nothing.  I tend to watch them when being told the same thing over and over with completely unnecessary accompanying graphics is calming, rather than annoying, which isn’t very often, so I only just caught this video on whether games can induce empathy.

If you are not in the mood to be reassuringly talked down to, they helpfully provide a summary:

Many studies have investigated whether or not there is a link between video games and violence, but few have looked at the bigger picture. What is the correlation between video games and empathy? Since games put us, as players, in the role of characters who are not ourselves, asking us to understand their situation and the problems that they face, they have the potential to teach us about how to empathize with others. While many gamers have anecdotal evidence about games that made them feel a character’s pain, there’s a disappointing lack of formal studies into that side of the question.

Examples: This War of Mine, Cart Life

I didn’t think anything of it until a week later at my Effective Altruism meetup, when we were discussing egalitarianism/maximization.  In a nutshell, EA believes that all lives are equally valuable, so if you can save two lives for $n each or one life for $2n, the most moral thing to do is to save the two lives.  Phrased that way I don’t understand how it’s at all controversial, but in practice it comes up against many people’s instinctive priorities.  For some, passing over a homeless person to give to GiveDirectly doesn’t just give them fewer warm-fuzzies, it feels actively immoral.  Someone at the meeting suggested it was a matter of empathy- people naturally feel more empathy the more often they see someone, or the more they have in common with them.

This is  of course obvious, which is why so many charities try to up the empathy you feel for their beneficiaries, by implying you’re helping a particular person when you’re not, or just sending a letter with a few heartwarming stories of all the injured dogs they’ve saved that year.*  They do it because it get donations, but it’s very hard not to slide into poverty porn. I find those examples really manipulative, but I loved the ability to choose out specific recipients when donating to Modest Needs so clearly I’m just as susceptible.

This is where I thought of that Extra Credits video.  What if instead of telling people how awful extreme poverty is, we gave them a video game demonstrating both the difficulties poor people faced and the resources they used?  Some things I would like to include:

  • Trade offs, trade offs, trade offs.  Do you invest in your child’s schooling or new farming equipment?
  • Bee Sting theory– demonstrating how it is easy to do the right long term thing when you have a few problems, but when too much is wrong sometimes palliatives are all you can manage.
  • The importance of social capital.  The poor (both in the US and the 3rd world) get a lot of criticism for spending so much on alcohol and ceremonies, but the fact is that that builds social relationships that can be crucial later on.  This doesn’t mean spending a lot on booze and parties is optimal, but that the change must come at a societal level.
  • How many well intentioned NGOs fail.  E.g. my continuing hate for the play pump.
  • Ideally you’d like to convey the scope of preventable deaths.  I don’t know how to do that respectfully.  You could do something like Shelter or The Oregon Trail, where you go in knowing some characters will die and the goal is to save as many as possible, but that seems a little horrifically callous.

I have several ideas for how to do this.  You could do the trade offs with a choice mechanism like that of Depression Quest or Long Live the Queen.  Soha Kareem has has apparently done some great work with video games to express her experience of microaggressions and sexual abuse.

EA strikes me as having a real comparative advantage when it comes to producing video games, relative to other charitable movements.  And by “real comparative advantage”, I mean “lots of programmers”.**  None are games programmers specifically, but it might be a skill worth picking up.

*Pro-tip for my local humane society: this may not work as well on cat owners as you were hoping.

**We were up to two non-programmers at the last meeting.  High five.

100% Food versus Soylent

I really, really wanted to like 100% food.  It has so much going for it- made of actual grown food, high protein variants, convenient portable single serve containers, shipping time measured in days rather than months… Unfortunately, it is inedible.

And if I’m saying inedible, it must be pretty bad.  I drink Soylent at room temperature, and for a long time didn’t bother mixing up the little protein clumps that formed (although once I realized how easy to clean my blender was, I did mix it).  As I write this I’m consuming my smoothie with a spoon because I put in too many chia seeds and it turned into a gel.  I cannot drink 100% food.  I ordered the six-variant mixer (chocolate/plain and regular/high protein/low carb), but I’ve only managed to try two (one low carb, one regular) and one of those was a mere pinch.  Extremely diluted the taste is tolerable, but still leaves this unbelievably gross oil aftertaste/film in your mouth.  I won’t drink it and you can’t make me.

The single serve containers were a disappointment too. There’s not enough room in them to really shake up the mix, so you end up with a lot of dry mix protected by a layer of wet mix.  So 100% food’s only real selling point is that it ships quickly.

I’m not 100% happy with Soylent.  I would really prefer fewer digestible carbs and more protein and fiber, but that’s addressable with some flax seeds and additional protein powder.  I would also love it if they shipped in < 3 months, and didn’t tell me they were going to ship a month before they did.  But it is better than starving to death, which is more than I can say for 100% food.

How effective is volunteering at a suicide hotline?

Months ago my local EA group had a meeting around the concept of Effective Volunteering.  EA is not opposed to volunteering anymore than it it’s opposed to working directly for a cause, but it is more skeptical than the general population that this is the most effective way to help the world.  This doesn’t mean volunteering is bad, it can have all sorts of benefits outside of helping the world- building community, buffing one’s resume, and generally feeling good.  But if you want to justify volunteering on its helping-the-world merits, you have to compare it to the standard option of “work more, donate money.”

[I’m ignoring the argument that most people aren’t paid hourly because “learn skills to boost wages, donate excess” is an equally valid plan]

Based on the local discussion plus this post by Ben Kuhn, I propose that volunteering is most effective when some critical mass of the following are met:

  1. The product produced by volunteers is not the same as that produced by minimum wage workers (e.g. food kitchen volunteers are generally more cheerful than McDonalds workers)
  2. The volunteer has some comparative advantage in the task (e.g. pro bono work by lawyers)
  3. The activity does not take away from paid work (e.g.I have more hours in the week total than hours in the week I am capable of programming).

The problem is that 2 and 3 are often in conflict.  People’s comparative advantage tends to be used at work, either because that’s what led them to the work or they developed the talent there.  So it either has to be someone not capable of working regularly, or the person has to have two different comparative advantages.  I happen to think I fall into this category, because I’m very good at both programming and crisis chat counseling and they use entirely different parts of my brain.  And actually crisis chat makes a good play for having trait 1 as well: it’s heavy emotional work, and there are a lot more people capable of doing it 4 hours a week than 40.

Which got me thinking: how effective is crisis chat?  I’m fully prepared for the answer to be “not very”, it really seems like it’s on the less efficient side of things, but let’s run the numbers.

First step: how much does running a suicide hotline cost?  The first posting I found that listed a salary said $16.00/hour, and that’s for bilingual workers in an area with a cost of living 60% higher than the national average.  Let’s say $20/hour to include taxes, phones and computers, vacation time, etc.  GiveWell considers anything under $5,000 per life saved to be extremely cost effective, so to be competitive a hotline worker would have to save one life every 250 hours worked.  Statistics on chat line effectiveness are hard to come by because they’re anonymous by design, but I worked ~170 hours last year and I know for a fact I was 1/2 of a team that saved one life, and find it plausible that I saved more.  I work on the text line, which for various reasons is less likely to attract people who are imminently suicidal, so I suspect the phone line workers are more effective.  By this measure, suicide hotlines are competitive with GiveWell’s top charities.

The complication is that the hotline doesn’t do this alone.  I gave myself half a life because I called in a rescue for a phone worker who contacted me via chat, but that success depended on emergency workers finding the person and a mental hospital to take him in.  Malaria nets don’t work alone either (they can’t solve famine or war), but this seems more like evaluating the cost of the nets without the cost of employees to distribute them.  On the other hand, some percentage of chats may talk people out of suicide without requiring an active rescue.  If I help a person form a plan to keep themselves safe until the urge passes, that’s incredibly effective.

The other way to look at it is what would people pay for the service.  My gut feeling is that the service I provide is more valuable than anything the visitors could buy with $20*.  The most comparable services, therapy and psychiatric visits, start at $60/hour.  Crisis lines are not a substitute for psychiatry or counseling, but a marginal hour of chatting may be a reasonable substitute for an hour of either, given how much of their sessions is empathetic listening.    Even if hotline workers are not as effective at listening because they are lower status, that’s still substantial savings.  Plus we get a good chunk of people are uncomfortable talking to a real professional because they are so high status, but feel okay talking to us.  On the other hand, I’m pretty sure most of the bottom billion would take the $20, or even $2, over an hour talking with me.  Competitive within the sphere of 1st world interventions is not the same as competitive.

Still, that’s a much higher effectiveness rate than I was anticipating.  And it manages to hit all three of my criteria above (for people who are good at listening but don’t do it professionally), which is a pretty neat trick.  Unfortunately it does not work for Kuhn’s use case at all, since he was looking for things EAers could do as a group on an ad hoc basis.  I suspect this is not a coincidence.

*Testing this directly would be hard, since there’s nothing to stop someone who wants two hours of chatting to say they want five, but will accept two + $60.

Is Nicotine Harmful?

Tobacco is so definitely harmful  I’m not even going to cite a source for that statement.  But tobacco contains a lot more chemicals than just nicotine. says nicotine isn’t harmful, but also says nicotine isn’t addictive, so I’m not giving them a lot of credit as a source.  Wikipedia also says pretty nice things about nicotine, but exactly how nice seems to depend on what day I check.  The page appears to be edited a lot, and sometimes claims it isn’t addictive.   So I’m going to fact check Wikipedia very carefully here.

Let’s get some basic things out of the way.  Nicotine is addictive to at least a certain percentage of the population. You can see that in science or in anyone you’ve ever watched try to quit smoking with and without the aid of nicotine supplements.  It is probably true that propensity to nicotine addiction varies in the population, and some people can try it a few times or even use regularly without becoming addicted, the same way opiates are insanely addictive to some people and I actively dislike them.  But most people with that propensity won’t ever start using tobacco because smoking is disgusting and if your brain doesn’t make you do it, you won’t.

Nicotine imitates choline in some but not all choline receptors (conveniently, the ones it affects are called nicotinic receptors).  Neurotransmitters are weird and powerful and we don’t fully understand them.  At best, nicotine could be in the same category as medications meant to treat depression, which have some costs and some benefits, all of which vary widely between individuals, and whether a given person is better off with or without it depends heavily on their exact mix of genetics and current environment.

Nicotine is poisonous in large enough quantities.  This is not necessarily damning: lots of things are poisonous in large doses including vitamin A, which has vitamin right in the name.

Which one will be your last?
Which one will be your last?

More to the point, nicotine is poisonous because it imitates choline, and in large doses completely borks that system.  This is not entirely dissimilar to the way SSRIs (commonly used as anti-depressants) can in large doses cause serotonin syndrome, and the same mechanism that causes that makes SSRIs incredibly useful for treating depression.*  Coincidentally, nicotine maybe also treats depression.

Nicotine promotes the growth of new blood vessels.  If you have just had an injury this could be good thing (although I found no data on nicotine specifically, and tobacco is definitely bad for recovery), but it also makes it easier for tumors to feed themselves, which is extremely bad.  It may also lead to hardening of existing blood vessels, which is pretty much always bad.

This may or may not be related to nicotine’s ability to temporarily raise blood pressure.  I would super like to tell you if or how they are related or at least if they are happening on the same time scale, but I could not find a primary source that measured the immediate cardiac of nicotine (as opposed to tobacco) with a sample size of more than 16. There are lots of secondary sources that say the increase in blood pressure/narrowing of capillaries is immediate, but they seem to be scare monger sites against nicotine use for harm reduction and don’t draw a strong distinction between tobacco and nicotine.  On its own this is worrisome only if it pushes your blood pressure to problematic levels, but if the process also leads to permanent hardening of blood vessels, it’s pretty concerning.

Nicotine also has some cognition boosting effects (even in people with Alzheimers)** similar to caffeine, appears to either partially treat schizophrenia or reduce the really awful side effects of anti-psychotic, and maybe Parkinson’s as well.

Based on this, I’m pretty confident that we should be investigating nicotine-derived treatments for a number of issues, and if I get Alzheimers or Parkinsons I will probably pick up a patch the next day.  But I still have serious concerns about its addictiveness that  would keep me from using it as an everyday cognition enhancer.  But I abstain from caffeine almost 100% of the time, so clearly I’m on the low side of risk tolerance in this area.

*Probably.  No one actually knows how SSRIs help.

**You remember last month when a study came out suggesting anti-cholinergics increased propensity for dementia, and I complained that they only studied drugs that affected muscarinic receptors, not nicotinic, so drugs inhibiting nicotinic receptors might be fine?  This would suggest I was wrong.

Every conversation I’ve ever had about opioid pain killers.

Me: The mild ones do nothing for me and the heavy ones are so unpleasant I’d rather be in pain.  Even when I got dry socket I only took them to sleep, and that was after days of going without.
Them: Opiates aren’t supposed to make you stop being in pain, they’re supposed to make you not care.

I’m not sure how they think this is helping. If I’m complaining about pain the drugs have pretty obviously failed at making me not care. I am especially confused by medical professionals trying to talk me into dangerous, addictive drugs I’ve said I don’t want.

Side note: Dry socket is a condition in which the blood clot that forms in the wisdom tooth extraction site dissolves, exposing a nerve to open air. I’m not sure what kind of pain you’re supposed to be in after wisdom teeth extraction, but ask your dentist, and if it’s more than that get help immediately. Especially if it gets worse over time.