Analytics

Sunday, September 30, 2012

Team Geek Book Review

Team Geek: A Software Developer's Guide to Working Well with Others by Brian W. Fitzpatrick and Ben Collins-Sussman, is a new book published in July 2012. It is written by two Engineers who are thought leaders within Google. They also heavily contributed and led the open source Subversion SVN) project. At the heart of the book is a central theme: Humility, Respect, and Trust (HRT).

The book focuses on the social aspect of software development, team culture, and personal interactions. Although it surrounds a technical field, the book does not dive into any technical jargon. There is no elaboration on the merits of elegant design patterns or database bottle neck optimizations. Through simple stories and anecdotes, the authors mentor the reader through the obstacles of the IT office place. From hairy pointed bosses, to the perfectionist, to the ego maniac, the authors have encountered a variety of situations and offer the reader practical advice. 

Sunday, August 12, 2012

Groovy Closures Do Not Have Access to Private Methods in a Super Class

Recently I came upon a groovy oddity. (At least it is perceived by me to be an oddity). Closures in a groovy class do not have access to a private method if that method is defined in the superclass. This seems odd paired against the fact that regular methods in a super class can access private method defined in the super class

Background

Groovy closures have the same scope access to class member variables and methods as a regular groovy method. In other words, closures are bound to variables in the scope they are defined. See the codehaus link for the official documentation:

http://groovy.codehaus.org/Closures

This implies that a closure will play by the rules of Object Orientation in the Java language. However, I found that closures do not have access to private methods that are defined in a super class.

The best way to demonstrate is through a short example from Grails. I have used TDD for the example. Note this is a dummy case with no business purpose. Later on I will offer a more reasonable scenario in the business context where I encountered this scenario.

Sunday, May 20, 2012

Grails Dynamic Dropdown

Recently I had a UI requirement where a customer wanted to select values from two separate dropdowns. The value of the first dropdown essentially filtered the values for the second dropdown. Given the financial projects we support are not heavy on UI requirements, I had to do some initial learning and experimentation to yield a good implementation. This blog entry details the how to implement dynamic dropdowns in Grails with ajax and minimal JavaScript.

Example Problem

A contrived for dynamic dropdowns can be described below:

A user would like to select a sports team for a city. The user first selects a value for a dropdown to choose a city. A second dropdown is filtered with the sports teams within that city. An example to clarify:
  • The user selects Dallas as the city in the first dropdown. The second dropdown now displays values: Mavericks, Cowboys and Rangers.
  • The user selects Pittsburgh as the city in the first dropdown. The second dropdown now displays values Steelers, Pirates, and Penguins.

High Level Design in Grails 

Before we get into the details, we can take a step back and describe how we can accomplish a dynamic dropdown in the grails framework.
  • On a gsp page, create a select dropdown with the list of cities.
  • On change of the city dropdown, send an ajax call to the server with a param of the city selected.
  • A controller on the server receives the parameter and looks for teams based on the city selected.
  • Return a template with a new select dropdown for the teams, providing a model with the filtered list of teams.
We will continue below with code snippets. The code was demoed with Grails 2.0.

Domain Objects
The domain objects for this example are quite simple: A City object with a name, and a Team object.

Saturday, February 4, 2012

That's Not Agile!

If you work with a bunch of agile minded developer's, you often hear the phrase "That's not Agile!" It's quite humorous to hear, because it comes up all the time.

Recently I have been reading Andy Hunt's books and I find them very insightful. The latest book I am reading is "Practices of An Agile Developer", which he co-authored along with Venkat Subramanium. At the beginning of each section they place a little quote which represents a "devilish" thought. They are entertaining to read, so I thought I would pick out some of my favorite and post them along with my thoughts. If you are agile minded like myself, you will certainly think "That's not Agile!"

Blame Game
"The first and most important step in addressing a problem is to determine who caused it. Find that moron! Once you’ve established fault, then you can make sure the problem doesn’t happen again. Ever."
This attitude is rooted in the blame game. Agile is about providing solutions, not assigning blame. If you run into this atmosphere, try to bring a positive outlook to it and solve the problem first. Allow room for a retrospective to mitigate problems in the future, but for pete's sake, don't blame.

Hack
"You don’t need to really understand that piece of code; it seems to work OK as is. Oh, but it just needs one small tweak. Just add one to the result, and it works. Go ahead and put that in; it’s probably fine."
Under time pressure, this thought will definitely come up in any reasonable person's mind. If you think about it, this mindset is a hack. Responsible developer's should understand what they are getting into. This doesn't mean getting into analysis paralysis, but always look for ways to understand, refactor, and improve the code. The trade off in doing that must always be a consideration, but a hack mindset only leads to distressed code in the end. Weigh the options. Refactoring and understanding the code you are working will pay for itself quickly. 

Egotism
“You have a lot invested in your design. You’ve put your heart and soul into it. You know it’s better than anyone else’s. Don’t even bother listening to their ideas; they’ll just confuse the issue.”
Agile is about collaboration and learning. I have run into this egotistic attitude many times in my career. I would hope an agile team is about ideas, not who is behind the idea. In addition, even if you have a design, it means nothing until you prove it out in code. Tracer bullet the idea instead of arguing, and you will probably come up with a better design in the end anyways if you consider others' input. Don't invest too much in upfront design. If you do, you are missing out on evolving your design.

