31 May 2014

The Template-Method-Antipattern

I had been skeptical about the GOF pattern book ever since I read it many years ago. Many of the patterns in the book seemed so trivial that I was irritated by how much attention they are given. Others have examples that seem overly simplified and never quite fit what actually happens in practice. Looking back now, I find that the premise of the book seems to be the early OO memes of "avoiding repetition" and "finding the right design for the application domain". The latter relates also to graphical modeling and model-driven-design. While those ideas are doubtlessly important, I think that early OO philosophy over-optimizes in that one direction and forgets about another very important direction: keeping the code as simple as possible. Instead of over-designing and already including space for "later extensions", realize that there are usually unknown unknowns and the later extensions might go into quite a different direction. It is the new agile world where running code and automatic tests are more important than fancy diagrams and great designs.

There are many guidelines which help us to write simpler (and thus more flexible) code. Before criticizing the template method even more, I want to remind you the two most powerful ones:

  • Number One law of procedural programming: favor pure functions over mutators. (And if you have mutators, separate them from the pure functions.) Note that this law fully applies to object-oriented programming as well!
  • Number One law of OO programming: favor composition over inheritance. (And let most of your inheritance be implementations of pure interfaces.)

I have always had trouble explaining why certain patterns were bad (especially those which over-use inheritance), but it was nonetheless very clear to me. I always found it hard to describe succinctly and precisely what the template does without going into the details of inheritance and the subclasses. Other people just didn't need this kind of clarity it seems. But yet, every time I had a debate with someone over a particular and specific piece of code I could convince them that my simpler variant was better in that particular case. So I am right in all cases, but still couldn't give a generally convincing reasoning why this is so.

Now recently I realized that rigorous unit-testing is a great way to validate a design: if it is hard to test, then that's a big smell and motivation to simplify! In a template method arrangement it is definitely hard (even though it's still possible) to test the template and its instantiations separately.

But instead of going on explaining what I find hard to explain, let's hear what others have to say:

2 May 2014

The start of my virtuous life

I recently finished working through the best self-help book that I have yet come across. "Ab Heute erfolgreich" (Successful from Today on) by German trainer and coach Alfred Stielau-Pallas. What makes the book so effective is the approach to read just one chapter per week (I usually did on Sunday) and then practice its teachings for an entire week. I liked this so much that sometimes I took a week off from the book to practice another important thing that I just had learned or been reminded of.
One of the many great ideas the book contains is Benjamin Franklins concept of 13 virtues which he practices one week per virtue for his entire life. (Going through all of them four times a year.) When I read this chapter I instantly thought that this would be a great way to continue the "weekly focus" which I liked so much about the "success book" (as I like to call it). But I also realized that Franklin's virtues aren't just right for me and the success book's practices are better, but still not completely reflecting my own virtues. So I knew from the moment of reading that I would have to come up with my own list.
Now, this actually wasn't easy and I procrastinated over it quite a bit. Fortunately I had already decided to go on sailing holidays for the May day long week-end and since sailing only takes a few hours each day, that's the prefect opportunity to do such kind of important work in the morning. (I only like be outside in the afternoon and evening anyways!)

So I came up with my own list of virtues and some practical exercises to go along with them, because I know too well, that just focusing on an abstract topic alone doesn't make it appear. It always needs concrete actions to take and finding those is not easy either. In fact, I plan to still spend at least one half-hour of focused thinking time per week to customize and concretify that week's virtue.

To start off, I wrote down some virtues which I think I already embody perfectly and which I don't want to practice in a focused way. Of course, I hope to still get better at those virtues, but I practice them spontaneously often anyway, so it doesn't feel just to give them even more weight. Those intrinsic virtues are Positive Outlook on life, Appreciation of small things, Gratefulness for what I have (and what I additionally get on each new day).
  • Not criticizing myself or others and instead focus on what's great about myself and others.
  • Thriftiness, frugality, and humility.
  • Humor.
  • Curiosity.
  • Creativity.
If you, dear Reader, now feel that I am at little arrogant and presumptuous here, praising myself so much, I can only reply that this is a simple exercise of my second virtue! While I hope to be well-aware of my shortcomings, I simply decided to focus on my strengths first! As the success book says: accept and love yourself as you are and only try to improve yourself one weakness at a time. I also want to add that this list is not set in stone. After each iteration through all my virtues (and especially after the first time through) I might decide to move any item from the "already perfect" list into the focus rotation list.

