Friday, March 27, 2009

I Code Better Without A Computer

Alright so this might sound a little silly because we need a computer to actually write code. However, I find that most of my best design, code, and refactoring efforts happen when I am not at a computer. This has been a common theme for me since college where I would wake up with a thought about some problem I was working on but could not resolve while conscious. I would literally wake up some nights with an answer to something that I obsessed about during the day.

I continue to find myself doing the same thing with my code. This happens when I am driving, sleeping, watching TV, playing WoW, showering (don't think too hard on that one) or while my wife is trying to carry on an important conversation (bad idea BTW). I just tell her that I was listening but spawned a new thread while she was talking. This tends to not work in my best interest so don't try that one. I will let you know when I think of a response that won't get you in trouble.

I guess I found out that I was not the only person who experiences this behavior when I attended Neal Ford's On the Lam from the Furniture Police presentation. There he explained how the right and left sides of your brain operate and how they contend for time. The right side of your brain is where your creative non-linear thoughts occur while the left side of you brain spends it's time with rational linear thought processes. It turns out that if you can occupy the left side of your brain with mundane white noise like sleeping, driving, showering, WoW, the wife, whatever...you free up time for your right brain to produce meaningful analytical abstractions without your left brain interfering.

How many times have you resolved an issue while you are in the process of explaining it to a coworker. Your own blabbering can shut down your right brain so your left brain can reason things out! Here is another cool technique that Neal Ford suggested which sounded bizarre at first to me but then made good sense (to me at least). He suggested putting a rubber duck on top of your monitor and when you get stuck you explain the issue to the duck. This is not a magic duck (I don't think). The point is you are freeing up your right brain to perform the tasks you are really interested in.

I am pretty interested in understanding more about how the brain functions and will probably read Andy Hunt's book Pragmatic Thinking and Learning: Refactor Your Wetware. Maybe if I can control my mind I might be able to control my code. Those of you that know me might agree...

Swiz is the Shiz

Now that I am doing more Flex development I am back to researching MVC frameworks for the Flex client. I initially did what most Flex developers do as they start learning and create inline code that cannot be maintained. From there I went to the other side of the spectrum and tried Cairngorm which did exactly what it said it would do but at the price of being very heavy but keep your code organized. The biggest problem with Cairngorm is that it lead to code explosion with all of the objects it required you to create. Needless to say I wanted to find something simpler.

I then researched some other available frameworks like PureMVC and Mate. PureMVC looks like and octopus of classes and seems like a Cairngorm like framework with incremental improvements. Mate was a lot closer to what I wanted but seemed to introduce too much custom framework.

Finally, I found Chris Scott's Swiz framework. Swiz works that way I think since I do so much Spring development in Java. Swiz's main goal is reduce the clutter you maintain in Flex like singletons and service locators by using dependency injection of your components in your application. Swiz also comes with a very intuitive annotation model for dynamically dispatching and registering event listeners to your methods. All of the nonsense you would normally write with some of the other frameworks are abstracted in Swiz and you end up with little framework noise. Visit the Swiz site and look at the docs. You will be up and running in about an hour if you understand how dependency injection works already. You can also check out Christope Coenraets Swiz example for a simple running example. Also look at the Flex 360 video from Chris Scott for a full explaination about this framework.

Tuesday, February 24, 2009

Mockups

I found this cool little mockup tool that is very easy to work with called Balsamiq. I generally use OmniGraffle for sketching mockups and wire frames but I found this tool to be very enjoyable to work with. When you DnD you elements to the screen you get lots of options for editing that is very intuitive. Here is a quick example of something I whipped up with this tool so you can see what you can do in 2 minutes. The images are cartoonish but I think it will resonate well with end-users when doing design meetings or technical presentations. Simple! Easy to use! Great tool!

Monday, February 16, 2009

Hudson, run a bypass

I thought I would share a pleasant experience I had with a CI (continuous integration) tool called Hudson. I have used other tools like this in the past including Anthill, CruiseControl, and TeamCity. While these tools did their job none of them seemed as easy to use as Hudson.

Hudson downloads as a self contained war file that launches from a command line:

java -jar hudson.war

That is really it to get running and there is nothing else to install. Hudson comes with a built in servlet engine called Winstone. There are no configuration files that you have to touch because you use the built-in intuitive UI to configure the Hudson server and your projects. There are tons of plugins available that can be used to extend the core functionality or you can write your own custom plugins. We run Starteam (yuck) for source control internally but I found a plugin for it and installed it from the web administration. Very simple! I was able to configure SCM checkout, setup email notifications, and execute our build script successfully in about 15 minutes without knowing the product. If you want to see what awesome open source projects look like check out Hudson.

Sunday, February 1, 2009

Flex 3 Builder on Mac OSX

I ran into problems installing the Flex 3 Builder Professional edition on my Mac. This was because my current version of Java was set to 1.6.0. Before you install make sure you go in your Java Preferences (from spotlight) and make sure your Java application setting is J2SE 5.0 32 Bit by dragging it to the top of the list (temporarily). Then install Flex Builder 3 from the DMG file. You will not encounter any errors in the installation.

Finally, I needed to use the latest version of Java but Flex Builder still needs to run on the 1.5 JDK. For this I went through Finder to edit

/Applications/Adobe Flex Builder3/Flex Builder.app/Contents/MacOS/FlexBuilder.ini

From here just add these lines to the top of this file so you can use the right version of Java:

-vm
/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0

-vmargs
-Xdock:icon=../Resources/flexbuilder.icns
-Xdock:name=Flex Builder
-XstartOnFirstThread
-Xms128m
-Xmx512m
-XX:MaxPermSize=256m
-XX:PermSize=64m
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dorg.eclipse.swt.internal.carbon.noFocusRing

Now when Flex Builder starts it will use the right version of Java. Go back into Java Preferences and move Java SE 6 back to the top of the list if that is what you want.

Tuesday, January 20, 2009

Grails Pitfalls and Tips

I have worked with Grails for some time now and thought I would share some of the common mistakes I have made early on. I also thought I could discuss some things that can make developing with Grails easier. Here is my short list of items:

Zero Turnaround Time

One of the convenient features of Grails is the ability to make a change and have that change be available immediately in your application. This is an obvious time saver and allows you to be more productive while developing your application. However, there are times when you will make major refactoring changes on the fly that the JVM cannot deal with. An example of this might be when you introduce something new in the middle of an existing class hierarchy. While it may appear that Grails is happy and your environment is sailing along you might see odd behaviour in the application and see some strange runtime exceptions along the way. What usually remedies this situation is instructing Grails to rebuild the internal structures in your application. This can be done by executing the following command and restarting your application:

# grails clean

Grails Console

One tool that you will want to keep in your Grails toolkit is the Grails console. This allows you to run a your application in an enviroment so you can experiment with code on the fly. One of the main reasons I do this is to try out my unit and integration code in the console before, or during, writing my tests. This is a fast way to get confidence that your test code will provide the results you want. And because you are doing this in the console you do not have to keep executing the grails test-app command to reinitialize the environment.

Since you have the full environment in the Grails console you can easily get references to your Spring beans and services. You are automatically provided a reference to the org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext class with a variable named ctx. This allows you to do things like this in the Grails console:

def service = ctx.bookStoreService
def book = service.getCurrentBook()
println "The most recent book is ${book.name} by ${book.author}"
println book.dump()
You can see all of the defined beans that Grails is aware of like this:

ctx.beanDefinitionNames.sort().each {println it}

Manually Assigning Primary Keys

Most of the time your domain objects will have autogenerated primary key values for the id field. However, I ran into a situation where I needed to manually assign a primary keys for one of my domain objects. This took a little bit of trial and error to make this work. Here is how you do this correctly:

          
String id
static mapping = {
id generator:'assigned', column:'RECORD_ID', type:'string'
}

Also note that you must set the id manually outside of the object constructor on a separate line like this:

def obj = new MyDomainObject(name:'whatever')
obj.id = 'REC000001'
obj.save(flush:true)

Not like this:

def obj = new MyDomainObjects(name:'whatever', id:'REC000001')
obj.save(flush:true)

because the value will not be saved.

Manually Triggering Quartz Jobs in Grails

Grails has an excellent plugin for managing scheduled Quartz jobs. However, I had a situation where I wanted to manually schedule a job. I could not find this in the documentation so after poking around in the source I figured out how to do this using the following technique. First you have to define the job name and group like this:

class MyValidationJob {

def name = 'MyJobName'
def group = 'MyGroup'

// your executable job method here...
}

Then you can manually trigger the job like this:

          // trigger the job manually by job name and group from your controller/service/whatever
def quartzScheduler // inject this in your class
quartzScheduler.triggerJob("MyJobName", "MyGroup")

Using Packages in the Grails

Grails provides a directory structure for your application components by convention similar to Rails. However, this can cause issues if you put your classes directly inside of these folders because they seen by Java in the default package. Using the default package can cause you issues when compiling your classes. Since we are using Groovy (and really Java) it is my opinion that you should add packages to your Groovy classes. I also think that modules in Ruby translate better than package structures at this point but we are stuck with Java constraints.

You can add packages to the provided services and domain folders and Grails will make Spring beans out of them. You just need to be careful not to use the same name for the bean twice. You just reference the bean by the name of the class. For example let's say you have a service called com.myco.service.validation.MyValidationService. Grails will expose this as a bean reference named myValidationService.


Base Classes with GORM

It is common practice that developers make a base domain class with common features of your subclassed domain objects. By defining an abstract class you can define common properties for your domain objects. There is a catch however. The GORM DSL allows you to define constraints and mappings blocks in these classes for validation purposes and defining ORM mappings respectively. The current problem is that if your subclasses have their own mappings and/or constraints defined they will override what is in your superclass instead of being merged with the superclass blocks. I am hoping that a future version of Grails addresses this issue (1.1 hopefully).


Unexpected NPEs

One of the earliest mistakes I made when working with Grails was generating NullPointerExceptions without much to decipher in the stack trace. The most common problem for me (which you will overcome quickly) was to make sure you validate your domain objects and handle the errors appropriately in your controllers. The errors object is automatically added to your domain objects and can be checked with the hasErrors method on those objects.


Viewing the Source of your GSP Files

This is just a quick tip that allows you to view the generated source of you GSP files. This is a simple as adding the 'showSource' parameter to your URL like this:

http://localhost/yourapp/yourController/list?sort=dateCreated&max=20&showSource

Monday, September 8, 2008

Generating GORM Domain Classes

I am on a project that already had a legacy database in place with about 100 tables. I did not want to create my GORM domain classes manually for my Grails project. I am surprised that I did not find any existing code to handle this code generation so I created a Groovy script to handle this. I am sure this code could use some improvements such as handling more SQL types so I will just call it a 0.1 release because it does what I needed for now. Modify the sql varible so it has the right database connection information. Also, modify the tables hash so you can control which domain classes to generate based on a [tableName:className] structure.

   1  import groovy.sql.Sql
2 import java.sql.Types
3
4 sql = Sql.newInstance("jdbc:mysql://localhost:3306/pts_development",
5 "root",
6 "password",
7 "com.mysql.jdbc.Driver")
8
9 // tables hash format => table : className
10 tables = ['PTS_REG_DTL':'Detail','PTS_REG_MST':'Master']
11 tables.each { table, className ->
12 File file = new File("${className}.groovy")
13 sb = new StringBuilder()
14
15 fieldNames = []
16 fieldTypes = []
17
18 query = "select * from ${table}"
19 sql.query(query.toString()){ rs ->
20
21 sb << "class ${className} {\n"
22
23 def meta = rs.metaData
24 if(meta.columnCount <=0) return
25
26 for(i in 1..meta.columnCount){
27
28 fieldName = meta.getColumnName(i).toLowerCase().replaceAll(/_[\w]/,{ it[1].toUpperCase()})
29 fieldNames << fieldName
30 fieldType = ""
31
32 switch(meta.getColumnType(i)) {
33 case Types.BIGINT:
34 fieldType = "Long"
35 break
36 case [Types.BINARY, Types.BIT, Types.BOOLEAN, Types.SMALLINT]:
37 fieldType = "Boolean"
38 break
39 case [Types.CHAR, Types.VARCHAR]:
40 fieldType = "String"
41 break
42 case [Types.DATE, Types.TIMESTAMP]:
43 fieldType = "Date"
44 break
45 case [Types.DECIMAL, Types.FLOAT]:
46 fieldType = "Decimal"
47 break
48 case [Types.INTEGER, Types.NUMERIC]:
49 fieldType = "Integer"
50 break
51 default:
52 fieldType = "Object"
53 }
54 fieldTypes << fieldType
55 sb << "\t${fieldType} ${fieldName}\n"
56 }
57
58 // Print out the table mappings
59 sb << "\tstatic mapping = {\n"
60 sb << "\t\ttable '${table.toString()}'\n"
61
62 for(j in 1..meta.columnCount) {
63 sb << "\t\t${fieldNames[j-1]} column:'${meta.getColumnName(j)}'\n"
64 }
65 sb << "\t}\n"
66
67 // Print out the table constraints
68 sb << "\tstatic constraints = {\n"
69
70 for(k in 1..meta.columnCount) {
71 sb << "\t\t${fieldNames[k-1]}("
72 sb << "nullable:${meta.isNullable(k) ? 'true': 'false'}"
73
74 if(fieldTypes[k] == 'String') {
75 sb << ", maxSize:${meta.getColumnDisplaySize(k)}"
76 }
77 sb << ")\n"
78 }
79 sb << "\t }\n"
80 sb << "}\n"
81 }
82 file.write(sb.toString())
83 }

This code will generate a separate file for each domain class you specified in the tables hash in the current directory. Just make sure you have your database jar file in your classpath. Here is how you could run this code from the command line:

groovy -cp .:/Users/meagle/java/api/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar GormGenerator.groovy