Pickaxe Book Chapter 01

I have finished the first chapter of the Pickaxe book. The first chapter was no big deal for me. It was about getting and installing Ruby and a few basic commands.

I have used rvm to install Ruby on my Ubuntu laptop, and Rails Installer to install Ruby and Rails on my Windows laptop.

Design Pattern Notes

On 2004-06-24, Alan Shalloway of Net Objectives gave a talk on design patterns at my then-employer. Here are my notes.

2004-06-24 - Patterns
Net Objectives -> Alan Shalloway, author of "Design Patterns Explained"
Boeing: Great internal education
Gang Of Four: Difficult book to understand
GOF: Using terms differently
AS: Looking at patterns differently, will also look at analysis

Adding functionality:
Where is the problem? Writing new code, integrating it into the system
Integrating is more difficult
Must accomodate change (not predict change):
identify special cases, abstract out commonalities, containing no more than one variation per class
Design from context: big picture to small, not small to big

Patterns can be architectural, design, idiomatic (language-specific)
Patterns describe relationships between entities (objects) in your problem domain,
handling variation and new ways of using inheritance come from inheritance

Patterns work on many levels: analysis/motivation, design, implementation
Think of them as "software patterns" - gives some "why" as well as "what"

use pre-existing solutions
some patterns deal with modifiability
design is not synthesis, but differentiation

3 perspctives:
- conceptual: what you want, requirements
- specification: interfaces of classes, how objects "talk" to each other
- implementation: code itself

Mop, broom and sponge: same and different
as specific object: different
as concept: all cleaning objects

abstract classes: concepts, never instantiated, define interfaces

person -> clean -> utensil interface (mop, broom, sponge)

encapsulation: ususally thought of as data hiding
can think of it as hiding classes -> derived classes
implementation hiding, type hiding, data hiding

Objects at different levels:
implementation: data with methods
specification: objects are contracts they implement
conceptual: entities with responsibilities

do not use inheritance badly
lots of switches (coupled) or inheritance
switches are coupled: if you must change one you have to change them all
sales tax: different class for each country

guidelines:
design to interfaces (interfaces in general sense)
favor object aggregation over class inheritance

consider what varies in design, encapsultate the concept that varies
- find what varies and encapsulate it in a class of its own
- contain this class in another class

use cases: "writing effective use cases"

cohesion: focusing on one thing
coupling: dependence of different actions

Commonality/variability analysis
From Jim Coplien - Multi-Paradigm Programming for C++
Thesis online
abstract: emphasize what is common, or ignore what is different
find commonalities relevant to problem domain

challenges in finging commonalities: we are data-centric,
objects usually thought of as "intelligent data", instead of as behaviors
variability: makes sense only in a given commonality
frame of reference
it is a variation of commonality

commonality: gives architecture longevity
variability: makes it fit for use

commonality -> perspective (conceptual), specification -> abstract class, interfaces
variability -> implementation, specification -> concrete classes

patterns are about relationships

Matrix for CVA

             case 1 case 2 case 3
behavior 1   implementations for behavior 1
behavior 2   implementations for behavior 2

Look at patterns in terms of their motivations, not just what they do
switches are okay if they are in one place
can use abstract factory to instantiate the implementations - separates construction from use
Joshua Bloch: Effective Java

www.netobjectives.com/dpe2nd - go to seminars too
Timeless Way of Being: Alexander
ezine: info @ netobjectives.com - subscribe

				

Code Academy Notes Week 1

Here are my notes from Code Academy week 1.

2012-01-12_08.14.41
Almost everything is lower-case
Methods: def method_name to name

Lists in Ruby
Very important to be good with lists.

landmarks = [ "Wrigley Field", "Millenium Park", "John Hancock Center" ]

This is an array. You do not specify the size.
Iterate through array:

landmarks.each do |name|
  print_landmark name, "100"
end

irb is “Interactive Ruby”
for a variable or a class, you can type “x.methods” in irb to get all the methods you can call on it
to print them alphabetically, x.methods.sort
to get out of irb, type “exit”
An array is a list of single elements
A list of pairs is a hash:

landmarks = { "United Center" => "90",
              "Wrigley Field" => "40",
              "Millenium Park" => "0",
              "John Hancock Center" => "15" }

Braces instead of brackets
Iterate through hash:

landmarks.each do |name, fee|
  print_landmark name, fee
end

Any methods created in a variable are local to the method. They only have meaning within the method

CSS

Back to Ruby: String interpolation, use the pound and braces:

puts "#{landmark_name} --- #{cost_of_admission}"

Interpolation is a bit faster

To set the variable, single equal sign:

x = 10

To compare the variable, double equal sign:

x == 10

Ruby classes:

attr_accessor :name_of_symbol

give it a symbol (colon and some name)

Variables: @name, @address, @cost: Private variables to that object
attr_reader will allow you to set it only at initialization, and only read thereafter
You could make a variable @api_key to be private, just don’t provide an attr_accessor
In pure Ruby, there is no way to ensure that @cost is always greater than 0. I would have to write my own methods for that.

 

Ruby Plans

One of my plans outside of Code Academy is to go through the Ruby “Pickaxe Book” by Dave Thomas. Someone gave me a copy of the edition for Ruby 1.9. I will write a short post about each chapter as I finish them.

Image from Wikipedia

 

Code Academy Week 2

Code AcademyI have been through my second week at Code Academy.

We started using Rails and some of the Rails commands. So far it seems pretty nice. It is a lot easier than the Java frameworks I have worked with.

I went to a lecture on  HTML5/CSS by Shay Howe. I may not make to every one, put I plan on going to as many of these as I can. I also went to a lecture on the Lean Startup idea.

I went to the Chicago Ruby hack night. The problem was Scrabble. I got the first step of it done. I should rewrite it with rspec. I was not writing tests first. I also am having trouble remembering how to iterate over collections in Ruby.

On Friday I went to the 8th Light University lecture. It was on cryptography. I also met with my mentor. We went over rspec and cucumber. My brain was overloaded after a couple of hours. I got the concepts, but he threw a lot of details at me. Another Code Academy person was there as well. He owes me an hour with his mentor.

I also spoke with Colin Jones, who is working on a project to improve the repl in Clojure.

Image from Code Academy

Last Lombok Refactoring

This is the last refactoring example of deadlocked Java code using the “synchronized” keyword.

This example is from a site called Rose India.

I was not able to really use Lombok for this example. The classes that deadlocked extended Thread, and the only method in those classes was the run() method. I did not know if annotating run() with the Lombok annotation would work. The method run() was not marked with the “synchronized” method in the original. Instead there were two synchronized blocks in the run() method. The two classes were using the same String objects to lock, which is why there was a deadlock.

So I decided to do by hand what Lombok does behind the screens. I created a private final object in each method and used those for one of the locks. Just as in the other examples, the deadlock was broken.

Here is the original;

package fromroseindia;

// from http://www.roseindia.net/javatutorials/deadlocksinjava.shtml

public class DeadLockDemo extends Thread {
    public static String str1 = "str1";
    public static String str2 = "str2";

    public static void main( String[] a ) {
        Thread myThread = new MyThread();
        Thread yourThread = new YourThread();

        myThread.start();
        yourThread.start();
        System.out.println( "At the end of main" );
    } // end method main

    private static class MyThread extends Thread {
        public void run() {
            synchronized ( str1 ) {
                System.out.println( "MyThread Holds lock on object str1" );
                try {
                    Thread.sleep( 10 );
                } catch ( InterruptedException e ) {
                    e.printStackTrace();
                }

                System.out.println( "MyThread waiting for lock on object str2" );
                synchronized ( str2 ) {
                    System.out.println( "MyThread Holds lock on objects str1, str2" );
                }
            }
            System.out.println( "At the end of MyThread.run" );
        } // end method run
    } // end class MyThread