But now, let's get to my focus virtues. For each one, let me briefly call it out, define it, say why I want it, and sketch some actual concrete practice exercises.
Mindfulness: The full and untainted awareness of what I am doing, what I am thinking, and what I am feeling. Also the knowledge that my thoughts can be mistaken or can focus on entirely unimportant things. And the knowledge that all feelings are temporary and fleeting and most of them even go by without any action by myself. There's actually a lot more to say about mindfulness and there might be better definitions, but let me just explain why I intentionally put this in the number one spot. You might know the saying "what you can't measure, you can't manage." Obviously what you're not aware of is even harder to improve!
As with every other virtue I want to practice mindfulness every day (and in every moment) and specifically I want to keep up my daily sitting meditation practice and weekly visits to a meditation group. During the regular mindfulness focus week I might then do extra activities like trying out new kinds of meditation, doing longer stretches of meditation or on different times of the, or visit new practice groups, read or reread some books or articles on meditation, and finally try to plan the week so that every activity can be done in a mindful fashion. 

Empathy and Listening to others: Everybody loves talking and by listening we give the gift of our attention to the other person. It's a great way to become liked and also to learn a lot. For practice, revise some deep questions to ask others, don't be afraid of silence and long breaks to give them room to think and answer, and finally be aware of how much you are talking yourself and keep it to the minimum of things that the other person actually wants or needs to hear. 

Compassion and Listening to myself: This is based on the idea of a silent retreat for one week, but still going to work. I will restrict myself to only professionally needed conversation, and spend my private life in complete isolation for this week. While that sounds really extreme, it is just one week after all and I don't have that many private interaction with people anyway. I think that by offsetting such a Silent Week with its opposite –a Connection Week– I might even get more socializing and certainly higher-quality socializing than by just floating along through life.

Generosity: You might have heard about that psychological study which showed that people actually become happier by spending money on others instead of spending it on themselves. So there's not much here to say: just do at least one good deed per day and don't let it just be tipping generously. Spend some quality-time to think creatively about possible gifts. When you buy something, think: who of my friends or acquaintances might like that, too? Sometimes I just buy two of a thing and later decide who to gift the spare one to! When you see some advertising, think: who of my friends might like this? or something like this? 
Creativity is important here! Don't just dismiss an initial thought because you don't think any of your friends will like it. Just continue a theme with a chain of associations until you get to something that will actually be appreciated. For instance, when I see another beautiful Porsche car at the traffic light, I might think of a friend who's going on a road trip (be it by car or bike or by hitchhiking doesn't matter here!) Now I can think of anything that my friend might need for that trip, be it a map, a guidebook, a dictionary, a scarf, or some nice tires for the bike. 

Decisiveness: Now we get to the core of self-improvement and to the harder stuff (at least for me). I grew up as a rather indecisive person and liked to go with the flow and with the opportunities that present themselves. One of the big things I have learned from the success book is that decisions just have to be made to get anywhere. Going with the flow only takes you where others want you to go or think or should go, but finding your own way requires to make decisions! I was so very fortunate to have read a great (despite the cheesy title) book on decision making just before starting the success book. I found it very helpful to have some decision-helpers (like simply sketching up a pros-and-cons list). It's also important for me to avoid procrastinating on decisions by asking myself "until when do I need to decide that? and what additional information do I really need to decide well?" I can also unblock my own undecidedness in a question by setting myself a timebox of five to 30 minutes (or more for harder decisions) and use that as quality thinking time just for this one decision. 
But even with all those techniques (and many more in the decisions-book), I can still be in a circle of thoughts without realizing that a decision is needed. Therefore it is important to regularly practice explicit decision making in the hope that it will become more and more automated with time.

Vision and Planning: After a strategic decision is made, nothing will happen unless I have some concrete action-steps that I can follow. That's why setting aside quality time for planning things is so important. I also include "vision" in this point because planning becomes much more powerful if it's done for medium or long-term goals. If I plan a project for three months or even a year then I can include many more cool things in it, while still being in sight of a clear finish line. I am not sure, whether a focus week is the best way to practice this, but since the topic is so important, I just mention it here.

Order and Finishing small projects: This one is also very important and fits perfectly to be the end spot in the list. I enjoy creative chaos as much as I like some order and having one week per quarter year where I really clean up, sort through things, tie loose ends, and absolutely don't start anything new (unless it takes less than, say, thirty minutes) seems like a perfect compromise. This is also a great ime to decide what to do with projects that have been stagnating for a while. Do I want to finish something (and, if yes, to what degree?) or just archive it? Also it's great to have a "clean house" before starting off with new plans for a new era of my life...