Stagnant
“That’s the way you’ve always done it, and with good reason. It usually works for you just fine. The ways you learned when you first started are clearly the best ways. Not much has changed since then, really.”
I'll just say it. This is my favorite. That's not agile! At all. In an environment of continous improvement and value creation, this is the last thing you should hear. Especially in the technology field, we need to brace for change and accept that new ideas may be better then the old. I'll borrow a quote from the athletic arena, "If you ain't improving constantly, you are getting passed up."

Feel free to add your own quotes based on your past experiences.

Monday, January 16, 2012

Groovy DSL - A Simple Example

Domain Specific Languages (DSLs) have become a valuable part of the Groovy idiom. DSLs are used in native Groovy builders, Grails and GORM, and testing frameworks. To a developer, DSLs are consumable and understandable, which makes implementation more fluid as compared to traditional programming. But how is a DSL implemented? How does it work behind the scenes? This article will demonstrate a simple DSL that can get a developer kick started on the basic concepts.

What is a DSL

DSL's are meant to target a particular type of problem. They are short expressive means of programming that fit well in a narrow context. For example with GORM, you can express hibernate mapping with a DSL rather than XML.
  static mapping = {
    table 'person'
    columns {
      name column:'name'
    }
  }  

Much of the theory for DSLs and the benefits they deliver are well documented. Refer to these sources as a starting point:

A Simple DSL Example in Groovy

The following example offers a simplified view of implementing an internal DSL. Frameworks have much more advanced methods of creating a DSL. However this example does highlight closure delegation and meta object protocol concepts that are essential to understanding the inner workings of a DSL.

Saturday, November 12, 2011

Pragmatic Thinking: Novice vs Expert

Recently I started reading Andy Hunt's fine book "Pragmatic Thinking And Learning." Hunt is notorious for writing books which offer practical, insightful advice in which developers can apply to their work on a daily basis.  His most famous book is "The Pragmatic Programmer", widely considered one of the top agile programmer books of all time. Even after reading the book 7 years ago, I still refer to it a few times a month. My colleagues and I bring up the "broken window" theory, or often throw out the phrase "Don't Assume, Prove it," sometimes to the chagrin of the unfamiliar. :)

Wednesday, September 21, 2011

4 Groovy Tips You May Not Know

I have been programming in Groovy full time for almost two years now, and I feel quite comfortable with it. In fact, the language's idioms, shortcuts, and syntax has become part of my daily programming thinking. This is fantastic as it has opened my mind to unique programming elegance and artistry, but unfortunately on the flip-side it has cause me to cringe when looking at traditional Java code. This speaks to the efficiency and conciseness of Groovy.

Recently I decided that even though I am adequetely familiar with the language, I wanted to read Programming In Groovy by Venkat Subramanium. I was pleasantly surprised that I learned some useful tips. Below are some tips that I learned:

1. Variant Looping Mechanisms

In addition to the traditional looping constructs, such as "for (i in iterm)" or range (0..5), Groovy provides alternate ways to loop.

Use the upto function to operate on a range of values:
def sum = 0
10.upto(15) {
  sum += it
}
println sum

result:
75


Use the step function to skip values:
3.step(20, 3) {
  print "$it "
}

result:
3 6 9 12 15 18 

Sunday, August 28, 2011

Database Migration in Grails

This blog covers the Grails Database Migration Plugin, the official plugin created by Spring Source and based on the popular Liquibase framework. Examples will demonstrate how database migrations can be controlled, managed, and executed. 

Database migrations are an important facet of web development. Preserving existing data while seamlessly adding new functionality and tables is critical when making incremental database changes to production applications. Without a tool to manage database migrations, teams rely on manual sql, error prone communication processes, and costly risk management to implement solutions.

What is a Database Migration

First let's define database migration. Simply put, database migrations are changes to a database that is already running in production, and the customer wants to retain the data for future releases. If this is not the case, then it is sufficient to not really consider it a database migration, and thus, you can rely on GORMs dbCreate configuration.

Saturday, July 23, 2011

Interviewing Agile Candidates

At my current client project, the group I am with is expanding rapidly based on recent success of agile projects in the last two years. With the reputation of our group increasing, our group is in demand for development to support the business. This is a great thing.

This means the group has opened up several positions for agile developers. It also means that the core members of the group have to interview several candidates to fill 6-10 positions. Not only does this take time and effort, but it also takes a disciplined approach to obtain the best candidates.

Along the way, we have developed a patterned approach to interviewing candidates. So far it has yielded high quality agile members joining the team. I hope to give an brief overview of the approach taken.

Team Members Participate in Interview

The interview process does not just involve the manager and the new candidate. We include a few members of the team during the interview as well. This gives the benefit of various perspectives and also establishes team ownership of the decision to bring on an individual. Existing team members, along with the managers, get exposure to the new candidate for up to 3 hours possibly (we first do a phone screen, then a face to face). This amount of exposure across team members only helps with obtaining high quality developers.

Monday, February 21, 2011

5 Handy Groovy Shortcuts

Groovy's main advantage over Java programming is the ability for a developer to implement a solution in fewer lines of code. Groovy's idioms produce concise, short, and clean code. Of course, on first look the code may look strange to a Java developer. But once you learn Groovy's shortcuts you realize the value of consciseness and how less noise produces easier maintenance of code. To me, this is simple: "Since there is less code to look at, there is less code to understand. Learn the shortcuts and idioms and produce less code to do more."

Over the last year, I adopted Groovy as an enterprise implementation language. Here are 5 Groovy programming shortcuts that I found to be very handy. They are listed as tests, in the model of TDD.

