Tuesday, November 27, 2012

Configure Git, Like a Boss

I have just created a Git presentation. The presentation is named Git, Practical Tips, and it contains good practices that I have picked up during my four years as a Git user.

The presentation consists of six parts, A quick introduction; History manipulation with merge, rebase and reset; Finding with Git; Configuration; Under the hood; and Interacting with Github.

If you find this interesting and would like to hear a very practical presentation about Git tips and tricks, feel free to contact me :)

In this post I will describe how to configure Git to work well from the command line. It consists of two main parts, Git configuration and Bash configuration.

I will only describe some select samples of my configuration here. If you want to see more, my configuration files are on Github.

Git Configuration

The Git configuration part is just a bunch of aliases I use. Some are simple and some are more advanced. The aliases are declared in my global git config file, ~/.gitconfig under the [alias] tag. Here are some of most important ones.

git add --patch

[alias]
ap = "add --patch"

git ap (git add --patch) is awesome. It lets me add selected parts of the changes in my working directory, allowing me to create a consistent commit with a simple clear commit message.

git add --update

au = "add --update"

git au adds all the changed files to the index. I use it mainly when I forget to remove a file with git rm and instead remove it with rm. In this case Git will see that the file is missing but not staged for removal. When I run git au it will be added to the index as if I had used git rm in the first place.

git stash save -u

ss = "stash save -u"

git ss stashes everything in my working directory, including untracked files (-u). The reason I use git stash save instead of just git stash is that it allows me to write a message for the stash, similar to a commit message.

git amend

amend = "commit --amend -c HEAD"
amendc = "commit --amend -C HEAD"

git amend lets me add more changes to the previous commit. It is very useful when I forget to add a change to the index before I commit it. It amends the new changes in the index and lets me edit the old commit message. git amendc does the same thing but reuses the old commit message.

git alias

alias = "!git config -l | grep alias | cut -c 7-"

git alias shows me all my aliases. Starting with a bang (!) is necessary to execute arbitrary bash commands. Note that the git command must be included. The code in the alias means, list configuration, find aliases, show characters 7 and on.

git log --diff-filter

fa = "log --diff-filter=A --summary"
fd = "log --diff-filter=D --summary"

git fa (find added) and git fd (find deleted) shows me a log of commits where files were added and deleted respectively. It is great for finding out how and when my files get deleted. I use it with a filename git fd my-missing-file.rb or with with grep, git fd | grep -C 3 missing.

grep -C 3 means shows me 3 lines of context around the matching line.

git log-pretty

l = "!git log-hist"
log-hist = "!git log-pretty --graph"
log-pretty = "log --pretty='format:%C(blue)%h%C(red)%d%C(yellow) %s %C(green)%an%Creset, %ar'"

git l is my main logging command it and prints a beautiful compact log. When I reuse an alias I must use the shell command alias, the bang (!), since Git does not allow me to reference an alias from another directly.

log               = The log command
--graph           = Text-based graphical representation
--pretty='format' = Format according to spec
%C(color)         = Change color
%h                = Abbreviated commit hash (6b266c2)
%d                = Ref names (HEAD, origin/master)
%s                = Subject (first line of comment)
%an               = Author name
%ar               = Author date, relative

git log --simplify-by-decoration

lt = "!git log-hist --simplify-by-decoration"

git lt (log tagged) uses --simplify-by-decoration to show a list of "important" commits. Important in this case means commits that are pointed to by a branch or tagged. It reuses the log-hist alias above.

Bash Configuration

I used to have a bunch of aliases, such as ga, gd, etc. but, now I use my Git aliases instead. But I still have configuration for command completion and a nice informative prompt.

function g()

I use the git command more than any other command during a days work. git status is the subcommand I use mostly. I have optimized for this by creating a function g() that has status as its default argument.

# `g` is a shortcut for git, it defaults to `git s` (status) if no argument is given.
function g() {
    local cmd=${1-s}
    shift
    git $cmd $@
}

The g() function gives me a lot of power out of a single character.

$ g
## master
 M README.md
?? doc.md

$ g l
* 4f71f8d (HEAD, heroku/master, master) Send 404 for missing ...
* ec00879 Added support for options Anders Janmyr, 5 weeks ago
* 09c178f (origin/master) id cannot be a number Anders Janmyr, 6 weeks ago
* e561d03 Send status and send in one call Anders Janmyr, 6 weeks ago
* 9615be5 Added some more logging Anders Janmyr, 6 weeks ago
* de4730e Improved the code somewhat Anders Janmyr, 6 weeks ago
* 1f3f763 Added allow methods header Anders Janmyr, 6 weeks ago
* ca3065c Added filter to documentation Anders Janmyr, 6 we

function gg()

My second (and last) function is gg().

# Commit pending changes and quote all arguments as message
function gg() {
    git ci -m "$*"
}

gg() allows me to type a commit message without any quotes.

$ gg Added todo list to the Readme
[master 98556af] Added todo list to the Readme
 1 file changed, 1 insertion(+)

bash-completion

Installing bash-completion gives me command completion for commands, subcommands and more.

# An example
$ git rem<TAB> sh<TAB> o<TAB>
# will complete to
$ git remote show origin

I use Homebrew to install Git, brew install git. It gives me a new version of Git. It also installs git-completion.bash in /usr/local/etc/bash_completion.d/.

I use the same configuration on Ubuntu and I check for the file in /etc/bash-completion.d/ too.

# Prefer /usr/local/etc but fallback to /etc
if [ -f /usr/local/etc/bash_completion.d/git-completion.bash ]
then
    source /usr/local/etc/bash_completion.d/git-completion.bash
elif [ -f /etc/bash_completion.d/git ]; then
    source /etc/bash_completion.d/git
fi

This is great but, what about my beautiful little g() function? How do I make it work with command completion? It turns out to be quite easy. Include the following little snippet in a configuration file, such as .bashrc.

# Set up git command completion for g
__git_complete g __git_main

The snippet reuses the functions, __git_complete and __git_main included with git-completion.bash to make completion work with g too. Lovely!

bash-prompt

In later versions of Git, the prompt functionality has been extracted out into its own script, git-prompt.sh. I include it like this.

if [ -f /usr/local/etc/bash_completion.d/git-prompt.sh ]
then
    source /usr/local/etc/bash_completion.d/git-prompt.sh
fi

I configure my prompt like this, it contains a little more magic than the plain Git configuration. I put it in one of my bash configuration files, such as .bashrc.

function prompt {
  # Check exit status of last command
  if [[ "$?" -eq "0" ]]; then
    # If it is OK (0) color the prompt ($) green
    local status=""
    local sign=$(echo -ne "\[${GREEN}\]\$\[${NO_COLOR}\]")
  else
    # If not OK (not 0) color the prompt ($) red and set status to exit code
    local status=" \[${RED}\]$?\[${NO_COLOR}\] "
    local sign=$(echo -ne "\[${RED}\]\$\[${NO_COLOR}\]")
  fi
  # Get the current SHA of the repository
  local sha=$(git rev-parse --short HEAD 2>/dev/null)
  # Set the prompt
  # \!                 - history number
  # :                  - literal :
  # \W                 - Basename of current working directory
  # $sha               - The SHA calculated above
  # $(__git_ps1 '@%s') - literal @ followed by Git branch, etc.
  # $status            - The exit status calculated above
  # $sign              - The red or green prompt, calculated above
  export PS1="[\!:${LIGHT_GRAY}\W${NO_COLOR} $sha${GREEN}$(__git_ps1 '@%s')${NO_COLOR}$status]\n$sign "
}

# Tell bash to invoke the above function when printing the prompt
PROMPT_COMMAND='prompt'

The function __git_ps1() can further be configured with some environment variables. This is what use.

# Git prompt config
export GIT_PS1_SHOWDIRTYSTATE=true
export GIT_PS1_SHOWUNTRACKEDFILES=true
export GIT_PS1_SHOWUPSTREAM="auto"
# export GIT_PS1_SHOWSTASHSTATE=true