Finally, there are some other virtues or focus which do not fit well with the weekly rotation, but I want to mention them anyways:
  • Most importantly for me, there is reading text books and writing my blog (often inspired by what I have read). I try to read some pages of a book every week and write a blog post for at least every book that I've read.
  • Next, there is learning new skills.
  • And finally, there is finding role models, mentors, and advisers and spending quality time with them.
While reading and writing works well since I resolved to do it more regularly about a year ago, the other two items need some more thinking about how I'll go about them. But this post is long enough already, isn't it? Let me know in the comments if you are inspired by this or not. ;-)

30 January 2014

Sky-borne urban transport: introducing the FlyWay and the FlyPod

In a blog-post about one year ago I wrote about how ridiculously expensive it is to build underground transport in existing high-density cities and how much better it would be to transport people and things in the airspace over existing streets and other free space. I also wrote that elevated railways (including monorails) and elevated roadways are unacceptable in people-friendly dense cities, because they create too much noise and remove precious daylight from the streets below.
I have also discussed that hovering, flying, or floating in the air are all impractical for urban transit vehicles, so we have to find some kind of support structure to hold unto, but which takes up as little airspace as possible. Obviously, the smaller and lighter that structure is, the smaller and lighter all the vehicles have to be. This brings us to the question: how light can people-transportation vehicles possibly be? Here are some numbers:
  • Bicycle: 10 to 15 kg
  • Velomobile (fully faired, recumbent bicycle): 30 kg
  • Motor Scooter (electric or combustion engine): 50 to 200 kg
  • SegWay: ca. 50 kg
  • Renault Twizy (faired two-seater, electric): 450 kg
  • Mercedes Smart (two-seater): 730 kg
  • ULTra PRT vehicles (Heathrow Aiport, 4 seats): 850 kg
  • SUV car: up to 2000 kg and more
As you can see, light vehicles like bicycles can transport up to ten times there own weight, while the heaviest ones often transport less than even a tenth of their own weight (because the usual load is much less than the permitted maximal payload).

Thinking of transit you'll probably think of large buses and train cars which weigh several tons a piece. Those will obviously be too heavy for a light-weight approach. But don't worry about getting enough transport capacity in our system: instead of big vehicles with big gaps in-between them, we'll just have to make sure that our small vehicles can draw really close and even form emergent trains without any coordination.

Using this idea we can design a vehicle, our FlyPod, to transport people together only if they really want to travel together, not (unlike buses or trains) if they just happen to travel in the same direction. The minimal payload would then be just one person with clothing and keys while other luggage could already be transported in a separate, trailing, vehicle. However, there is lots of convenience associated with having your luggage with yourself and furthermore, if the vehicle has enough space and the seating flexibility, this space could be used for either a second passenger or for some luggage! Taking this into account our design payload would be 200 to 300 kg depending on the country of usage. (People sizes and weights vary quite a bit in the different regions of the world.) The empty weight of the vehicle would then be between 50 and 150 kg depending on other factors of the design. 

Note particularly that the resulting overall loaded weight is much less than that of typical areal lift vehicles (gondolas) which usually transport between 4 to 20 people per vehicle. And there we have the solution to our problem: just hang the vehicles on cables! Cables are so slim that they are almost invisible and small pedal-powered or electric vehicles running on those cables with less than 50 km/h will not make much noise. Supports will have to be spaced closer than for areal lifts (because vehicle density is higher), and they will have to be a bit sturdier than those built for streetcar overhead-wires, but otherwise they can be customized and integrated into the urban landscape adapting to whatever style is already present. And that's the FlyWay on which our FlyPods will travel!

FlyPods bring cycling to a whole new level