Spread Dot Operator

The spread dot operator calls a method on every item in a collection. Upon the invocations, it creates a new list from the return items.  So instead of looping through a collection to make a call on each object, use the spread dot operator.

Let's say we want to get the first 3 letters of each username:

    void testSpreadDot() {
      def emails = ["nirav@yahoo.com", "bob@gmail.com", "jacob@msn.com"]
      def firstThreeLetters = emails*.getAt(0..2)
      assertEquals(firstThreeLetters, ["nir", "bob", "jac"])
    } 
This is very useful when utilizing several common design patterns or just plan old polymorphism. You are able to call an interface many times with minimal code.

Thursday, December 30, 2010

mockFor and MockFor in Grails

I recently came across a small shortcoming in Grails' mockFor feature. I wasn't able to return a value from a service that was mocked. I get an error where the return value is always a closure, not the value I intended. (Note this occurred in grails v1.1).

I found that using Groovy's MockFor is just as convenient and does not contain this shortcoming.

Concept Overview

Often a developer would like to use mocks to isolate code and verify that a unit of code is operating correctly. The rationale is: "Given that collaborators are behaving in a specific way, the code under test behaves as expected." In other words, if collaborator returns A, then the code under test will perform B. If the collaborator returns C, then the code under test will perform D.

Many Java mock frameworks provide this ability, including EasyMock and JMock, to name a few.

mockFor Shortcoming

On a grails project, I wanted a mock to return a certain value. This did not work. Let me provide an example to illustrate the problem.

Sunday, October 31, 2010

Grails SpringOne 2GX Presentation Summary

This month I had the privilege of attending the SpringOne 2GX conference in Chicago. It was an amazing event for me where I got to meet the leaders in the field and learned many new things.  I primarily went to dive in deep into the latest Groovy and Grails developments, technologies, and trends. This blog serves as a housing place for my notes on each presentation I attended.  At the end of the blog, I have posted the original presentations and made them available.


Grails 1.3 Update
by Graeme Rocher

Industry Usage
  • Grails has 499 plugins
  • Lots of high profile sights such as eHarmony, LinkedIn, Wired, Walmart, Sky, SitOrSquat, Northwestern Memorial Hospital, Many Moons
Grails Tooling
  • Eclipse STS - much improved
  • Unit test improvements - see test reports in console, run integration tests
  • code completion, highlighting errors, gsp completion, tag attribute completion
  • grails command window, auto completion, create apps wizard

Thursday, October 28, 2010

Grails One to Many Mapping with Foreign Key

Grails is a fabulous light weight framework that operates by convention over configuration. This mode of operation results in significant developer productivity and a decrease in configuration headaches.  However, Grails conventions sometimes yield subtle unwanted results.  One example is the default one to many unidirectional mapping configuration, in a very specific scenario.  Grails maps the one to many relationship with a join table. This results in a problem when deleting the child when calling delete() on a child object.

One to Many Mapping Unidirectional Default

When mapping two objects with a one to many relationship and making that relationship unidirectional, grails provides a simple default way to map this to the database.  Take an example of Company and Employee. A Company can have many Employees. Here is a code snippet of how to map these objects.

Sunday, August 15, 2010

3 Common Ways to Use Groovy Closures

What is a Closure?

The concept of closures is an important part of the Groovy language. A closure resembles a function or method in many aspects of programming. For example a closure can take arguments, can have a return value, and can be executed from one or many clients. A closure is essentially a block of code that is defined and executed a later point. A closure can be assigned to a variable or remain anonymous.  You can create a closure, assign it to a variable, and then pass it around your program like any other variable.  For a more thorough explanation, see Groovy Formal Definition.

Use Groovy Closures

Closures enable the creation of creating concise, clean code when applied correctly. Although all programming problems can be solved without closures, a problem solved using closures will most likely contain less code, avoid repetition, and be more elegant.  This article will focus on some simple and common uses of closures. It is directed towards newcomers to Groovy, typically Java developers coming over to the dark side.  We will discover how closures can be used for:

Wednesday, July 21, 2010

Software Principles are like some Life Principles

Software principles are useful tools for design and implementation and they help us produce quality products. However, software principles can be compromised at times. They don't always have to be followed as there are exceptions to the rule. In some ways, they are similar to some life principles, and this blog explores that idea.

Software and Life

In life we have ethics and morals that we live by. Ethics and morals manifest themselves as life principles. They give us a framework to become better people, respect one another, and ultimately improve our quality of life.

In the software industry we have software design principles.  They are rules we operate under in order to make the products we develop elegant, easy to understand, and maintainable.  Software products run our economy or make our day to day lives easier, and software principles play a large role in allowing that to happen.

However, software design principles are not meant to be dogmatic. They are not meant to be strictly adhered to.  The use of software principles should be evaluated within the prism of trade offs.  Software principles are essentially rules of thumbs and can be broken if it's the most pragmatic thing to do.

Software principles are like some life principles . . . but unlike others.  To illustrate my point, let's consider some life principles that can be considered absolute, i.e, should never be broken no matter what the circumstances.

Don't Cheat, and Be Nice

Take the rule "Don't cheat." Under no circumstances would I teach my son that it is permissible to cheat.  It's not OK to cheat on a test at school. It's not OK to cheat on your taxes, and its not OK to cheat on a board game at home.  No matter what the context, big or small, cheating is not beneficial. It only hurts others and ultimately your self.  Software principles aren't like the cheating principle. 