The resulting prompt looks like this:

The different signs to the right indicate:

# * - Changed files in working dir
# + - Changed files in index
# % - Untracked files in working dir
# < - The branch is behind upstream
# > - The branch is ahead of upstream (Yes, it can be both)

More info can be found in git-prompt.sh.

Credits

Obviously I have not figured this out all by myself. Here are some of my sources:

Sunday, November 11, 2012

The Double Rainbow at Øredev 2012

At Øredev I had a discussion with some people about how the double rainbow comes about so in the spirit of sharing knowledge I thought I would share how it works.

The first rainbow comes from light being reflected once in the raindrop and similar to a prism the refraction of the light in the drop splits the white light into different colors.

Compare with the prism on Pink Floyd's Dark Side of the Moon.

The secondary rainbow on the other hand comes from the light being reflected twice inside the drop.

This is the reason the colors of a real secondary rainbow are inverted.

If you find this kind of stuff interesting I can recommend the book Light and Color in the Outdoors. It is expensive, so you may want to borrow it from the library (in Sweden) instead.

Friday, November 09, 2012

Øredev 2012, Notes from Day Two

The Rebellion Imperative, Reginald Braithwaite

Every daring attempt to make a great change in existing conditions, every lofty vision of new possibilities for the human race, has been labelled utopian. -- Emma Golden

Wealth breeds inefficiency

Since a wealthy man can buy anything he wants he has no need for efficiency.

The powerful enforce statis.

Progress is against their best interests.

Stasis, the state of equilibrium or inactivity caused by opposing equal forces. -- dictionary.com

The four sustainable positions from Marketing Warfare

  • The Leader Defends
  • The Rival Attacks
  • The Innovator Disrupts
  • The 99% are Rebels

Android is for people that don't need to be cool!

Don't attack their weakness, attack their strength!

Principles of Rebellion

  • Find a territory small enough to defend - and don't overextend yourself.
  • Never act like the leader.
  • Be prepared to bug out at a moment's notice.

God fights on the side with the most cannons. -- Napoleon

When you are being rebellious, you don't want a lot of dependencies, like infrastructure etc. You need to be in control of your own destiny.

Bug out

You can't fall in love with what you are doing, because most of the time it will not work out.

A rebel does not have resources to waste on a lost cause.

Rebels are lean

  • Rebels have lean businesses.
  • Rebels use lean tool chains.

Disruption

If there is an existing market, you are doing it wrong.

Analysts are wrong because they are corrupt motherfuckers who are paid to make press releases. -- Reginald Braithwaite

You can't ask customers, you have to tell them!

Micro Service Architecture, Fred George

Unit test counts are important, the more you get working the more you show progress.

1M loc -> 100K loc trying to get out -> 20 * 5K loc services, trying to get out

Only nuggets should be published by the services. Nuggets are small pieces of information not the whole blob. If you need everything go get it from the source.

Clients that are not desperate will not try anything interesting at all.

Bayesian Service Principles

  • It's okay to run more than one version at the same time.
  • You can only deploy one service at at time.

Observations

  • Services are like classes, small, crisp conceptualization, 100 loc.
  • Smalltalk messages perfect for services.
  • Encapsulation, every service own the data.
  • Services became disposable, no need for test, just rewrite them.
  • Loosly coupled via RESTful JSON
  • Self monitoring services replaces Unit Tests.
  • Business monitoring replaces acceptance tests.
  • Service language-agnostic, Ruby, Node, Clojure

Problems

  • Cycle, lost packets
  • Need to redefine tracking, logging
  • No experience in defining services.

Data Ecosystems

Collect all the data, In The Plex

  • Consumers, R, Hive, Monitoring, Apps, Services
  • Producers, app, app, service, web server

Conclusions

  • Agile Best Practice Not Used
  • Technical Debt does not appear, services are so small.

Principles

  • Very small
  • Loosely coupled
  • Multiple versions acceptable
  • Self-execution monitoring of each service
  • Publish interesting stuff
  • Application is a poor conceptualization

Living Software System

  • Long-lived system, short lived services
  • Extremely dynamic with continuous deployment, 5-10 minutes between deploys.
  • Accept it is complex (especially for testing)
    • Acceptance test on business outcomes instead.
  • Radical impact to processes, anarchy
  • There will be a learning curve for developers!

Scalable and Modular CSS FTW, Denise Jacobs

Denise gave an overview of some other people's ideas. The ideas come from Object Oriented CSS, SMACSS, and CSS For Grown Ups.

OO CSS (I think)

DRY, Don't Repeat Yourself, Never repeat a style property if you can Group selectors with shared properties. Ask yourself why isn't this part of the group?

  • Use a grid
  • Use a reset CSS
  • Use the cascade
  • Separate structure and presentation
  • Style classes rather than elements
  • Don't use IDs for styling, only for JS hooks
  • Avoid class names that are related to the style.

SMACSS

Categories of styles

  • Base
  • Layout
  • Module
  • State
  • Theme

Shallow Selectors

  • Use class names as the right-most key selector.
  • You're better of adding classes than having overly-specific selectors.
  • Module candidates navbars, carousels, dialogs, widgets, tables, icons
  • Naming conventions are very important. Examples is-active, is-collapsed, btn-pressed

CSS for Grown Ups

Don't style pages, instead style modules and make a library that you can reuse.

Categories of Styles

  • document
  • base
  • module
  • layout

Javascript styles prefixed with js-

Common ideas

  • IDs not so much
  • Classes are good
  • Less is more
  • Use modules
  • Naming conventions? !important

  • Structure and inform, naming conventions, grids

  • Reduce, no inline styles, short chains, don't use elements, prefer classes over IDs

  • Recycle and Reuse, Leverage the cascade, modularize page components, extend through sub classing.

Measure twice, Cut once.

Techniques for improving CSS

  • Optimize Selectors
  • Reduce the redundant
  • Clear the cruft,
    • eliminate style that rely on qualifiers high in the domA
    • Create portable styles
    • Institute a Grid, box-sizing, make it fluid max-size: 100%
  • Separate the modules into separate files.

New best practices

  • normalize.css
  • Use a better Clearfix
  • Use an <hr> as a divider
  • Image replacemenet
  • Use an <i> as an icon element.

Less, the Path to Good Design, Sandi Metz

  • The Design is the Code
  • Code need to work once and be easy to change forever
  • The purpose of design is to minimize the cost of change.
  • Loosely coupled, highly cohesive, easily composable, context independent
  • Transparent, Reasonable, Usable, Exemplary
  • Design is never perfect, the code is never done.
  • Done is good enough!

  • Sequence diagrams are great for object oriented design.

  • Managing dependencies is at the center of design.

  • The objects of which you are most uncertain are probably the ones that are at the center of design, they are your core objects.

  • Uncertainty, shows you where to decouple.

  • Trustworthy objects knows more of what they want and less of what others want.

  • Practical Object-Oriented Design in Ruby

Typescript, Mads Torgerson

Typescript is a typed superset of Javascript that compiles to plain Javascript. It adds optional static types, classes, and modules. It compiles to idiomatic Javascript.

The type system

Being a superset means that raw Javascript is allowed in Typescript. Since typing is optional errors should be seen as warnings. The language supports type inference which gives you type safety without declaring all variables.

The biggest advantage of the static typing is that it gives good code completion. The type system is structural, similar to Go, and that allows duck typing like calls. It supports optional properties so it is more about guiding you than forcing you to follow strict rules.

The functions in Typescript supports overloading, i.e. foo(x: string) and foo(x: number). Functions can be declared to have properties.

It is also possible to declare index accessors [] on the objects, declared like this.

foo = {
  [x:string]
}

Typescript supports type inference on the built in Javascript objects by means of declare files provided by the IDE.

Classes and Modules

Classes in Typescript follows the Ecmascript standard, and adds types, privates and statics.