I have to admit that I personally prefer the pedal-powered variant because I love bicycling myself. It actually has so many advantages compared to a regular bicycle that it becomes a whole new experience. The best thing for me is that a passenger does not need to stop at red lights and crossings, you don't even need to look out for traffic! You could be reading on your phone, playing on your tablet or just gazing out the window for the whole trip! Totally like in a taxi except that you have to pedal a bit. And the pedaling will be easier, too, since most of an ordinary urban cyclists power is used for accelerating themselves after a stop. But if you don't stop, you also never waste energy for braking and speeding up again! Also, even though the vehicle is a bit bigger than a normal bicycle the recumbent position and the fairing make for a very aerodynamic shape which doesn't need much more power than a bicycle to get moving. In fact, vehicle weight only matters when accelerating and we just need to do that one single time per trip. (And there's help for that too, as we'll see later.) The next advantage is that you are protected from rain and wind and even excess heat, since a simple yet effective cooling system could be powered by solar panels on the vehicle roof. (The sun creates the heat, so it's always available when we need energy for cooling!) Fleet management of the FlyPods is very similar to how public bicycles (like Paris' famous Velib and numerous others around the world) are managed except that empty FlyPods can be moved around in little trains along the wires itself without taking up any extra road space for maintenance vehicles. If a station has surplus empty vehicles which need to go somewhere else, these can even be just pushed onto the main FlyWay and then pushed around by other vehicles, but this leads us to the next exciting topic: emergent trains and smooth merging.

Emergent trains are very simple to explain: since we are dealing with slow vehicles that have no obstacles on their way except other vehicles of the same sort (which in turn have no obstacles in their way...), a train simply forms by a faster vehicle bumping into a slower one! This bump is cushioned of by springs in the vehicle ends which contract as the vehicles approach and slowly expand again as the front vehicle gets pushed and the rear one consequentially slowed down. The spring also compensates for the normal small variations in pedaling power which would otherwise result in repeated bumping into each other. The nice thing about those emergent trains is that the air resistance of two closely travelling vehicles is almost the same as for a single one. In other words, not only the front vehicle profits by being pushed, but the follower also profits because they now have less resistance to overcome.

Smooth merging is also simple and it is necessary to keep vehicles from stopping at intersections. But, of course, there won't be shared intersections in the usual sense. Instead, crossing FlyWays will be on different heights such that vehicles just pass above and below each other. Just like on grade-free highway crossings turning onto another FlyWay means merging out onto a ramp and then into the other main FlyWay. Therefore, the only traffic conflict possible in this system is two vehicles merging into one lane. And this is accomplished by an automatism which uses the kinetic energy of the vehicle which enters the merging zone last to speed up the vehicle which is ahead. The second vehicle will thereby lose speed such that the first one will clear the merging point safely ahead. Note that if the vehicle being slowed down is a train, then all the vehicles behind it will also be slowed down, while the vehicle being sped up is always pulled away from the train so that the other vehicle can sneak in. If two trains meet this results in vehicles being sped up from the front of the trains in alternation while the tails of the trains get slowed down more and more.

Flying Bicycles, so what?

Of course, this great invention of mine is not going to appear in reality very soon. I found one project, called Shweep, which is very similar to what I described here (they use a very narrow metal rail instead of the cable) and which itself is still in the research stages, especially for the switching technology: how to merge in and out of lanes. I admit that my description is very fuzzy in this regard and while the rest of the system is pretty low-tech and could have been build 50 or 100 years ago, the best solution for switching might actually use quite a bit of high-tech.

While doing research into this topic I found a lot of information about "Personal Rapid Transit" (PRT) systems, a combination of mass transit and private vehicles (basically a transit system that never requires transfers and always takes you from your starting station directly to the destination station). Despite much research this never took off big and the above-mentioned ULTra system at Heathrow airport is probably the example which handles the most traffic. ULTra with its vehicles driving on normal asphalt also shows that PRT now becomes less like rail-based systems and more like ordinary cars. To me, it actually seems quite likely that self-driving cars will popularize enabling driverless taxis and thereby fulfill all of PRTs promises plus picking people up at their door without the need of any stations at all! Isn't it fun to think that SciFi also imagined flying cars which were driven by people, but now in reality we seem to be getting the boring old combustion-powered asphalt-rolling cars, but they will drive themselves?! (I know that burning fuel to drive might get out of fashion soon with electric cars, but that's not a point I want to argue here. Besides: (1) electric traction (in street-cars) was commonplace in big cities many years before cars arrived at the scene, so it's not really a new technology, and (2) there are ways to produce engine fuel from other than crude oil, so maybe combustion engines will stay with us for longer than it seems now. See XtL (sorry German), English: CtL, BtL.)

Driverless cabs might make commutes much more relaxed and save a little space on crowed streets (for example, by separating the car into two compartments and taking two passengers on the same ride, or by taking a full four or more, for a cheaper rate than a bus and still end-to-end, with a minimal detour to drop off or pick up others), but they will not make obsolete the need to create higher capacity for transport in general as in new subway construction. The FlyWay, on the other hand, can take between 10% and 30% of inner city traffic which in itself might be just enough to considerably reduce congestion on the streets as well as in subways and buses. So the FlyWay isn't just a very relaxed, comfortable, and quick way to travel for those who use it, but it's also a great service to everybody else on the road.


28 January 2014

I just donated eight percent of my 2013 net income to GiveDirectly, a charity that directly transfers this money to some of the poorest people in the world.

I have learned about GiveDirectly the charity via GiveWell, a charity evaluation project founded by two people who wanted to donate heaps of money for good purposes, but didn't find good information on what best to invest in. I already donated a smaller amount to GiveDirectly twelve months ago. What I like about GiveDirectly that they are the first organisation who do a very simple and obviously good thing efficiently on a large scale: directly giving donations to people who need resources. By donating such a large amount to one single cause, I am not neglecting all the other important causes, but I am following GiveWell's detailed analysis which says basically that most of the really good causes and efficient charities already get a lot of funding and sometimes even have trouble absorbing and using more funding with their existing staff.

Recently I read a lot of interesting articles on "effective altruism", the science of doing the most good with the little money that each of us can spare:
So Warren Buffet gives away 99% percent of his wealth during his lifetime or in his will. In the meantime he talks to other billionaires to convince them to give away at least half of their wealth and it seems he's quite successful at that. 

There's also a more inclusive club for non-billionaires (like you and me) called Giving What We Can. All you need to do to become a member is commit to regularly donate 10% of your regular income to any good altruistic cause. 

Twice in a row, I have used my winter-holidays in January to decide on and make a yearly donation. This time I realized that I can make my giving much more social by doing it in the traditional holiday season. Then I can talk to others what and where they intend to give this year. This will be much more fun and probably also do more good. I am looking forward to a great year!

7 January 2014

my vegan cooking and meditation club

→ Deutsche Version des Artikels gibt's unten! ←

I am trying a mixed German/English post here and I am not a diligent translator, so only the key facts are the same in both versions and the narration/motivation is half English, half German. Feel free to read however much you understand or want to read. ;-)