Another example would be "Never treat a person as a means to an end." It is unethical to use a person strictly as a means to an end with disregard to their humanity.  People should be treated as human beings, not as objects. Under no circumstances, would I teach my child to "use" someone just for the sake of personal gain and devoid of respect.  Software principles aren't like ethical principles . . . we can break them if needed.

So what are software principles like then, and what software principles am I talking about?  Most life principles we live by are general rules of thumb, they are not absolutes. Software principles are like that. Here are a few examples of what I mean:

DRY

We live by the principle of "Always tell the truth", but this rule doesn't always apply.  Take for example white lies. If your wife asks you, "Do I look fat in this dress?", you would be asinine to say yes.  Most us would say "No honey, you look great!" Even though your beautiful wife may be slightly overweight (no big deal in my eyes, personally.) 

In software, we have the DRY principle: Don't Repeat Yourself. This should be something you mostly do and can greatly contribute to clean code.  But would you really want to create a full fledged Template or Strategy Method Pattern to save 1 or 2 lines of code?  Sometimes violating the DRY principle can avoid excessive pattern usage, which can cripple a project and make code unintelligible. Evaluate the trade offs for DRY and make the best decision.

Law Of Demeter

How about the life principle of "Always eat healthy"?  Yes, we should eat healthy and watch our diet, in general, so we can live a quality life. But we are allowed to break the rule on holidays and eat the fried turkey and pecan pie. It is permissible to go out with the guys and down some beers and wings once in a while. It's not going to kill you.  If eating unhealthy is the exception, it is fine.

The Law of Demeter is a software principle that enables loose coupling and limits the knowledge of one component to another.  Following this rule keeps your code understandable and limits dependencies. But even though its called a "law", it should be viewed more as a guideline.  If you are dealing with an anemic object, and just need to get some data, it is permissible to for a client to dig through objects to get what it needs.  The alternative would be to blow up the API with several needless methods, which is a documented disadvantage of Law of Demeter.

Conclusion

When designing software, we should understand that software principles should be followed in order to produce quality code. However, use them in a pragmatic manner and don't pursue a software principle so hard that it makes your life and code, miserable.  Evaluate your design in terms of trade offs. After all, we certainly have life principles that we don't always follow, and software principles are the same way. Do what's best for value added effort and leave the dogma behind.

Monday, July 5, 2010

Apply Groovy Curried Closures and Composition to Business Rules

Groovy offers new programming idioms
Groovy is a language that operates on the Java platform and is completely compatible with Java.  Many of its features are easily grasped by Java programmers attempting to learn the language. For example, Groovy automatically provides getters and setters for attributes on objects, treats numbers and strings as first class objects, and offers a myriad of programming shortcuts (like << to add to a list or [:] to create a map).

Closures are easy to understand

However, Groovy also contains programming idioms that are not customary in the Java world.  These concepts are borrowed from other languages and empower Groovy to be very effective and dynamic in solving business problems.  The concept of closures is one example.  Closures are a prime feature in Groovy, but do not exist in Java (although Java 7 is scheduled to contain closures). A closure is a defined block of code that can be passed around and executed at a later point.  They are commonly used when iterating over collections, and they eliminate much of the code noise that comes with Java iteration.  With some effort, closures in their most common application are fairly simple to grasp.

More complex Groovy idioms

Some concepts are more foreign to the conventional Java programmer. Curried closures are an extension to the concept of closure.  Currying a closure takes a little more effort to understand and is certainly not a concept common to Java.  Groovy also allows for composition of closures, where closures are combined together so that closures operate on other closure results.  These techniques are part of the functional programming paradigm which emphasizes the application of functions, rather than methods conducting state changes on data.  Haskell, Schema, and Erlang are functional programming languages.  Through an example, this article will demonstrate how curried closures and composition can be applied to solving business world problems.

Curry Definition

First let's define what a curried function is. The term curry comes from the mathematician Haskell Curry who developed the concept of partial functions.  In functional programming, currying a function means transforming a function into another function by fixing some of its input arguments.  Currying is good for mathematical business problems where you need to break the problem down into pieces.  Essentially, you have a template mathematical formula and you can assign fixed values to a portion of the formula to create new version of the template. A simple math example follows:

f(x, y) = x / y   ---- template
f(x, 2) = x / 2   ---- curry with fixed value
g(x) = f(x, 2)   ---- this is the new curried function
g(10) = 10 / 2 = 5

Function Composition Definition

Function composition is the application of one function to the result of the other.  Using composition, two or more functions can be combined to produce a more elaborate one.  A simple examples follows:

f(x) = x * 2
g(y) = y / 100
f(g(y)) = (y / 100 ) * 2

Investment Business Problem #1

Let's define a business problem that would be interesting to solve with Groovy using curried closures and function composition.  One we clearly see the problem definition, we can apply the programming concepts and illustrate the power of its usage.  

Bob wants to invest some money for retirement. He is 55 years old and will retire at 65.  He has $5000 total to play with.  He has found an investment vehicle that will deliver 8% interest every year for 10 years (compounded once a year). He is not sure whether to invest all of the $5k or only a portion of it.  He wants to see the difference. 

Used a Curried Closure 

Recall that in Groovy, we can create closures which are basically passable functions.  Here we can create a closure that encapsulates the investment formula. 

def interestFormula = { r, y, p -> p * Math.pow(1+(r), y) }

In order to reduce the formula to a specific context, we can replace some of the variables with fixed values.  Currying will carry out this task. Then we can reuse the closure to test out various principle investments.  