class Greeter {
    private greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
    static default = new Greeter('Hola');
}   

var greeter = new Greeter("world");

Typescript also supports lambdas => and it provides lexical scoping of this similar to what Ecmascript will provide

Modules

Modules are declared with the module keyword and export properties explicitly.

module Sayings {
    export class Greeter {
        greeting: string;
        constructor (message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
}
var greeter = new Sayings.Greeter("world");

Datomic, Tim Ewald

Fact, an event or thing known to have happened or exists Datoms, a tuple with entity, attribute, value, time

Everything can be encoded by datoms.

A collection of facts

  • An append-only model
  • Data is immutable
  • Database state at given time is a value

Datomic Architecture

  • Separate read, write, and storage.
  • All apps reads from a local cache.
  • A transactor supervises the writes and reflects it out to the peers.

Reading

  • Read / query db value in the peer.
  • Long-running work on consistent image.
  • Opening query to clients with bulkheads
  • Cross-database joins

Query

  • Datalog-based query language
  • Can invoke code
  • Can define views using rules
  • Can invoke application specific code
  • Supports querying the past and a possible future.

Direct Access

  • Entity Maps
  • Direct Index Access via iteration

Writes

  • Writes managed by transactor, single point of failure
  • True ACID semantics, transactor functions can be stored in the database.
  • Reified transactions can be queried as normal data.
  • Transaction notifications can be listened to by the peers.
  • Transactions return db-before, db-after, tx-data, tx-id

Storage

  • mem, dev, ddb, sql, infinispan, riak, couch, etc.
  • Pick a service that provides the scale and availability you need
  • Migrate as needed with backup and restore.

Thursday, November 08, 2012

Øredev 2012, Report from Day One

Software won, so what now? - David Rowan

A healthy disregard for the impossible.

Software developers have the power to make a massive impact. We should do something other than help people pass the time or sell more on the Internet!

We should do this by making it easier for non software developers to write programs. One solution, David believes, is to create new languages, for example DOG!? I don't agree with him that this is a good way forward, Applescript anyone?

The Internet can be used to create greater transparency for government and companies. Some examples

  • I paid a bribe web site.
  • Thank doctors who works without taking bribes.
  • Making transparent elections.
  • TED, Ideas worth spreading.
  • Publicising data to get help with data mining.
  • Random hacks of kindness
  • Education, Udacity, CoderDojo, Rails & Girls
  • Government, Street Bump, Don't Eat At, Open Government API
  • Health, Asthmapolis

Vim, Precision Editing at the Speed of Thought, Drew Neil

We spend a lot more time editing text than inserting text, so it is only appropriate that the keys can be used without modifier keys.

Vim is more like playing a melody than playing a chord.

Targets

The ideal way to move the cursor to the target is to look at the place where you want the cursor to go and it would just go there.

The mouse is very intuitive for finding targets, but it requires precision and breaks your typing flow.

Hunt and Peck is the standard interface in a less capable editor if you are not using the mouse. That means using the arrow keys to find the proper plays, possibly after moving to an area closer to the spot you want first.

Vim provides precision targetting, short commands that allows you to move to the spot you want. An example of this is the f command.

f{char} moves you to the first occurence of of the letter char.

fb moves you to the first b on the line.

Vim also have something called text objects. Text objects are pieces of text delimited by characters such as quotes, parentheses, or tags.

vi{delimiter} Visually selects the text Inside of the delimiter. va{delimiter} Visually selects All the text including the delimiter.

`vi)` selects the text inside the parentheses.
`di)` deletes the text inside the parentheses.

`va"` selects the text and the quote.
`da"` deletes the text and the quote.

Vim allows navigation between files with commands like:

gf to move to the filename under the cursor.

ctags is an external indexing program that allows you to go directly to definition and other navigations common to a lot larger IDEs.

This was a good introductory presentation to Vim, but nothing new for experienced Vimmers.

Software in the Age of Sampling, Brian Foote

Most new software development is really taking sampling and mashups. We take libraries or code snippets that already work and tweak them to work the way we want.

Copy and paste is a really powerful technique to get us started. We all do it all the time.

If you are going to steal, steal from the best

But, when you steal make sure it works by understanding it or putting it under test. Also make sure to add your own style to what you steal to make it fit with your own code base.

What's new in ASP.NET 4.5, Damian Edwards

ASP.NET 4.5 comes with some good stuff built in, OAuth, NuGet, Asset handling, and async support.

OAuth authentication supported with different providers. Supports connecting and disconnecting the local account from the external providers.

Package manager is pre-configured to use NuGet.

Support for concatenation and minification of Javascript via Bundles. Support for precompilation and minification of CSS via external Bundle plugins.

Async

  • Make async handlers by extending HttpTaskAsyncHandler or Forms.Page
  • HttpClient is exclusively async.
  • Task.WhenAll and Task.WhanAny to handle parallel tasks synchronization.
  • CancellationTokens help you cancel many tasks at the same time.

Microsoft has done a good job integrating async into DotNet.

Testing Online Crazy Glue, Chris Hartjes

Testable applications are better!

Chris introduced us to testing PHP. The sad news is that even though PHP is a dynamic language it has to be tested as if it is static.

The good news is that testing static languages is a solved problem. It is solved by tools, strategies, and automation.