I've participated in my friend's meditation meetups every week since I came back to Berlin. (Today is the first time that I skip it, because of the parallel LYL Berlin meetup.) I also feel the desire to contribute to the world by offering or organizing meditation or self-help groups. And additionally I have the desire to meet new people and cook together, and get to know each other to possibly do other stuff together. 

So this week I decided to bring it all together and organize a combined cooking - meditation - dinner - socializing event. The idea is simple: I want to give myself and others an occasion to exchange in a relaxed and social manner, but also provide a common theme: we are all interested in cooking and meditation. Also, I find that meditating together creates a nice, tranquil atmosphere by making people more open for others. (This way, we don't need alcohol as an ice breaker ;-) We could even add a listening meditation in one of the later meetups. 

Here's a sample schedule for such an event:
6 pm: people arrive and start cooking. if too many are in the kitchen, others can just sit on the couch and chat over tea.
around 7:30 pm: when the meal is prepared and the table is set, we keep the food warm and close the doors for 20 minutes of group meditation. Then we silently walk to the dining room, do some waiting meditation for people to fill their plates, and then 15 minutes of eating meditation. Then the social part of the evening begins!

That's the end of the English part!

Random picture of delicious vegan food to make this more viral on the social networks :-P

Also hier nochmal auf Deutsch, zuerst die Idee: nur wegen einer kurzen Meditation eine lange Reise durch Berlin zu einem Treffen zu machen, kostet vielen zu viel Zeit. Aber für eine lange Meditation am Abend bin ich persönlich meist zu müde. Deswegen habe ich mir einen Kompromiss ausgedacht: verbinden wir eine kurze Meditation mit einem Kochabend und zur Krönung des Ganzen noch einer Genuss-Meditation beim Essen! Danach sind wir dann nicht nur satt, sondern auch im Geiste erholt und können den Abend gemütlich ausklingen lassen.

Hier ist ein beispielhafter Terminvorschlag (je nach Wochentag/Wochenende bzw. den Teilnehmern anzupassen):
18:00 Uhr Gäste trudeln ein und wir beginnen zu kochen. Wer in der Küche nicht gebraucht wird, darf auch gern einfach bei einem Tee auf der Couch sitzen und mit anderen plauschen (die vielleicht ihren Teil des Essens schon fertig zubereitet haben). Dadurch muss niemand pünktlich sein und jeder kann kommen, wann er eben kommt.

so gegen 19:00 Uhr: wenn das Essen fertig ist und der Tisch gedeckt, stellen wir es warm und verschließen die Tür. (Jetzt kann niemand mehr hinzukommen, damit wir in Ruhe meditieren können.)
Wir machen ca. 20 Minuten Meditation in der Gruppe (z.B. zwei verschiedene Übungen à 10 Minuten). Gleich im Anschluss und ohne zwischendurch die Edle Stille zu verlassen, nehmen wir uns Essen, warten bis alle am Tisch sind und machen dann 15 Minuten Genuss-Meditation beim Essen. Dann können wir zu reden beginnen während wir fertig essen und fließend in den sozialen Teil übergehen.