package curry.blog

def interestRate = 0.08
def years = 10
def principle1 = 3000
def principle2 = 5000

// create current investment from interest formula with set rates and 
// see what differences in savings will pay off
// years down the road
def interestFormula = { r, y, p -> p * Math.pow(1+(r), y) }
def invest = interestFormula.curry(interestRate, years)

println "invest ${principle1} and return: " + invest(principle1) 
println "invest ${principle2} and return: " + invest(principle2)

From the example above, the output is:

invest 3000 and return: 6476.7749918183645
invest 5000 and return: 10794.62498636394

Clearly, Bob can see that $5k investment returns almost $4k more than a $3k investment. If he can afford to put all $5k for retirement, it would pay off well. 

Investment Business Problem #2

Now we are ten years down the line, and Bob is ready to liquidate his investment.  However, he encounters a money savy friend who says he found a firm that will rollover his retirement fund and actually pay him 10% to manage his money. In order to rollover his retirement account, he must pay the existing firm $100.  Thus, Bob is considering liquidating his account and paying the government 30% tax to keep his money, or continue to invest by rolling over and gaining 10%, essentially deferring his taxes until later.  He wants to evaluate his initial $5k investment against the different paths he can take.

Used a Curried Closure and Composition 

We can create a closure to represent money after tax is applied.  We can then curry it to be specific to the 30% tax bracket.

def taxFormula = {  t, p ->; p * (1 - t) }
def applyTax = taxFormula.curry(taxRate)

For a rollover, we can create a simple closure as well. No currying necessary here as there is only on variable.

def doRollover = { z -> (z - rollOverFee) * (1 + rollOverMatching) }

Bob wants to compare the situation where he liquidates against when he reinvests.  A composition closure addresses this nicely.  We can create a composition template where you can apply different actions after the investment is liquidated.  Curry the composition with the investment closure, then leave the other variables open for the principle and the action.  Essentially the resulting closure does the investment result for you, then applies the various actions to the result.

def composition = {g, x, f -> f(g(x)) }
def considerPostInvestmentAction = composition.curry(invest)

See the entire Groovy script.  considerPostInvestmentAction calculates the investment, then tells you what the result is after you liquidate it and pay taxes, or roll it over.  It can accept a closure and an initial principle. The closure passed in represents the action taken on the liquid value, either tax applied or a rollover.  Bob can compare the differences.


package curry.blog

def interestRate = 0.08
def years = 10
def taxRate = 0.30
def principle2 = 5000
def rollOverFee = 100
def rollOverMatching = 0.10

def interestFormula = { r, y, p -> p * Math.pow(1+(r), y) }
def invest = interestFormula.curry(interestRate, years)

// tax formula which tells you how much you will have after taxes
def taxFormula = {  t, p -> p * (1 - t) }
// curry it with the tax Rate
def applyTax = taxFormula.curry(taxRate)
// formula for rollover; the amount you will have after rollover
def doRollover = { z -> (z - rollOverFee) * (1 + rollOverMatching) } 
// template for functional composition
def composition = {g, x, f -> f(g(x)) }

// use composition and currying to allow you apply a function on top of your 
// investment after you sell it. Thus you can decide 
// whether to pay taxes and keep the income, or roll over into another account
def considerPostInvestmentAction = composition.curry(invest)

println "initial investment is ${principle2}. After taxes it is: " + considerPostInvestmentAction(principle2, applyTax)
println "initial investment is ${principle2}. After rollover it is: " + considerPostInvestmentAction(principle2, doRollover)
The print lines reveal:


initial investment is 5000. After taxes it is: 7556.237490454758
initial investment is 5000. After rollover it is: 11764.087485000335 

Should Bob have the ability refrain from liquidating his investment, he can gain big. His $5k turns into ~$12k.  And he can hope that later down the line, he will be in a lower tax bracket and he can keep more of his money.  If he withdraws now, he is still in the 30% tax bracket and his investment only comes back with ~$7500. 

Conclusion

This business problem can certainly be solved with conventional Java paradigms. However, Groovy is rich in features as well as programming idioms.  Groovy gives the developer a chance to solve programs in a concise, elegant fashion.  If a business problem has functional and mathematical qualities, consider functional programming to solve the issue.

Monday, May 10, 2010

JBoss Seam White Paper Published

JBoss Seam has been in use within industry for a few years now and has a substantial following in the developer market.  Recently, I published a paper highlighting how Seam enables Rapid Application Development (RAD) in the context of Agile environments.  The paper was written in collaboration with my colleague, Jacob Orshalick. 

JBoss Seam: Agile RIA Development Framework

Much of Seam's features are widely documented in forums and on the JBoss site. However, this white paper does not just highlight the many features of Seam.  The paper takes real world use case scenarios and demonstrates how Seam's features can be applied to increase speed of product delivery.  The use cases are geared toward solving business problems and user needs, while the gory details of a technical solution are avoided so that Seam's utility is understood by a wider audience. 

The audience of the paper includes product champions, sponsors, managers, business analysts, architects and developers.  In essence, the goal of the paper is to demonstrate how Seam can be applied to real world scenarios and allow a development team to focus on business needs rather than extraneous concerns, resulting in faster product delivery.

Sunday, April 4, 2010

My Comprehensive Reading List