  • The tool of choice is PHPUnit.
  • The strategy is dependency injection and mocks.
  • Automation is solved with a simple script, and version control hooks or a CI-server.

It is not hard to do TDD in PHP, the tools are there, use them!

Sunday, September 23, 2012

Reasons to Go to Øredev, Reginald Braithwayte

Øredev is selling tickets like never before. For the first time ever we believe we will sell out all days and not just Wednesday, like last year. So if you still haven't bought a ticket it is time to do it now.

To help you along the way I'm going to present you with another reason to register, Reginald Braithwayte

Reginald has recently released some books through leanpub, such as What I've learned from Failure and How to Do What You Love & Earn What You’re Worth as a Programmer.

I first came in contact with Reginald through the blog, Raganwald, where he wrote about programming, testing, agile, work, etc. On this blog, you can find gems, such as:

The Narcissism of Small Code Differences where he writes about different styles of programming and why and why not they matter.

Why Why Functional Programming Matters Matters?, a commentary on the paper "Why Functional Programming Matters". It discusses topics such as "Separation of Concerns" and "Responsibility Driven Design".

The significance of the meta-circular interpreter discusses meta-programming, DSLs, and why it is important for a language to be self hosted.

Programming conventions as signals, a blog about why it is important to write in a style that signals the intent of the code to other programmers.

More recently he started another blog, Homoiconic, hosted on Github. In this blog you can read about functional programming in Javascript, Coffeescript, etc.

Some of my favorites are:

Method Combinators in CoffeeScript where he uses function combinators to create AOP like constructs like before, after, around, etc.

Captain Obvious on JavaScript, examples using functional programming in Javascript.

Reg will be giving a keynote on rebellion and a talk on jQuery Combinators Don't miss him at Øredev.

Sunday, September 16, 2012

Enthusiasm, the Invisible Key to Success

Nothing great was ever achieved without enthusiasm. -- Ralph Waldo Emerson

The quote from Emerson is a classic but, even though it is true, we don't put enough effort into encouraging enthusiasm.

So, why do I say that enthusiasm is the key to success? There are a two reasons for this. The first is happiness, enthusiastic people are happy.

Happiness

Happy people are better at creative problem solving. -- Martin Seligman, Authentic Happiness

In positive conditions, mental images appear rapidly, with great variation and our thought process flows quickly. -- Antonio Damasio, Descartes' Error

Happy people are more likely to have insights. -- David Rock, Your Brain at Work

Time

The other reason why enthusiasm is important is the amount of time spent on the issue that we are enthusiastic about. When I write the amount of time spent on the issue, I mean two different kinds, conscious and unconscious time.

Conscious time is the time we spend actually working on the task at hand. Enthusiastic people will spend a lot more focused time on the task than on something else like Twitter, Stackoverflow, or Facebook. This is of course great but, this is not the most important time.

Unconscious time is the most important time. This is the time we spend not actually working on the task, but doing other thing such as taking care of our kids, enjoying sports, beer, or even sleeping. As I wrote about in Rationality is Overrated, our unconscious mind has a lot more capacity than our conscious part. An enthusiastic mind will work overtime, for free, on any task. This is not something we should take lightly.

The enthusiastic approach may not always be the most sensible approach. This is OK, enthusiasm is more important than sense.

What is sensible about open source? Open source is created by enthusiasts and the code usually has a lot higher quality than enterprise code.

Encouraging Enthusiasm

If you believe my above reasoning, it is easy to see why encouraging enthusiasm is important. So how do we do it? We do it by trusting people. We do it by letting the people working on our projects do it in the way that they find best. This is what is talked about in the Scrum books about hyper-productive team's. It has little to do with Scrum and everything to do with enthusiasm and autonomy. Autonomy is one of the major driving forces of motivation in Dan Pink's book Drive. Hyper-productive teams are enthusiastic teams and they are hyper-productive because their brains, conscious and unconscious spend more time on the project than any Death March project is able to force in.

But, it is not enough to just allow people to be autonomous, it is also important to encourage everyone on the team to become enthusiastic about what they do.

Everyone should be encouraged to do the tasks they are enthusiastic about and, they should also be encouraged to reframe the tasks they are not enthusiastic about into tasks that they are enthusiastic about. This is a lot easier than it sounds. One way to do this is to encourage people to create tools that allows them to automate what they find boring. Writing automation software is not boring, in my opinion.

There are of course other things that will help you and your team build your enthusiasm. Find them and encourage them.

Discouraging Enthusiasm Dampening Behavior

There are three things that kill my enthusiasm. They are unnecessary process, bad code and deadlines.

Unnecessary process

You can almost tell from the name that it is unnecessary :). Being unnecessary means that it is also an enthusiasm killer. Process should be minimal. Challenge every part of the process, often! An unnecessary part may sneak in without anyone thinking about it at the time.

Bad Code

You may have heard of the broken window theory

Applied to code, it basically says that if you allow bad code (broken windows) in your application, eventually the whole application will be broken, since the bad code will serve as an example and give silent permission to write more bad code. This is a theory that I believe in.

But I also have a corollary to this theory, I call it the pile of shit theory.

The Pile of Shit Theory, if you leave crappy code in an application for too long, the stench will eventually drain the enthusiasm from the developers working on that code.

If the crappy code cannot be completely isolated from the application, it must be refactored or the enthusiasm for the entire application will eventually disappear, and along with it the developers.

There are lots of other things that may dampen yours and your teams enthusiasm, try to identify and eliminate them as soon as possible.

Deadlines

I have written extensively on my thoughts on deadlines in No Deadlines, so I'm not going to dwell on it too much this time. Suffice to write that deadlines, usually, is incompatible with enthusiasm. Since deadlines produces stress, and stress puts us out of flow.

Summary

Enthusiasm is an almost unlimited resource that we must take advantage of. How much of your day do you spend on tasks that you are not enthusiastic about? It is time to stop doing that and to become a happy, productive enthusiast.

Nobody grows old merely by living a number of years. We grow old by deserting our ideals. Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. -- Samuel Ullman

Monday, August 27, 2012

CSS Good Practices

Most web developers have realized that Javascript is a first-class citizen in web development, but the same is not true of CSS. CSS is still "the wild west" and I believe that this is because CSS falls between the chairs of developers and designers. CSS is also a first-class citizen and it needs as much love as Javascript to avoid becoming a maintenance nightmare. Here are some ideas that I believe are good practices to follow.

Use a pre-processing language

CSS does not allow us to use standard abstractions such as variables and functions. This makes duplication common practice, but there is a simple solution to this problem. Use a pre-processing language! There are a number of good alternatives, Sass, Less, Stylus, etc. My preference is the SCSS dialect of Sass but, I have no problem using any other variants as long as they give me the abstractions I need.

The first abstraction is variables, which are really constants since they are commonly never changed. Consider the following example:

.info-message {
    color: #eee;
    background: #1e1;
    margin: 5px;
    padding: 5px;
}

.error-message {
    color: #eee;
    background: #e11;
    margin: 4px;
    padding: 5px;
}

What do these values mean? Is the color #eee, referring to the same concept in both info-message and error-message? Should the margin and padding be the same in both cases, or should it be off by one pixel? Looking at this CSS, it is not possible to tell. Contrast it with the following SCSS.

$info-message-foreground-color: #eee;
$info-message-background-color: #1e1;

$error-message-foreground-color: #eee;
$error-message-background-color: #e11;

$message-margin: 4px;
$message-padding: 5px;

.info-message {
    color: $info-message-foreground-color;
    background: $info-message-background-color;
    margin: $message-margin;
    padding: $message-padding;
}

.error-message {
    color: $error-message-foreground-color;
    background: $error-message-background-color;
    margin: $message-margin;
    padding: $message-padding;
}

Isn't that lovely! Now there are not doubts about what anything means anymore. It turned out that #eee was referring to different concepts in info-message and error-message

Variables is enough reason to use a pre-processor, but since we are now already using a pre-processor we may as well take advantage of another killer feature, mixins.

Mixins allows us to chunk up common concepts into reusable blocks. Continuing with the example above we can introduce a mixin, message-layout to get rid of the duplication of margin and padding.

...
$message-margin: 4px;
$message-padding: 5px;

@mixin message-layout {
    margin: $message-margin;
    padding: $message-padding;
}

.info-message {
    color: $info-message-foreground-color;
    background: $info-message-background-color;
    @include message-layout;
}

.error-message {
    color: $error-message-foreground-color;
    background: $error-message-background-color;
    @include message-layout;
}

Another way to do this is to create a parameterized message-box-mixin.

$info-message-foreground-color: #eee;
$info-message-background-color: #1e1;

$error-message-foreground-color: #eee;
$error-message-background-color: #e11;

$message-margin: 4px;
$message-padding: 5px;

@mixin message-box($message-foreground-color, $message-background-color) {
    color: $message-foreground-color;
    background: $message-background-color;
    margin: $message-margin;
    padding: $message-padding;
}

.info-message {
    @include message-box($info-message-foreground-color, $info-message-background-color);
}

.error-message {
    @include message-box($error-message-foreground-color, $error-message-background-color);
}

Sweet! As you can see from this simple example, a pre-processor is not really something that we should do without. I consider it professional malpractice not to use one.

This is only the tip of the iceberg. Now that we are using a pre-processor we can make use of pre-packaged mixin libraries such as, Bourbon or Compass, relieving us from having to write all the vendor-variants all over again. But don't go overboard, use with moderation.

Everything with moderation, including moderation. --Oscar Wilde

Pre-processor usage

When using a pre-processor there are a few ways to use it.

  1. Use a framework that supports pre-compilation, such as Rails or Express
  2. Use a watcher and check in the generated CSS.
  3. Use a watcher, but don't check in the generated CSS. Deploy using a build-script that does the pre-compilation.

My preferred choice is to use a framework that supports it, but if that is not an option, I prefer to not check in the generated CSS. There is a small problem with this approach when using Git as a deployment tool, like Heroku does. This problem is best solved with some clever scripting and an extra deployment branch that is used to hold the generated CSS for deployment.

Watchers come in many forms, sass --watch, Watchr, Guard, and Livereload to name a few.

Variable and Mixing Naming

Variables names should reflect the names of the domain. The domain, in this case, is the name of the designers, commonly called the legend. They know what it means when they talk about a color palette, primary-color, etc.. We should know what this means too, and we should use these names.

Mixins comes in two forms, domain-mixins related to our application, and utility-mixins overcoming deficiencies in browsers etc.

Domain-mixins are similar to variables and should be named similarly. Utility-mixins are more general, they can often be reused across projects and should be named appropriately and separated out into their own file.

CSS Naming

Naming is another part of CSS that is inconsistent to say the least. The most common way of naming CSS entities is to use dasherized names, such as my-lovely-tapir and left-margin. I believe this is the best way for a couple of reasons.