    private static class YourThread extends Thread {
        public void run() {
            synchronized ( str2 ) {
                System.out.println( "YourThread Holds lock on object str2" );
                try {
                Thread.sleep( 10 );
                } catch ( InterruptedException e ) {
                    e.printStackTrace();
                }
                System.out.println( "YourThread waiting for lock on object str1" );
                synchronized ( str1 ) {
                    System.out.println( "YourThread Holds lock on objects str1, str2" );
                }
            }
            System.out.println( "At the end of YourThread.run" );
        } // end method run
    } // end class YourThread

} // end class DeadLockDemo

Here is the output of the original:

MyThread Holds lock on object str1
YourThread Holds lock on object str2
At the end of main
MyThread waiting for lock on object str2
YourThread waiting for lock on object str1

Here is the refactored version:

package fromroseindia;

// refactored version of http://www.roseindia.net/javatutorials/deadlocksinjava.shtml

import java.util.UUID;
import lombok.Synchronized;

public class DeadLockDemoLombok {

    public static String str1 = "str1";
    public static String str2 = "str2";

    public static void main( String[] a ) {
        Thread myThread   = new MyThreadLombok();
        Thread yourThread = new YourThreadLombok();

        myThread.start();
        yourThread.start();
        System.out.println( "At the end of main" );
    } // end method main

    private static class MyThreadLombok extends Thread {
        private final Object object1 = new Object();

        public void run() {
            synchronized ( object1 ) {

                System.out.println( "MyThread Holds lock on object object1" );
                try {
                    Thread.sleep( 10 );
                } catch ( InterruptedException e ) {
                    e.printStackTrace();
                }

                System.out.println( "MyThread waiting for lock on object str2" );
                synchronized ( str2 ) {
                    System.out.println( "MyThread Holds lock on objects object1, str2" );
                }
            } // synchronized ( object1 )
            System.out.println( "At the end of MyThreadLombok.run" );
        } // end method run
    } // end class MyThread

    private static class YourThreadLombok extends Thread {
        private final Object object2 = new Object();

        public void run() {
            synchronized ( object2 ) {
                System.out.println( "YourThread Holds lock on object object2" );
                try {
                    Thread.sleep( 10 );
                } catch ( InterruptedException e ) {
                    e.printStackTrace();
                }
                System.out.println( "YourThread waiting for lock on object str1" );
                synchronized ( str1 ) {
                    System.out.println( "YourThread Holds lock on objects str1, object2" );
                }
            } // synchronized ( object2 )
            System.out.println( "At the end of YourThreadLombok.run" );
        } // end method run
    } // end class YourThread

} // end class DeadLockDemoLombok

Here is the output of the refactored version:

At the end of main
YourThread Holds lock on object object2
MyThread Holds lock on object object1
YourThread waiting for lock on object str1
YourThread Holds lock on objects str1, object2
At the end of YourThreadLombok.run
MyThread waiting for lock on object str2
MyThread Holds lock on objects object1, str2
At the end of MyThreadLombok.run

 

Image from Wikipedia page for the Indonesian province of Central Java

Third Lombok Synchronized Example

East JavaHere is another installment of my exploration into concurrency in Java. I have written about finding the Lombok library which uses annotations to reduce boilerplate in Java code.

One of the annotations provided by Lombok is @Synchronized. It is to replace the “synchronized” keyword and prevent some of the problems that can come with using the “synchronized” keyword. There are other annotations available via Lombok, but I have not looked at them.

Here is the third example of a program with a deadlock using the “synchronized” keyword that I refactored with Lombok. I got this example from the Java 2S site.

For this one I have also included the output of each of the programs.

Here is the program:

package newpackage2;

// from http://www.java2s.com/Code/Java/Threads/Threaddeadlock.htm

public class Deadlock extends Object {
    private String objID;

    public Deadlock( String id ) {
        objID = id;
    }