Recently I decided to track all the books I have read since I graduated college and compile them into one comprehensive list.  What I discovered was that I have read many technical books and that my interests lie in a few discrete other areas.  All the books I have read contribute to my career path and my personal life in some way, and I try to apply anything I learned from reading.  I am interested to see what has influenced you as a developer as well as a person.

I welcome any recommendations, suggestions, thoughts, or criticisms related to these readings.  I am particularly interested in the category I labeled as "Social Science", as I think the themes in those books correlate with the software workplace in many ways, but with a different perspective.  On the same note, I am always looking for the inspiring novel or story to sharpen up the emotional side of my brain.

Technical
  • The Pragmatic Programmer: From Journeyman to Master, by Andrew Hunt and David Thomas
  • Ship It!: A Practical Guide to Successful Software Projects, by Jared Richardson, Will Gwaltney, Jr
  • Domain Driven Design: Tackling Complexity in the Heart of Software, by Eric Evans 
  • Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin
  • Design Patterns: Elements of Reusable Object-Oriented Software (Hardcover), by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides
  • Head First Design Patterns, by Eric T Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra
  • Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and the Unified Process, by Craig Larman
  • Agile and Iterative Development: A Manager's Guide, by Craig Larman
  • Refactoring: Improving the Design of Existing Code, by Martin Fowler, Kent Beck, John Brant, and William Opdyke
  • Seam Framework: Experience the Evolution of Java EE, by Michael Juntao Yuan, Jacob Orshalick, Thomas Heute
  • Maven: A Developer's Notebook, by Vincent Massol and Timothy M. O'Brien
  • JBoss RichFaces 3.3, by Demetrio Filocamo
  • Getting Started with Grails, by Jason Rudolph
  • Grails in Action, by Glen Smith and Peter Ledbrook
  •  Driving Technical Change, by Terrance Ryan
  • The Agile Samurai, by Jonathan Rasmusson
  • Getting Real, by 37Signals
  • Programming in Groovy, by Venkat Subramaniam
  • Building and Testing with Gradle, by Tim Berglund and Matthew McCullough  
  • Practices of an Agile Developer, by Venkat Subramaniam and Andy Hunt
  • Manage It, by Johanna Rothman 
  • Joel on Software, by Joel Spolsky
  • Theory of Relativity, an intuitive explanation, by Jeffrey Bennet   