  1. It is the way that CSS internal properties are named, left-margin, border-radius, -webkit-search-decoration.
  2. It makes a clear contrast between CSS and Javascript properties.

Sometimes it may be convenient to use CamelCase or snake_case style to interact with another programming language. Avoid falling for this temptation. It is not difficult to write a camelcase, snake\_case or, dasherize function to convert between the different styles.

IDs and Classes

Since IDs are global in the page, they should be named with specific names that clearly identifies what they are on the page. Classes, on the other hand, are not unique, and should be named with more general and succinct names to allow for reuse across scopes.


/* Specific singleton elements are named with specific names. */
#sidebar {}
#send-email-button {}
#all-animals
#animals-in-tapir-cage

.selected {
    /* Common for all selected elements on page. */
}

#all-animals .selected {
    /* Specific CSS for selected elements in #all-animals. */
}
#animals-in-tapir-cage .selected {
    /* Specific CSS for selected elements in #animals-in-tapir-cage. */
}

Sass Nesting can be put to good use when writing this kind of CSS, but beware of creating overly long selector chains, since this will slow down the CSS parser as well as making the code less clear. There is never a need for two IDs in a selector, since IDs are unique. (Unless you are overriding someone else's crappy CSS, that has put this horrendous method to "good" use :)

It is also possible to avoid using the generic .selected element altogether by making it a mixin instead of class, but I believe that the method above still has a place.

Structure and Semantics

The HTML provides the structure of our GUI but, it also contains the semantics of our GUI. When we put a class or an ID on an element, we are naming that part of the DOM-tree. We should name it in a way that makes is clear what the meaning of this part of the tree is. It is not different from naming a class or an object in a real programming language, and just as important. Name it so that it easy to reason about that part of the tree. What is this area used for? What does it contain?

If an HTML element makes it clear, it is better to use the element than to use a class. It is better to use <article> than <div class='article'>. On the other hand it is better to use <div id='sidebar'> than <aside> since aside has a different meaning, than commonly believed.

aside, a remark that is not directly related to the main topic of discussion -- dictionary.com

There is absolutely no reason to use "style-classes".

/* Horrible use of CSS */
.mb5 {
    margin-bottom: 5px;
}
<!-- Horrible use of CSS -->
<div class='mb5'>
...
</div>

Not only does this suck from a semantic and structural perspective it is also awful because it is less clear than style='margin-bottom: 5px' and it encodes the value in the name, a few weeks later the code will be littered with mb5s and the CSS will change to 8px, making insanity the norm.

/* Horrible use of CSS */
.mb5 {
    margin-bottom: 8px;
}

But there are also other uses of style-classes, that group a set of properties together in order to reuse them on many different elements. If you are not using a pre-processor I understand the need for this but, when you are using a pre-processor this behavior can be replaced by mixins.

Grids

Grids are another type of style-classes that I believe that we can remove from our HTML. I am not experience enough in responsive design to confidently say that it is possible to do it well without polluting the HTML with span4, offset3, etc. but, I feel that this type of styling can be moved into pre-processor functionality like the Bourbon#flex-grid

Summary

CSS is a first-class citizen of web development, but it is not good enough to be used without a pre-processor providing us with better abstractions. A good pre-processor allows us to clean up not only our CSS but our HTML too. That is a very good payoff for the small price of a small compilation step.

Saturday, May 19, 2012

Notes on "Your Brain at Work"

I just finished reading Your Brain at Work by David Rock and it is really good. If you haven't read it I can highly recommend it. Since I think it is so full of good ideas, I decided I wanted to write down my understanding of it while it is fresh. I also recently finished reading Blah, Blah, Blah by Dan Roam and I'm going to use his Vivid style in this text.

The Prefrontal Cortex

Our consciousness is located in an area of the brain called the Prefrontal Cortex (PFC).

The Prefrontal Cortex main responsibilities are: recalling, memorizing, understanding, deciding, and inhibiting.

Recalling, getting information from long term memory into the PFC.

Memorizing, storing information from the PFC into long term memory.

Understanding, connecting new information to the information already stored inside our brain.

Deciding, comparing two or more different items and deciding which one is most suitable.

Inhibiting, preventing information from other parts of our brain and outside interferences from entering the PFC.

Attention is Limited

Paying attention consumes energy and the brain has limited resources available. The more ideas we try to hold in our head at once the less attention we can pay to each of them.

One especially energy consuming task is prioritizing, since it involves most of the ideas that the PFC has to do. In order to be able to prioritize well, we should do this when our minds are fresh. We need to prioritize prioritizing!

In the sixties George A. Milner, experimented with consciousness and came up with the idea that we are only able to hold 7±2 items in attention at once.

The problem with this is that he probably overestimated our abilities. It is more likely that the number is less than four, and the less the better.

Preserve Resources

The more information we can get our of our PFC, the better we will be able to focus on what is in it. Good ways to get things out of our PFC are: write them down or draw them. Visuals are especially good since our brain is very good at dealing with visual information and consumes less resources when dealing with visuals.

Another important task to do to preserve resources is to inhibit low prioritized thoughts. Write them down so that they don't consume your resources any more. Tasks that are not well-defined consume a lot more energy than they are worth.

When comparing items, the less items you need to compare the better. The optimal number of items to compare is two. And, it is important to get the ideas out of your head and onto paper, so that you don't have to try to remember the other things while you are debating the merits of one.

New ideas consume more energy than old, since old ideas are just references into long-term memory.

Two techniques for limiting the amount of information you hold in you PFC are chunking and simplification.

Chunking means grouping information into one chunk. It is easier to remember 1978 than to remember 1, 9, 7, 8.

Simplification is a way of ignoring the complexity of something by just labeling it.

Multi-Tasking

Armed with this information it is easy to see that multi-tasking is a very bad idea. Dual-task interference happens when we try to do two or more things simultaneously. When this happens we loose precision. If accuracy is important don't divide your attention.

If you do need to multi-task, here are some techniques that helps.

  • Order things and only work from the front of the queue.
  • Explicitly suspend-resume. Do one thing, stop, do another thing, stop, etc. It is a good idea to let others know that you are switching between tasks to let them know when you are paying attention or not.
  • Automate it! This means learn it well enough so that you can do it without thinking consciously. More about this in my blog, Rationality is Overrated

Distractions

The brain is easily distracted. It has survived thousands of years by reacting to "a rustle in the bushes".

In our modern world similar, external, distractions come in the form of mobile phones, email, twitter, colleagues, friends, family, etc.

Avoiding distractions, inhibition, consumes energy, so, it is best to not let the distractions distract you in the first place.

Along with external distractions we also have internal distractions, impulses. It is not as easy to turn off the internal distractions. To do this we need to practice self-control. But self-control is also a limited resource. When you have resisted one impulse, it gets harder to resist the next.

Internal distractions are often triggered when we are thinking of ourselves. We can reduce the likelihood of internal distractions by clearing our mind before we set out on a new task.

We can improve our mental breaking system by practicing, and re-enforce it by doing something physical along with the mental braking.

Getting Stuck

Getting stuck on a problem is called an impasse. To resolve an impasse, we need to let the brain idle. This gives the unconscious part of the brain a chance to solve the problem.

To have insights involves hearing subtle signals and making loose connections. This requires a quiet mind with minimal electrical activity.

Insights occur more frequently when you are relaxed and happy. Take a break, do something interesting. Focus on connections between information instead of details. Simplify problems into a very high-level description.

The Networks of the Brain

In the brain we have two main networks: the narrative network and the direct experience network.

The Narrative Network is the default network when nothing is happening. It keeps a conversation going in the mind. It makes assumptions and figures out plans from them. It is very sequential in the way it works. If I think of this, then this, then this, then this, etc., etc., etc. By just tuning in to this network, we make us very busy indeed. All the time. When we receive information through this network, it is filtered, and interpreted before we can do anything about it.

The Direct Experience Network is our other main network. It is triggered when we let the brain idle, and just "listen" to what our senses tells us. This is often called mindfulness. This network is not sequential like the narrative is. It is immediate and it makes use of the full processing power of the brain and not just the pre-frontal cortex. The sensory information that is received through direct experience include information about the self, about thoughts, feelings, emotions, and internal states.

When we need to get unstuck or unstressed, it is very wise to try to shift over to direct experience. This can be done by focusing on sensory information, such as how the chair feels on our buttocks, how the wind feels on our cheeks, or listening to the sound of birds singing or our own breath. This simple act will allow the brain to get unstuck of its previous ideas. The act is actually not that simple, it is not easy to focus on one thing for more than a few seconds.

Mindfulness

A part of working memory called the executive function "sits above" the other functions monitoring our thinking, choosing how to best allocate resources. Mindfulness is about living in the present and it gives us "the ability to pause before we react." When you are being mindful you are also noticing information about yourself.

When you notice that you are not doing what you should, you are being mindful. You are noticing information about how and what you are thinking. You are noticing inner signals.

"Mindfulness isn't hard, the hard part is to remember to be mindful." -- John Teasdale

Practice, you can be mindful anywhere and with anything.

"The unexamined life is not worth living" --Socrates

Danger and Rewards

The brain tries to minimize danger (away response), and maximize rewards (toward response).

The away response is stronger, faster and longer lasting than the toward response. The away response can reduce cognitive resources, making it harder to think about thinking, making you more defensive and mistakenly classify situations as threats. Trying to suppress an emotion often makes it worse and often makes other people feel uncomfortable.

Labeling an emotion, giving it a name, often reduces the emotion. The label needs to be symbolic, short and succinct.

Reappraisal

Reappraisal is a powerful method for managing increased arousal. It means that you evaluate a situation and see it from a different perspective than you first do. Four forms of reappraisal are: reinterpreting, normalizing, reordering, and repositioning.

Reinterpreting is something we do every day. When we are late for an airplane, we feel worried and hurry our steps, to avoid missing the plane. When we can see the gate and the people waiting for the plane, we automatically reinterpret the situation since we see that we have plenty of time. Nothing has changed, except our interpretation of the situation.

An example of normalization, is when we are at a new job, we may feel worried, since everything is new to us. It is easy to overreact to trivialities that otherwise wouldn't bother us. Normalization is when someone tells you, or you figure it out for yourself, that it is normal to feel worried at a new job. Everybody feels worried, it is normal! We immediately calm down. Nothing, again, has changed, except our interpretation of the situation

Reordering is a larger form of reappraisal. It involves changing the way we prioritize what is valuable to us. If we value two things, such as autonomy and responsibility, they may come in conflict. An example would be working as a member of a team where you are allowed to make independent decisions about how to do your work, allowing you to feel in control of the situation. When you are suddenly offered the job as team lead, you will lose control of the situation, since other people will be responsible for doing the work that you used to do. Your autonomy has decreased since you have to rely on other people to get the work done. You have to reappraise the situation, reorder your priorities, in order to be comfortable with this new situation.

The last form of reappraisal, repositioning, involves putting yourself in someone else's position. In order to understand why they are reacting the way they do. If someone thinks all your ideas are worthless, they obviously don't see the world the way you do. In order to understand why they feel the way they do, you have to try to put yourself in their shoes.

Perhaps they have tried the ideas, you are suggesting, and failed previously. The reason they don't want to you to try it may be in the best interest of everyone; they don't want the project to fail or, it may be simple jealousy; they don't want you to succeed with what they failed with before.

I does not matter what the reason is. By putting yourself in their position you will be in a better position to deal with the arguments when they come.

If you find it dishonest to change your view of the world, you must remember that:

"All the brain can know, it knows from inside itself." --Walter Freeman

If you recognize that all interpretations of the world are just that, interpretations your brain has made, then, having a choice about which interpretation to choose at any moment makes more sense.

People who reappraise more tend to live happier lives. One way to reappraise a situation is to think "It's not me, it's my brain!"

It is also worth noting that reappraisal uses a lot of energy and it is best done when the brain is fresh. But, reappraisal, like everything else, is something you can practice until it becomes habitual.

Expectations

Expectations are the brain paying attention to a possible reward or threat. Expectations alter the way you perceive the world. It is common to fit incoming data into expectations and to ignore data that don't fit.

Met expectations generates a small increase of dopamine. Exceeded expectations generate a large increase of dopamine. And dopamine makes you feel good.

Unmet expectations generates a large drop in dopamine level, and a strong threat response.

The dynamics of expectations can generate upward and downward spirals.

A general feeling of expecting good things generate healthy levels of dopamine and may be the neurochemical marker of feeling happy.

If your expectations are not met, try reappraising, remembering that it is your brain reacting to the dopamine levels.

Collaboration

Maslow's hierarchy of needs may have been wrong and other needs may be as important as the primary needs that he identified.

Social connections are a primary need, as vital as food and water. We know other people by experiencing their states ourselves. Safe connections with others are vital for health and for healthy collaboration. People are classified as friend or foe quickly. Foe is the default. You need to work hard at creating connections to create good collaboration. Connect to people on a human level, by sharing experiences, to create better collaboration.

In order to collaborate well with others it is a good idea to take into account the major areas that we care about socially. The can be summarized by the SCARF model, SCARF stands for Status, Certainty, Autonomy, Relatedness and Fairness.

Status, is a significant driver at work and across life experiences. Status changes affect our threat and reward circuits. People pay a lot of attention to building and protecting their status. When everyone is trying to achieve higher status, there is a decrease in relatedness. Playing against yourself increases your status without threatening others. You can decrease the status threat in others, by sharing your humanity or mistakes.

Certainty is when you feel sure about yourself, your environment, and the people around you.

Autonomy, the feeling of control, is another primary reward. Note that is the feeling of autonomy that is important, not the actual autonomy. The feeling of autonomy can be increased by letting people understand that they have choices.

Relatedness is the feeling of being part of something. The feeling of being part of a team or of a cause. The feeling to belong.

Fairness, can be a very strong drive indeed. People go to war in order to make a wrong right. Treating people fairly may increase several of the other primary social domains.

Problems and Solutions

Trying to solve problems is less effective than trying to find solutions. When solving problems we narrow in on a specific area rather than trying to creatively find a solution that we are really looking for.

When helping others to solve problems, it is often not helpful to suggest possible solutions. People don't want to be fed a solution that they are not buying into.

This can be explained in terms of the SCARF model in that it:

  • Threatens the status, since it implies that they are incompetent.
  • Threatens the autonomy, since they cannot come up with their own solution.
  • Threatens the relatedness, since it is harder to relate to someone else's solutions than to your own.

It is better to bring people to their own insights. To do this it can be helpful to ask questions that make them think about their own thinking or to think of the problem at a very high level. Some ways to do this is to ask questions about what strategies people have been thinking about for solving the problem or to ask them to summarize the problem in one sentence.

Creating Long-term Change

The brain constantly changes itself. This is called neuroplasticity. Focused attention changes the brain. Attention is lost very quickly if we feel threatened by something. To induce change try to move attention away from the perceived threat by posing good questions. Creating long-term change requires paying attention regularly to deepen the new circuits.

Don't try to influence people in a strong away state. Use elements of the SCARF model to shift people into a toward state. Practice using solution-focused questions that focus people's attention on the specific circuits you want to bring to life. Invent ways to have people pay repeated attention to new circuits.

Recommendation

Your Brain at Work is as you may tell from my notes not only about the brain at work. It is about the brain. It is a really good book and I highly recommend it to everyone!

Thursday, May 03, 2012

Rationality is Overrated

When I was about 20 years old, I worked as a janitor at a home for elderly people. I had no skills that a janitor was supposed to have. In fact I didn't even know that a janitor needed skills :)

One day I was asked to fix a clogged sink, I thought, "Sure, how hard can it be?", then I went to work. This is how I did it.

  • I examined the sink and quickly established that the problem was a clogged water trap (vattenlås).
  • I carefully removed the water trap, it was filled with filthy stinking brown water.
  • Very carefully I lifted the trap, to avoid spilling the filthy water on the floor.
  • Then, I poured the water into the sink...

I realized that I was not as smart as I thought I was. How could I do this? I was so very careful not to spill a drop and yet my stupid brain failed me big time. What was wrong with me?

After many years, and a lot of books, I think I have understood what the problem is. It is not me, it is my brain. I am a pattern matching robot, who reacts to incoming patterns in predefined ways. If there is not a pattern that matches, it chooses the closest matching pattern and that is not necessarily good.

Robots

My intention with this text is to show that we are more like machines than any of us are willing to admit. We react to patterns that we pick up through our senses. Our ability to work in a rational way is extremely limited since our rational part of the mind is extremely limited. To demonstrate this, I'll start with several examples.

Irrationality

What I mean with irrationality is, something we do without paying attention. It is something we can do without involving our conscious part of the brain.

Irrational = Unconscious = Without paying attention

Facts are useful; they give the conscious mind something to do while the emotions decide what’s true! --Dale Dauten

Most of what we do, we do without paying attention

Earphone Study

In an earphone study researchers wanted to find out how much we are affected by actions that are seemingly unrelated to our brains.

In the study a number of people were asked to test out earphones, to tell if they were comfortable.

  • The first group were told to sit without moving and listen to what was being said in the earphones.
  • The second group were told to nod their heads while listening.
  • The third group were told to shake their heads while listening.

After the test was completed the subjects were asked about what the person had been talking about in the earphones. The result was statistically significant: The group that were nodding were more positive than the group who sat without moving and, they were more positive than the group who had been shaking their head. The opinion of the people were affected by how they were moving their head while they were listening!

How rational is that?

Biking

How do you ride a bicycle? You grab a hold on the handlebars, push off with your foot to get some initial speed, keep you balance by moving the front wheel in the direction in which the bike is falling. When the bike is falling the other way you turn the wheel that way instead, and so on.

Needless to say this way of teaching someone to ride a bike will not work. We can ride bikes, but we don't know how we do it. And even if we could do it the way I described it, our conscious minds are too slow to be of any use. Try riding a bike with a wheel that turns the opposite way, when you turn the handlebars. It is very, very difficult.

Decisions

Imagine that you are standing on a trampoline, preparing to jump into the pool. Half a second before you jump, your unconscious mind has started its activity that will eventually make you jump. Half a second! Conscious decisions are initiated unconsiously!

Cocktail Party

Imagine you are at a cocktail party, having a conversation with some friends. Then, suddenly, you hear someone mention your name somewhere around you. Your conscious attention is moved to the other conversation. You may not even hear what your friends are talking about anymore, because your unconscious mind has scanned the environment around you and now you want to know what they are saying about you.

Is this a rational way to act?

Snap

Our unconscious mind is exceptional at making snap decisions. It does it all the time. If we meet a person in the street we, unconsciously, scan them to see if they are a threat, if they look good, etc. If there is something that is not "normal" about them we are immediately aware of it.

Sleep

When we are sleeping, our brains repeat the thoughts we have thought during the day. In a study two groups of people were tasked with first learning some new skills, then solve creative problems based on what they had learned. The first group learned the skills and started applying them right away. The second group learned the skills, had a nights sleep, and then applied their skills to the problems. The group that was allowed to "sleep on it", were 70% more effective than the first group.

Beauty

You may have heard the song by Skunk Anansie, called "Just because you feel good", some of the lyrics go like this.

Just because you look good, doesn't make it right! -- Skunk Anansie

It is a good song, but unfortunately the conclusion is wrong. We are, naturally, affected by beauty. We cannot do anything about it. A good example of this is the justice system, who ought to be immune to this. Beautiful people get, significantly, lower sentences than ugly people.

Our irrational mind, doesn't have any problem discriminating people.

Tumour

This is a story about a man who started to like child pornography. After he had made a pass at his wife's sisters daughter, his life went to pieces. He was divorced. But he went through a medical examination that showed that he had a tumour in his brain... When they removed the tumour his mind returned to normal. Of course, it was too late to do anything about his broken marriage, but still, good for him. But there is an epilogue to this story. The man started to feel the urge for child pornography again, and went to see his doctor. The tumour had returned and once removed, the behavior of the man returned to his "normal" behavior.

Dreyfuss Model of Skills Acquisition

In the Dreyfuss Model of Skills Acquisition an expert is defined as someone who has "intuitive grasp of situations based on deep, tacit understanding". Intuitive! In order to become experts we have to let go of our need to be rational and trust our intuition. Being rational is too slow.

Einstein

Einstein was an extremely intuitive scientist. He had trouble communicating his ideas to other scientists since he was not thinking in a language that he was able to easily communicate to others.

I only need symbols to communicate. -- Albert Einstein

Optical Illusions

What square is lighter? "A" or "B". The obvious answer is of course incorrect. They both have the same color as can be seen in the second picture. Just as easily as we are fooled by this optical illusion our rational mind is fooled all the time when our unconscious filters remove facts from our every sensation of "reality".

This is a good thing. Our rational mind couldn't cope with the overflow of information it would otherwise experience.

Reflective Robots

So as you can see, we are pattern matching robots, who react to patterns in predefined ways. But that is not the whole truth. The cool part is that we are reflective robots and this is where our rationality comes into play.

Rationality

My definition of rationality is, of course, similar, but opposite, to my definition of irrationality. Rational is something we do consciously, something we pay attention to. But, rationality is extremely limited.

Time

Our rationality is able to deal with time. While our unconscious lives in the present our conscious is able to move back and forth through time at our whim.

Planning

Being able to deal with time is essential for planning. What is the use of planning if there is no tomorrow? How can we plan for the future if we cannot rely on experience from the past?

Focus

The conscious mind can focus, to concentrate the entire conscious mind and some parts of the unconscious mind.

Discipline

Related to focus is discipline. This is also something that the conscious mind excels at. While our irrational mind, simply reacts to incoming patterns, our rational mind is able to keep the mind in check in order to force our rigid, irrational mind to learn new patterns.

Choices

The conscious mind can make choices. And, every time we make a choice our mind changes and we become more likely to make that choice again. We make choices all the time, even when we don't.

Every Read is a Write

Andy Hunt put it very well in his book, Pragmatic Thinking and Learning. He said that when it comes to the brain "Every read is a write". What this means is that every time we think a thought, that thought becomes easier to think. The patterns gets even more established. It is a thought worth thinking more than once. Every time we think something, that thought becomes easier to think!

What do you want to think?

11 000 000 Bits

Our senses take in around 11 million bits every second. Most of it, around 10 million, comes through our vision. Our hearing picks up almost 1 million bits and the rest comes through our other senses.

Less than 50 bits

At the same time our rational mind is able to process less then 50 bits, some say less than 16... The rest of the information is filtered out by our unconscious mind in order to protect our poor, limited, slow conscious mind from overflowing.

Unconscious vs. Conscious

Unconscious Conscious
Parallel Sequential
Automatic Controllable
Fast Slow
Rigid Flexible
Now Time aware
Near infinite Very limited

So What?

So, I have established, we are robots, and we can affect our behaviors in very limited ways. So what? What can we do with this information.

Alfred Whitehead

Civilization advances by extending the number of important operations which we can perform without thinking of them. --Alfred Whitehead

This is not only true for civilizations it is true for humans too.

We can become whatever we want.

Even though our consciousness is extremely limited we can become whatever we want. We do this through automation. We create habits.

Habits or routines are often taken to be boring. You have probably heard the saying, "It is just routine, anyone can do it!" You have probably said it yourself. But this is hogwash! Routines are vital to our behavior. Without our automatic behavior we, as a species, would be extinct long ago. Another way to think of habits is:

Outsourcing to our unconscious!

The more we can outsource the behavior we want, the more we will be able to focus our attention on other things. But creating habits take time, psychologists say that it takes 21 days.

Talent is Overrated

The Spanish violinist, Pablo Sarasate, was declared a genius by the press, this is how he responded:

“A genius! For 37 years I’ve practiced fourteen hours a day, and now they call me a genius!” –- Pablo Sarasate

He took it as an insult. Becoming who we want to be takes time and effort and practice.

Practice

Our conscious mind is able to see the benefits of learning something well. It is able to discipline us to practice boring repetitions, over and over, until they can be done unconsciously.

Tiger Woods started playing golf when he was two years old, and has probably practiced more than any other golf player on the tour.

Try!

Jill Bolte Taylor is a brain scientist who had a stroke. She had the unique competence to be able to study the stroke while it happened. When she was recovering she had to re-learn habits such as walking, reading and talking. She said:

Try! When we try to do something, we tell the brain that we value this connection. The more we try, the stronger the connection becomes. The stronger it becomes, the easier it gets. -- Jill Bolte Taylor

Learning Curve

The normal learning curve, consists of plateaus of knowledge where we seem to learn nothing new. Then after a long time of practice a small bump in knowledge occurs, and then we are stuck on a new plateau. The small bumps are signs that the knowledge has become second nature to us. Automatic!

Deliberate Practice

What separates most experts from the not-so-greats is something that is called deliberate practice. A deliberate practice task has four parts.

Designed

The task to practice should be specifically designed for you and your skill level. And it should be set up with a goal to improve in one specific area.

Small

The task should be small and specific enough for you to complete it and receive feedback in a short time frame.

Demanding

The task should be hard. If it is not hard it will not give as much as it will if it is designed to be just over your current abilities.

It is only human nature to want to practice what we already know, since it is a hell of a lot less work, and a hell of a lot more fun! --Sam Snead

Observed

It is important to observe yourself while practicing. This should be done before, during and after the task.

Mentor

Sometimes we need help in observing ourselves. It is easy to lose focus and start falling back into old habits, even during practice. Having a mentor or coach that can help observe and correct you can be very helpful. This does not have to be an expert as long as you can describe what you want them to do.

Loosing Bad Habits

The good thing about good habits is that they are automatic and can be performed without conscious thought.

The bad thing about bad habits is that they are automatic and performed without conscious thought.

Since we are not aware of our bad habits, it is very difficult to lose them. Thus, if someone criticizes us for something, we should take this as a kind gesture. They are helping us to notice our bad habits. And, once they are noticed we can do something about them, such as replacing them with something else. It is easier to replace a bad habit with a good one, than to just stop doing the bad habit.

Hormones

Some bad habits are supported by our hormones. When we get angry at someone, adrenaline is pumped out into our body. This will make us more hostile and make it more difficult for us to act the way we would like to.

Spirals

If we react while our hormones are keeping us on edge, we may react more strongly than we would wish to act. This can lead us into a downward spiral where our anger feeds our behavior, which in turn makes us more angry...

Wait

The solution to this is simple. Wait! This is taught to our children in kindergarten. They are told to count to ten before retaliating when something has annoyed them. We should do this too. Jill Bolte Taylor writes in her book, that it takes our body 90 seconds to wash out the hormones. If we can just wait for a minute and a half, we may respond in a more thoughtful way.

What Habits Do You Want?

When deciding on what habits you want to cultivate, keep the wise words of Ralph Waldo Emerson in mind.

A foolish consistency is the hobgoblin of little minds. -- Ralph Waldo Emerson

Just because we have done something in the past does not mean that we have to do it in the future. Just because people expect us to do something doesn't mean that we have to do it at all!

Happiness

So, what habits do I cultivate. I cultivate habits that make me happy! Not only because it feels good to be happy, although that is a large part of it.

Authentic Happiness

In his book, Authentic Happiness, Martin Seligman studies what happiness does with people, especially creative people. Here are some of his conclusions.

Happy people perform better!
.

People that are in a good mood produces much better results.

Increasing happiness increases the likelihood of insight!

And insight is the key to creativity.

Flow

Flow is the feeling you get when you do something that you are good at. When you are performing on the limit of your ability. You lose the concept of time and you are living in the moment. The conscious and unconscious are one. We are whole!

Flow is my favorite state to be in and I believe that it can be achieved not only when we are performing complex tasks, but also when we are doing much more mundane tasks.

As long as we want to do what we are doing, we can immerse ourselves in the task and in the moment and find flow in anything. I think this is the key to living a happy life, finding flow in anything.

Stress

When writing about flow, I also want to write about stress. Stress is the opposite of flow. Instead of doing what we want, right here, right now, we want to be somewhere else. We want to be done. We don't want to do! This is fatal. It is the end of creativity.

In a stress study with clerical students, who were to become priests, the following happened.

Clerical Students

The students were at a lecture, where they were discussing what was the most important trait of a priest. They all agreed that compassion, and helping those in need, was the most important trait of a Christian priest. Towards the end of the lecture, the teacher interrupted and said. "Oh! I forgot, you are supposed to meet the bishop at his office in five minutes. You must hurry!"

The students hurried out of the classroom and started walking, at fast pace, towards the bishops' office.

Along the road a homeless man who looked to be suffering was planted by the researchers. What do you think happened? Right! Most of the students, who had been told and all agreed on, that helping people in need is the most important trait of a Christian priest, ignored the man in need.

The stress produced by being late to the meeting made them forget or ignore their most important trait!

This is what stress can do to us, and it is not pretty!

Be kind

Back on the happiness track. One simple way to become happier is to be kind to others. Studies show that when you are nice to someone.

  • You feel happy.
  • The person being helped feels happy.
  • And, everyone who witnesses the act of kindness, feel happy too.

A special form of kindness is being polite! If you thank someone who helps you they will feel good about helping you and be more likely to help you again. So do what your mother told you. Say "Thank You"! Say "Please"!

Beauty

Beauty is in the eye of the beholder, as we all have different tastes. Surrounding yourself with beautiful things, that you care about will make you happier. If the code you are working with is beautiful, it will be much more enjoyable for everyone who has to touch it.

(define y-combinator
  (lambda (f)
    ((lambda (x) 
       (f (lambda (arg) ((x x) arg))))
     (lambda (x) 
       (f (lambda (arg) ((x x) arg)))))))
The Y-Combinator, one of the most beautiful functions in the world!

Death

Another tip for finding out what habits you should create is to think about death. Death has a way of forcing you to think clearly. What would you do if you died tomorrow?

And, remember it is about people.

No one ever said on their deathbed, "Gee I wish I spent more time in front of the computer".

We are social animals, and we thrive in the company of people we like.

Enthusiasm

Nothing great was ever accomplished without enthusiasm! -- Ralph Waldo Emerson

Why waste time doing something you are not enthusiastic about. Either do something else or, become enthusiastic about it. If I only take the time to dig into something, I find that almost everything is interesting.

Belief

What is the difference between fantasy and reality? Belief! -- David Hume

In our brain, the only difference between what we know and what we hope is belief. If we are sure that something is in a certain way, it is that way. No matter if it is true or not. Believe in yourself!

Do It!

Starting something is half the battle.

Once you get going it is easy to keep going.

We Are What We Repeatedly Do

We are what we repeatedly do. -- Aristotle

We can talk all we want, but at the end of the day, we are our habits. Good habits makes us happy and when we are happy everything becomes easier.

Resources

If you found this interesting here are some books that will go much deeper into the topic (affiliate links):