    public synchronized void checkOther( Deadlock other ) {
        print( "entering checkOther()" );

        try {
          Thread.sleep( 2000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        print( "invoke 'other.action()'" );
        other.action();

        print( "leaving checkOther()" );
    }

    public synchronized void action() {
        print( "entering action()" );

        // simulate some work here
        try {
            Thread.sleep( 500 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        print( "leaving action()" );
    }

    public void print( String msg ) {
        threadPrint( "objID=" + objID + " - " + msg );
    }

    public static void threadPrint( String msg ) {
        String threadName = Thread.currentThread().getName();
        System.out.println( threadName + ": " + msg );
    }

    public static void main( String[] args ) {
        System.out.println( "Starting Deadlock" );
        final Deadlock obj1 = new Deadlock( "Thread 1" );
        final Deadlock obj2 = new Deadlock( "Thread 2" );

        Runnable runA = new Runnable() {
            public void run() {
                obj1.checkOther( obj2 );
            }
        };

        Thread thread = new Thread( runA, "A" );
        thread.start();

        try {
            Thread.sleep( 200 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        Runnable runB = new Runnable() {
            public void run() {
                obj2.checkOther( obj1 );
            }
        };

        Thread threadB = new Thread( runB, "B" );
        threadB.start();

        try {
            Thread.sleep( 5000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "finished sleeping" );

        threadPrint( "about to interrupt() threadA" );
        thread.interrupt();

        try {
            Thread.sleep( 1000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "about to interrupt() threadB" );
        threadB.interrupt();

        try {
            Thread.sleep( 1000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "did that break the deadlock?" );
        System.out.println( "Ending method main" );
    } // end method main
} // end class

Here is its output:

Starting Deadlock
A: objID=Thread 1 - entering checkOther()
B: objID=Thread 2 - entering checkOther()
A: objID=Thread 1 - invoke 'other.action()'
B: objID=Thread 2 - invoke 'other.action()'
main: finished sleeping
main: about to interrupt() threadA
main: about to interrupt() threadB
main: did that break the deadlock?
Ending method main

There is a line that says “Ending method main”, but it does not end unless you kill the program.

Here is the program refactored with Lombok:

package newpackage2;

// example from http://www.java2s.com/Code/Java/Threads/Threaddeadlock.htm
// refactored to use Lombok

import java.util.UUID;
import lombok.Synchronized;

public class DeadlockLombok  extends Object {

    private String objID;
    private final Object someObject = new Object();

    public DeadlockLombok( String id ) {
        objID = id;
    }

    // public synchronized void checkOther(DeadlockLombok other) {
    @Synchronized public void checkOther( DeadlockLombok other ) {
        print( "entering checkOther()" );

        try {
          Thread.sleep( 2000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        print( "invoke 'other.action()'" );
        other.action();

        print( "leaving checkOther()" );
    }

    // @Synchronized public void action() { // does not work
    @Synchronized( "someObject" ) public void action() { // works
    // public synchronized void action() {
        print( "entering action()" );

        // simulate some work here
        try {
            Thread.sleep( 500 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        print( "leaving action()" );
    }

    public void print( String msg ) {
        threadPrint( "objID=" + objID + " - " + msg );
    }

    public static void threadPrint( String msg ) {
        String threadName = Thread.currentThread().getName();
        System.out.println( threadName + ": " + msg );
    }

    public static void main( String[] args ) {
        System.out.println( "Starting DeadlockLombok" );
        final DeadlockLombok obj1 = new DeadlockLombok( "Thread 1" );
        final DeadlockLombok obj2 = new DeadlockLombok( "Thread 2" );

        Runnable runA = new Runnable() {
            public void run() {
                obj1.checkOther( obj2 );
            }
        };

        Thread thread = new Thread( runA, "A" );
        thread.start();

        try {
            Thread.sleep( 200 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        Runnable runB = new Runnable() {
            public void run() {
                obj2.checkOther( obj1 );
            }
        };

        Thread threadB = new Thread( runB, "B" );
        threadB.start();

        try {
            Thread.sleep( 5000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "finished sleeping" );

        threadPrint( "about to interrupt() threadA" );
        thread.interrupt();

        try {
            Thread.sleep( 1000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "about to interrupt() threadB" );
        threadB.interrupt();

        try {
            Thread.sleep( 1000 );
        } catch ( InterruptedException x ) {
            x.printStackTrace();
        }

        threadPrint( "did that break the deadlock?" );
        System.out.println( "End method main" );
    } // end method main

} // end class

Here is the output of the refactored program:

Starting DeadlockLombok
A: objID=Thread 1 - entering checkOther()
B: objID=Thread 2 - entering checkOther()
A: objID=Thread 1 - invoke 'other.action()'
A: objID=Thread 2 - entering action()
B: objID=Thread 2 - invoke 'other.action()'
B: objID=Thread 1 - entering action()
A: objID=Thread 2 - leaving action()
A: objID=Thread 1 - leaving checkOther()
B: objID=Thread 1 - leaving action()
B: objID=Thread 2 - leaving checkOther()
main: finished sleeping
main: about to interrupt() threadA
main: about to interrupt() threadB
main: did that break the deadlock?
End method main

The image is the coat of arms of the Indonesian province of East Java

First Week At Code Academy

Code AcademyHere is my late blog post about my first week at Code Academy.

First off, getting up that early is pretty tough. I am trying to become a morning person. So far I am doing okay.

We use pair programming in class, and so far I have had a different partner each time. My partner on Thursday knew little about programming. A couple of things mentioned in class were brand new to him. I tried to explain a few things to him, but I think I may have made him more confused.

I also read one of the recommended books: Apprenticeship Patterns: Guidance for the Aspiring Software Craftsman by Dave Hoover and Adewale Oshineye. It is available online for free. I do not know who Adewale Oshineye is. He is in London now, so I will probably never meet him. However, I have met the other author: Dave Hoover is a lead developer at Groupon here in Chicago. He was a lead developer at a consulting firm here in Chicago called Obtiva which was bought by Groupon. He runs the weekly Geekfest at Groupon (which I might not get to for a while since I am in the Tuesday-Thursday class). He is also a mentor at Code Academy.

The book is full of techniques and strategies for people who are getting into software, as well as people like me who are going from one language to another. I think it was intended for people coming into software, but the patterns apply for all software developers. I read through it in a few sittings in a couple of days. It was probably intended to be read slowly, but a lot of stuff will be thrown at us in Code Academy, so I wanted to get through it. Plus I can always re-read it. It has advice that I think will still be good as long as there is software. Until the moon turns red and the screens turn blue.

It helped shed some light on the software craftsmanship movement as well. I have been seeing people referring to themselves in blogs and profiles as software craftsman and I have seen references to apprentices and apprenticeships. It turns out this movement started about ten years ago and has been gaining momentum ever since. I only became aware of it a little over a year ago. I guess that is what happens when you work for a large multinational.

The only beef is that some of the links are out of date. I got a few “Page Not Found” messages for a few of them.

One neat thing is that I have met quite a few people mentioned and quoted in this book, including Dave Hoover.

Image from Code Academy

Second Lombok Synchronized Example

West JavaHere is the second example of a program that deadlocks, with an example that I refactored using the @Synchronized annotation from Project Lombok.

This example was posted on one of the LinkedIn groups in which I first started asking about concurrency using the synchronized keyword. The basic idea to prevent deadlock is to mark the methods with the @Synchronized annotation. For one of them you should create a private, final object, and use the name of that object as the element for that annotation. For the other method that deadlocks I just use the annotation without an element.

Here is the original that was posted:

package fromlinkedin;

// posted on a LinkedIn group discussion

import java.util.UUID;

class A {

    private String uuid = UUID.randomUUID().toString();

    synchronized void doA() {
        System.out.println( "In doA for " + uuid );
    }

    synchronized void doB( A another ) {
        doA();
        another.doA();
    }

    public static void main( String[] args ) {
        System.out.println( "starting main" );
        final A a1 = new A();
        final A a2 = new A();
        Thread second = new Thread() {
            public void run() {
                a1.doB( a2 );
            }
        };
        second.start();
        a2.doB( a1 );
        System.out.println( "At end of main" );
    } // end method main
} // end class

Here is the version with the Lombok refactoring:

package fromlinkedin;

// Lombok-ed version of a class posted in a LinkedIn group discussion

import java.util.UUID;
import lombok.Synchronized;

class LombokA {
    private final Object objID2 = new Object();
    private String uuid = UUID.randomUUID().toString();

    // synchronized void doA(){
    @Synchronized void doA() {
        System.out.println( "In doA for " + uuid );
    }

    // synchronized void doB( LombokA another ) {
    @Synchronized( "objID2" ) void doB( LombokA another ) {
        System.out.println( "objID2.hashCode(): " + objID2.hashCode() );
        doA();
        another.doA();
    }

    public static void main( String[] args ) {
        System.out.println( "starting main" );
        final LombokA a1 = new LombokA();
        final LombokA a2 = new LombokA();
        Thread second = new Thread(){
            public void run() {
                a1.doB( a2 );
            }
        };
        second.start();
        a2.doB( a1 );
        System.out.println( "At end of main" );
    } // end method main
} // end class

I have a couple more examples before I get to my notes from No Fluff Just Stuff.

 

The picture is from the Wikipedia page for the Indonesian province of West Java.

 

 

First Lombok Synchronized Example

JakartaI found some examples of Java programs that become deadlocked due to their incorrect use of the “synchronized” keyword. I decided to try to get them to work using the @Synchronized annotation provided by Project Lombok.

First, here is the example from the Really Big Tutorial.

package really.big.tutorial;

// from Really Big Tutorial:
// http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

/**
 *
 * @author ericm
 */
public class Deadlock {

    static class Friend {
        private final String name;
        public Friend( String name ) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow( Friend bower ) {
            System.out.format("%s: %s has bowed to me!%n",
                this.name, bower.getName() );
            bower.bowBack( this );
        }
        public synchronized void bowBack( Friend bower ) {
            System.out.format("%s: %s has bowed back to me!%n",
                this.name, bower.getName() );
        }
    } // end class Friend

    public static void main( String[] args ) {
        final Friend alphonse = new Friend( "Alphonse" );
        final Friend gaston = new Friend( "Gaston" );
        new Thread( new Runnable() {
            public void run() { alphonse.bow( gaston ); }
        }).start();
        new Thread( new Runnable() {
            public void run() { gaston.bow( alphonse ); }
        }).start();
        System.out.println( "At the end of main" );
    } // end method main

} // end class Deadlock

 

Here is the same program with Lombok:

package really.big.tutorial;

// Lombok-ed refactoring of deadlock example from Really Big Tutorial:
// http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

import java.util.UUID;
import lombok.Synchronized;

public class DeadlockLombok {

    static class Friend {
        private final Object readLock = new Object();
        private final Object readLock2 = new Object();
        private final String name;
        public Friend( String name ) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }

        @Synchronized( "readLock" ) public  void bow( Friend bower ) {
            System.out.format( "%s: %s has bowed to me!%n",
                    this.name, bower.getName() );
            bower.bowBack( this );
        }

        // either one works
        // @Synchronized( "readLock2" ) public void bowBack( Friend bower ) {
        @Synchronized public void bowBack( Friend bower ) {
            System.out.format("%s: %s has bowed back to me!%n",
                    this.name, bower.getName() );
        }
    } // end class Friend

    public static void main( String[] args ) {
        final Friend alphonse = new Friend( "Alphonse" );
        final Friend gaston = new Friend( "Gaston" );
        new Thread(new Runnable() {
            public void run() { alphonse.bow( gaston ); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow( alphonse ); }
        }).start();

        System.out.println( "At the end of main" );
    } // end method main

} // end class DeadlockLombok

I will have a few more examples over the next few days.

Image from the Wikipedia page for Jakarta, a province in Indonesia. With Java, the name is usually based on coffee or Indonesia