Social Sciences
  • Naked Economics: Undressing the Dismal Science, by Charles Wheelan
  • The Tipping Point: How Little Things Can Make a Big Difference, by Malcolm Gladwell
  • Outliers: The Story of Success, by Malcolm Gladwell
  • Blink, by Malcolm Gladwell
  • Kluge: The Haphazard Evolution of the Human Mind, by Gary Marcus 
  • First Things First, by Stephen R. Covey, A. Roger Merrill, Rebecca R. Merrill 
  • The 7 Habits of Highly Effective People, by Stephen R. Covey
  • Freakonomics: A Rogue Economist Explores the Hidden Side of Everything, by Steven D. Levitt, Stephen J. Dubner
  • The World is Flat: a Brief History of the Twenty-First Century, by Thomas L. Friedman
  • Ethics for Everyone, by Arthur Dobrin
  • The Happiness Hypothesis: Finding Modern Truth in Ancient Wisdom, by Jonathan Haidt 
  • Shalom in the Home: Smart Advice for a Peaceful Life, by Rabbi Shmuley Boteach  
  • The Principle of the Path: Smart Advice for a Peaceful Life, by Andy Stanley
  •  Under the Banner of Heaven, by John Krakauer
  • The Big Short, by Michael Lewis
  • God the failed Hypothesis, by Victor Stenger
  • God is not Great, by Christopher Hitchens 
  • Discover your Inner Economist, by Tyler Cowen 
  • Liar's Poker, by Michael Lewis 
  • The End of Faith, by Sam Harris 
  • Moneyball, by Michael Lewis  
  • Freedom At Midnight, by Larry Collins and Dominique Lapierre  
  •  Power of Habit, by Charles Duhigg
  • It Starts With Food, Dallas and Melissa Hartwig 
  • Free Lunch, David Johnston 
  • Predictable Irrational, Dan Arielly 
  • Bonobo and the Atheist, Frans De Waal 
     Biographies
    • Three Cups of Tea: One Man's Mission to Promote Peace . . . One School at a Time, by Greg Mortenson and David Oliver Relin
    • The Boy Who Harnessed the Wind: Creating Currents of Electricity and Hope, by William Kamkwamba and Bryan Mealer
    • Gandhi An Autobiography: The Story of My Experiments With Truth, by Mohandas Karamchand (Mahatma) Gandhi
    • The Autobiography of Martin Luther King, Jr., by Martin Luther King Jr. and Clayborne Carson
    • Baseball's Great Experiment: Jackie Robinson and His Legacy, by Jules Tygiel
    • Faith of My Fathers: A Family Memoir, by John McCain and Mark Salter
    • Hang Time: Days And Dreams With Michael Jordan, by Bob Greene
    • Playing for Keeps: Michael Jordan and the World He Made, by David Halberstam 
    • It's Not About the Bike: My Journey Back to Life, by Lance Armstrong 
    • Crazy Horse and Custer, by Stephen Ambrose
    • The Color of Water, by James McBride
    • Lessons From a Third Grade Dropout, by Rick Rigsby
    • The 5 Love Languages, by Gary Chapman
    • Unbroken, by Lauren Hildenbrand
    Novels
    • A Thousand Splendid Suns, by Khaled Hosseini
    • And the Mountains Echoed, by Khaled Hosseini
    • For One More Day, by Mitch Albom 
    • The Five People You Meet in Heaven, by Mitch Albom 
    • Siddhartha, by Hermann Hesse
    • The Da Vinci Code, by Dan Brown
    • Tuesdays with Morrie: An Old Man, a Young Man, and Life's Greatest Lesson, by Mitch Albom
    • The Twentieth Wife, by Indu Sundaresan 
    • On the Road, by Jack Kerouac
    • Fever Pitch, by Nick Hornby
    • The Alchemist, by Paolo Coehlo 
    • The Girl Who Played With Fire, by Stieg Larsson 
    • The Girl Who Kicked the Hornet's Nest, by Stieg Larsson
    • The Help, by Kathryn Stockett
    • The Hunger Games, by Suzanne Collins
    • Catching Fire, by Suzanne Collins  
    • Mockingjay, by Suzanne Collins
    • The Lucky One, by Nicholas Sparks
    •  True North, by Jim Harrison
    Parenting
    • How to Really Love Your Child, by D. Ross Campbell 
    • Raising Happiness: 10 Simple Steps for More Joyful Kids and Happier Parents, by Christine Carter
    • 1-2-3 Magic: Effective Discipline for Children 2-12, by Thomas W. Phelan
    • Toddler 411: Clear Answers & Smart Advice for Your Toddler, by Denise Fields and Ari Brown
    • Fatherhood, by Bill Cosby and Alvin F. Poussaint
    • Bavy 411, by Dr. Ari Brown

    Sunday, March 28, 2010

    One to One Shared Primary Key is Eagerly Fetched in Hibernate

    One to One Shared Primary Key is Eagerly Fetched
     
    Every so often Hibernates presents some peculiarity that, at first observance, doesn't make much sense.  However, once you investigate the peculiarity thoroughly, you see why hibernate behaves the way it does. 
     
    An instance occurs when mapping a one-to-one relationship with a shared primary key.  In certain instances, even if this mapping is declared to fetch lazily, hibernate will eagerly fetch the association.  The reason is because due to the nature of a shared primary key, hibernate does not know whether to initialize the association to null or not without actually joining against the associated table. 
     
    Explore through an Example
     
    Let's set up an example to further explain the situation.  Let's say we want to map a one-to-one association with a shared primary key for two basic entities: a Passenger and a AirlineTicket.  A Passenger can only have one Airline ticket, and an Airline ticket can only have one passenger.  For our example, the relationship will be bidirectional from Passenger to AirlineTicket.
     




    We can map the objects with JPA and hibernate with the code snippets below. Note that we have marked the association from Passenger to AirlineTicket as LAZY.
    
    ....
    @Entity
    @Table(name = "PASSENGER")
    public class Passenger {
    
        @Id
        @GeneratedValue
        @Column(name = "PASSENGER_ID")
        private Long id;
    
        @Column(name = "NAME")
        private String name;
        
        @Column(name = "BIRTHDATE")
        private int age;
        
        @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "passenger")
        private AirlineTicket airlineTicket;
    ... 
    }  
    

    
    ...
    @Entity
    @Table(name = "AIRLINE_TICKET")
    @org.hibernate.annotations.GenericGenerator(name="passenger-primarykey", strategy="foreign",
     parameters={@org.hibernate.annotations.Parameter(name="property", value="passenger")
    })
    public class AirlineTicket {
    
        @Id
        @GeneratedValue(generator = "passenger-primarykey")
        @Column(name = "PASSENGER_ID")
        private Long id;
        
        @Column(name = "SEAT_NUMBER")
        private int seatNumber;
        
        @Column(name = "CLASS")
        private String clazz;
        
        @OneToOne
        @PrimaryKeyJoinColumn
        private Passenger passenger;
        
        public AirlineTicket() {
        }
    ...
    }  
    

    However, when we load the entity with a entityManager.find(..), hibernate issues a join in the generated sql to eagerly load the AirlineTicket!  If the Passenger entity was loaded with a ejql statement such as "from Passenger", hibernate will issue two separate sql statements back to back: one to load the passenger, and then another to load the airline ticket (which essentially is an eager fetch.)
     
    Why does this peculiarity occur?  When hibernate loads the Passenger object, it has to initialize its attributes.  AirlineTicket is an association which is mapped with a shared primary key.  Therefore, in order to find out whether the AirlineTicket is null or not, hibernate must issue a join to the AIRLINE_TICKET table to check if a row exists with the same primary key as the Passenger object.  If hibernate abstained from issuing a join to AIRLINE_TICKET and proceeded to instantiate a proxy for AirlineTicket, the Passnger object would contain a AirlineTicket, even if there was no real association in the database.
     
    Solution
     
    In order to take advantage of lazy loading when you have a shared primary key one-to-one relationship, you can use the optional=false setting on the relationship. For example, the AirlineTicket reference in the Passenger object would have optional=false.  This conveys to hibernate that the there will always be an AirlineTicket for a Passenger, thus it can create a proxy and it is guarenteed to have a corresponding object.
     
    Design Considerations
     
    So what are the situations to use a shared primary key in a one-to-one?  This begs the question of when is it best to use a one-to-one relationship?  One-to-One relationships are modeled in the domain when one object instance has an exclusive relationship with another object instance.  Simple examples would be [Person, Heart], [Husband, Wife], [HeadCoach, NflTeam]. (Of course, you could make silly arguments to debunk this, but you get the drift). 
     
    The easiest mapping for one-to-one relationship is to have a foreign kep from the owning entity to the other object.  In our Passenger example, the PASSENGER table would have a foreign key column AIRLINE_ID. This approach has no peculiarities with lazy loading, as hibernate can figure out if the association exists without joining to another table. All it has to do is check the foreign key for null. 
     
    A shared primary key for one-to-one mapping is appropriate only if the association is non-optional.  Meaning each end of the association has to exist.  If one side exists, so does the other.  If you map without this symbiotic relationship, you will run into the peculiarities above and possibly have to eager fetch for no reason.  This could lead to performance issues.  Shared primary keys save a column on the database, but the mapping is a little more complicated and peculiarities exist.  Hardware is cheap, knowledge is expensive.  Consider this approach carefully.

    Source Code 
    one-to-one.zip
     
    References:

    Monday, March 22, 2010

    5 Ways to Think Wisely in Development

    Recently I have been reading some popular and interesting social psychology books.  The contents are based on empirical evidence and scientific research, and often provide stories about how society operates, and why people behave the way they do.  Some of the books in this genre include: Freakonomics, The Tipping Point, Outliers and Kluge

    The most recent book I read is Kluge: The Haphazard Construction of the Human Mind, by Gary Marcus.  Marcus argues that the human mind is not the elegantly designed organ that we conventionally perceive it as, rather it is a cobbled together contraption which is a product of evolution. He offers explanations on why our minds do clumsy things, such as forget where our car is parked, or why we can't remember what we ate for breakfast.

    Without getting into the details, he points out several characteristics of the human brain that are products of evolution. Our cognitive makeup contains several bugs which can be referenced by psychological terms, some of which include: context driven memory, confirmation bias, motivated reasoning, and framing.  (I'll leave the explanation of these terms to the book itself.) He also gives recommendations on how to overcome these mental pitfalls.  It is a fascinating for the laymen psychologist. 

    So what does all this have to do with developing software?  From Marcus' exploration of the mind, I see several recommendations that can help us become better software developers.  Many of the technical and social decisions we make as part of a software team are often afflicted by the "kluges" of the mind.  Some basic and common sense tactics can help offset these imperfections, not to mention a help us becomes clearer thinkers, wiser developers, and better teammates. 

    1. When possible, consider alternative hypotheses.

    Often when we have an idea, we get stuck on it and want to see it through to the finish, just for the satisfaction of feeling good about ourselves. It could be a design pattern we see for a problem, or it could be some performance enhancement we think needs done.  We tend to not evaluate our own ideas in a dispassionate or objective way.  One of the simplest things we can do to improve our capacity to think and come up with good solutions is to consider an alternative track.  Contemplate on the opposite and counter your own initial ideas.  This can go a long way on improving your own initial thoughts or could lead to an entirely better solution.


    2. Imagine your decisions will be spot-checked.

    Research has shown that people who believe that they will have to justify their answers are less biased than people who don't.  Hold yourself accountable for any decisions you make,  technical or otherwise.   If we do this, we will tend to invest more cognitive effort and make correspondingly better decisions based on analysis, not just feelings or habits.  A good practice would be to write down rationale for any sophisticated decision made and make sure the reasoning is sound.  This could be notes for yourself, or published to the software team in a collaborative tool such as a wiki.


    3.  Always weigh benefits against costs.

    There is always some feature or tool that is cool to use or enticing to learn.  We should always weigh the benefits versus the costs before we proceed down a certain route.  The feature may be cool to the developers, but how much business value does it provide? Does it help the business save money?  The new ORM tool looks great and has some added benefits, but what cost will it incur versus the technical savings? 

    The inverse argument should be considered just as much.  A refactoring may incur some cost to implement upfront, but will payoff in the long run by resulting in more maintainable and defect free code.  The new integration testing tool may require a week of investment, but could reap dividends by allowing the team to write automated tests and eliminate the painstaking manual and repeated tests.  Sometimes the initial pain is worth enduring to get a long term benefit.

    4.  Whenever possible, don't make important decisions when you are tired or have other things on your mind.

    Marcus describes how we have two portions of the brain: the reflexive and the deliberative. The reflexive portion of the brain evolved early on and controls our bodily motions. It also controls ours emotions and fight or flight responses.  The deliberative portion of the brain is the most recently evolved and controls rational thinking and logic.

    When making decisions related to software, make sure you are well rested and not stressed.  Get enough sleep and keep your hunger under control.  When your health is not optimal, your reflexive portion of the brain activates and overrides the rational part.  This inhibits rational thinking and can especially inhibit complicated problem solving.  In order to make the best technical and team decisions, keep in a rested state to leverage the rational part of the mind.

    5. Distance yourself.

    Our mind is set up to ponder the near and defer future decisions for a later time.  It's always about the now and the urgency of the present.  The release needs to be done immediately, and we get into fire fighter  mode where everything is an emergency. Or...The debate is on about the new design and we must engage in the battle and win the argument!

    It's always best to take a step back and distance yourself from the situation. Imagine you are watching from afar and try to judge the situation objectively.  Of course, the here and now is always important, but it's also important to balance situation by distancing yourself.  Doing so will help assess the situation fairly.  It can also let the reflexive portion of the brain simmer down and let the deliberative mind step in to take control when needed.

    Even though we are rational people in a technical field, we are human after all.  We are products of our ancestors and emotions and rationality are both part of our makeup, although not always in the correct proportion. However, simple mindful steps can be taken to offset any shortcomings we have.