Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, January 9, 2012

Project Euler Problem 8 in Scala

This is 8 in a series.  The previous post is at, Project Euler Problem 5 in Scala. 


So we saw problem 6 solved with a 'one-liner'.  Then we moved on to problem 7 and I had to have a while loop and control variables, which really disappointed me. Problem 8, however, was not only satisfying, but allowed me to explore even more features of Scala.  


Before I get into the actual problem, I want to comment on my language progress.  My 'native tongue' so-to-speak, is Java.  I use Java at work and have for 12 years. I expect it will be paying the bills for years to come.  We can debate the merits of Java as a language, and I'm sure every one reading this has an opinion about it, good or bad.  Regardless of opinion, I am most productive in Java.  Period.  Why?  Because I have used it so much, and am so familiar with the syntax and libraries that the language 'gets out of the way'.  I don't have to think about anything but what the code is intending to do.  This makes me very productive.  I'm finding that its taking a little longer to get to the point where I feel like the language has stepped back with Scala.  Part of it is the rather verbose API documentation, which, just seems to tell me too much and doesn't allow me to get right to 'how do I use this'.  Part of it is that Scala has a lot more power and expressiveness than Java, and that takes more time to learn.  At any rate, my Scala skills are slowing improving.  


Now, on to Problem 8:

Find the greatest product of five consecutive digits in the 1000-digit number.
 73167176531330624919225119674426574742355349194934
 96983520312774506326239578318016984801869478851843
 85861560789112949495459501737958331952853208805511
 12540698747158523863050715693290963295227443043557
 66896648950445244523161731856403098711121722383113
 62229893423380308135336276614282806444486645238749
 30358907296290491560440772390713810515859307960866
 70172427121883998797908792274921901699720888093776
 65727333001053367881220235421809751254540594752243
 52584907711670556013604839586446706324415722155397
 53697817977846174064955149290862569321978468622482
 83972241375657056057490261407972968652414535100474
 82166370484403199890008895243450658541227588666881
 16427171479924442928230863465674813919123162824586
 17866458359124566529476545682848912883142607690042
 24219022671055626321111109370544217506941658960408
 07198403850962455444362981230987879927244284909188
 84580156166097919133875499200524063689912560717606
 05886116467109405077541002256983155200055935729725
 71636269561882670428252483600823257530420752963450
 This problem is pretty straight forward.  Iterate the string literal and multiply sets of 5 numbers together.  Find the largest of those numbers and return it.  Now, in Java, this would take a couple of for loops, a String, possibly a string buffer, some variables to store the results, and an ugly System.out.println....

Not so in Scala.  The Collections facilities actually allowed me to solve this in one line, without any mutable state.  No, really, I mean it.  Check this out:


object Problem8 {
  def main(args: Array[String]): Unit = {
    val totalDigits = """[omitted the big string literal here, but you can add it back if you want to run the code...]"""
    println((for (i <- 5 to totalDigits.length()) yield totalDigits slice (i - 5, i)) collect {
      case i =>
        i.foldLeft(1)((product: Int, nextChar) => {
          (nextChar asDigit) * product
        })
    } max)
  }
}


Okay, its a 'one-liner' but there is a lot going on there.  Let's deconstruct the statement.  First, we see that everything is wrapped in a 'println', which is nice shorthand in Scala for System.out.println.  The second thing we see is that the result of the statement 'max' is what will be printed.  max is a collection function.  A couple of things to note.  Since max takes no arguments, we drop the '()'.  Since Scala can infer its a method call, we can even omit the '.'.  Now let's look at the rest of the code, shall we?


Let's go back to the beginning of the statement.  We are using the 'for' comprehension.  To be honest, the 'for' comprehension in Scala is much more powerful than the 'for' loop in other languages I've used.  You can see, we are going to iterate 5 to the length of the string.  For each iteration, we are going to yield the slice if i-5 and i.  slice is a nice string operator in Scala.  Essentially, we're getting 5 characters.  In turn we are going to collect the results of folding (There's that foldLeft again....) the 5 character Sequence.  The result of all of these will be a Sequence of Int values, on which we call 'max' function.


Boy, that was a mouthful.  It was cool, though, wasn't it?  It took a few minutes for me to weed through the API and figure out the syntax for this, but in the end, it is a succinct and stateless solution....


On to the next one...



Sunday, July 17, 2011

GWT JSNI Reference

I've recently had to go through the GWT JSNI interface, and I found the documentation a little lacking.  While the official JSNI page has nice examples and clearly shows how things integrate, it leaves out some reference information that would be helpful.  My guess is that they didn't want to duplicate the JNI reference, but its still a little frustrating to have to look up the type codes in a separate area.  And the type codes aren't exactly intuitive, I mean, who would guess that 'Z' is the representation for boolean?

So, here is a little cheat sheet for those of you looking for the GWT JSNI type codes.  These are, of course, the same codes that can be found in the JNI reference.

Native Type Java Language Type Description Type signature
unsigned char jboolean unsigned 8 bits Z
signed char jbyte signed 8 bits B
unsigned short jchar unsigned 16 bits C
short jshort signed 16 bits S
long jint signed 32 bits I

long long

__int64
jlong signed 64 bits J
float jfloat 32 bits F
double jdouble 64 bits D

Table taken from Wikipedia, 5/7/2011


In addition to the primitive types, any object can be referenced using its fully qualified name like this:

LFully.Qualified.Name;

For example, to access a string, you use:  Ljava.lang.String;

To reference an array of the same type, prepend [ like this:

[Ljava.langString;

So that's my quick cheat sheet.  Here are a couple of additional references that help:

Coding Basics - Javascript Native Interface (JSNI) 

JDK 6 Java Native Interface-related APIs & Developer Guides

Sunday, April 24, 2011

My First Scala App

I've been looking at learning another development language for some time. Over the years I've dabbled in PHP, Groovy, and even C/C++. While I learned a lot in doing this, I never became an 'expert' in any of them. For the most part, I used them for the project in which they were needed or for the scenario where they were most appropriate and then went back to Java for my primary development platform.

The reason is that I'd become so familiar with the Java tool set, language, and available libraries. I was (and am) most productive in that environment. But Java is showing its age and limitations. Its becoming clear that some of the most vexing problems facing developers will need a full range of tools to solve them, and while Java's OO support is good, its functional support is not. I, therefore, decided that I needed to expand and really learn another language pretty well. I decided that language is going to be Scala.

Why Scala? Well, I'll go over that in a different post. This post is about my experience writing my first Scala app. So, here it goes.

The Application
Since I am changing jobs (again), I decided I would leave something behind for my co-workers.  In our current work environment, we have a shared drive where server error logs are stored in 'pseudo' XML format.  It was always annoying to me that we had to navigate the file structure, open a text file, and hunt through the file to find an error we would be looking for.  It was also difficult to determine how often an error was occurring.  Now, the easy way to solve this is to use the log4j XML appender and read the files with Apache Chainsaw, but this is a large company, and it decided to go with a proprietary format.  I decided to use Scala to write a little desktop app that the developers could use to view the log files in a tabular format, then select a row to see the stacktrace detail.

The Functionality
The application needed 3 essential things : a table to show rows, a TextArea to show the detail, and a FileChooser to select which log to view.  In the background it also needed the following processing capabilities:  read in a file, modify the text to make it valid XML, parse the XML tags.  That's about it.

The Results
Well, I whipped out the app pretty quickly.  It would have been much more quickly if I hadn't been learning Scala along the way.  There were some really nice things about Scala that I found out.  First, its swing wrapper classes are nice, and their pub/sub model is succinct.  Second, the XML processing is excellent.  The built in support for XML files allowed me to parse the logs in a couple of lines of code.  Finally, the Actor metaphor for multi threading was also very easy to use and implement.

I had a few frustrations along the way as well.  The Eclipse plugin was nice, but it still doesn't have code-complete (One of the biggest productivity tools in my mind).  The code-complete is supposed to be in the plugin, but for some reason, doesn't seem to work for me.  I've tried on 3 separate computers. This meant that I was reading a lot of documentation.  Its also hard to read the documentation.  Since Scala has so much support for so many features, the docs can get a little complicated to read.  I'm sure as I become more familiar with the libraries and syntax this will get easier, but I can see how it would be daunting for a junior developer.

Conclusion 
I'm by no means a Scala expert at this point, but I enjoyed the language enough, and it seems to have enough benefits that I'm looking forward to learning more.  Who knows, maybe one day Scala will be my primary language...

Saturday, February 5, 2011

GWT and SmartGWT - JNI and Unsatisfied Link Error

GWT uses the Java JNI mechanism in a really unique way.  JNI was originally intended to work with native code on the computer where you had your JDK, like C++.  I've had limited exposure to the JNI interface - I've only had to use it for a serial communication component.  Even then, I was using a library that relied on JNI, so I didn't generate the code, I just had to make sure the native library was on my classpath.

The Google Engineers applied this mechanism to Javascript, however.  If you want to write 'Native' Javascript in your GWT classes, its easy.  Just flag your method as native and put your javascript code, in comments, before your terminator.  Here's a sample from the Google Web site.


public static native void alert(String msg) /*-{
  $wnd.alert(msg);
}-*/;


Viola!  Instant native interface for your JavaScript CLIENT code.  That's right, just try running this method on the server.  While working on my current project, I ran into this issue accidently while trying to use a SmartGWT class.  I got a JNI error on the server because the VM couldn't find the native code.  Of course, there isn't any native code on the server.  In this case, the 'native' code is JavaScript.

I was trying to pass a SmartGWT ListGridRecord to the server so I could map it to a persistent bean.  Of course, once I saw the error, I followed the inheritance hierarchy for ListGridRecord all the way up the chain, and what did I find at the top?  JsObject.  Of course, I didn't even have to go that far.  After looking at the Record code, it relies on static methods in JSOHelper, which uses a lot of native JavaScript

In the end I had make transfer objects to use to send the data over GWT RPC. This was a good reminder, though, that while GWT looks like Java, what's being executed really isn't.

Friday, December 31, 2010

GWT Designer

I am not a fan of WYSIWYG software.  Almost every experience I had with WYSIWYG tools had the same pattern:
  1. I implement some application using the tool because I am pressed for time.
  2. I get the initial project done very quickly.
  3. Someone requests a change.
  4. Because of the WYSIWYG generated code, I essentially have to rewrite the app.
Maybe I just didn't use the WYSIWYG right.  Obviously, a lot of people love them.  But they were always counter-productive for me.  In the end, they cost me more time than they saved.  So, you can imagine my feelings when I read about GWT Designer.  Here was a Drag and drop visual editor for GWT, complete with integration for SmartGWT and Ext GWT.  I was hesitant, to say the least.

But I also firmly believe that as a Software Engineer, you have to keep your mind open and constantly re-evaluate new tools.  So, I installed the GWT Designer plugin for Eclipse.  I used it for my capstone project, a CRUD application for running a sign installation company.  I was pleasantly surprised.  

Here are a few observations about the Editor:
  1. I was able to jump between code and the visual editor easily
  2. Changing my code by hand didn't break the visual editor 
  3. The code generated by the editor was easily readable and clean
Even though I started with the WYSIWYG, as I got a simple layout produced, I found myself easily translating into the code. It was a good experience.  The visual components I created were originally going to be mock ups, but they were so clean, I've transitioned them into the working code.  The application is not done yet, but its looking good - I've already been able to easily incorporate changes requested by my client.  

Now, here are the drawbacks I encountered:
  1. My 5 year old PC and laptop run the visual components a little slow. 
  2. The visual rendering isn't yet perfect.  While it was mostly reflective of the actual output, there were a few differences.
All in all, though, the drawbacks were more annoyances than restrictions.

If you use GWT, I recommend you try GWT Designer.

Sunday, June 6, 2010

A two week diversion. Eclipse Plugin to Generate Unit Tests

I took a new job about a month ago at an insurance company. The company is in the middle of rewriting the Point of Sale application for its line of business. Since the project had already kicked off and development had begun, I had been assigned the glorious task of filling in Unit test coverage.

You see, the management at this company is pretty new to Agile development methodologies, and until about a year ago, Unit tests were largely unknown to them. They are driving a tight timeline for delivering the rewritten project. Often, the developers are going over their burndown hours, so the first thing to suffer was, you guessed it, the unit tests. On top of that, management is insistent on getting 80% coverage. As you can probably guess from the title of this post, I was assigned the duty of creating unit tests for this iteration of the code, with the purpose of increasing code coverage to as close to 80% as possible.

When I was handed the code, the coverage, depending on sub-project, was between 0% and 20% covered.

I decided to create an Eclipse plugin to help me with the task (On my own time, of course.  During the day, I wrote tests.) I call it Unit Test Generation Plugin.  This version is very basic.  It really only works to create tests for POJOs at this point, but I think I'll extend it a bit to make it more useful soon.

I was really quite surprised at how easy and fun it was to create a plugin for Eclipse.   I thought I'd post some of the code and the process I used to create the plugin on the site.

Here are some highlights.  Let me know if you'd like me to write more detail about a particular topic.

Binding An Event To The Eclipse Package Menu
Eclipse uses a powerful plugin framework to allow you to extend and enhance the platform.  The way to add extensions is to use the PDE, which is a part of the core project.  Eclipse makes creating a new project VERY easy.  To start, go to File->New->Project...->Plugin Project.

In the New Plugin Window, Enter a name, like com.a.plugin.  The rest of the defaults can be left alone.  Click, Next.  Another popup appears to allow you to select more options for your project config.  Modify the name and provider all you like, but the defaults should suffice.  Click Next.

The final panel allows you to select several templates that demonstrate different extensions.  You can select a template if you like, or none at all.  For this project, I will select none.

When you finish, a new Eclipse plugin project is created and you are ready to continue.

Extension Points
An extension point is how you add new functionality to Eclipse.  They are configured using an XML file.  Eclipse supplies an editor to allow you to easily edit this file.  I had some trouble configuring my Handler through this screen, but was able to write the code by hand.  Once I edited it, it appeared correctly in the editor.  I've done a little reading and that might be because I didn't have some RCP plugins installed, but I haven't verified it yet.

Java Code Support
It also turns out that Eclipse has robust support for Java project Elements.  There are interfaces like ICompilationUnit, IPackageFragment and so forth.  It was pretty easy to generate new tests.

The Result
I have decided that I am going to make the project open-source and created a SourceForge project for it.  It is still in Alpha stage, and there is a bit of work to make it a 'real' plugin, but its now out there in the world.

Unit Test Generation Plugin

Now, I'm sure that Robert Martin would hunt me down if he knew what I created, and would destroy the laptop it was written on (OK, I don't really know him, but I've read one of his books, Agile Software Development, Principles, Patterns, and Practices.  From the perspectives presented there, I can infer that he would not be happy with my tool

Tuesday, May 25, 2010

Identifying and refactoring - Inversion Of Control

In my new position, I am now working on a large team of developers (15 in all). This team is working to complete a single product that has been designed using a Service Oriented Architecture. I have some insights into that design as well, however, in this post I thought I would show an example of how to identify and refactor to a design pattern, and why I feel this is a good thing for the project in the long term.

One of the hardest things about design patterns is recognizing when to use them and when not to. I have seen so many architects apply patterns for patterns sake, making code more complex, and making it HARDER to apply patterns where they are truly needed. I've also seen lots of code that isn't refactored to design patterns, and it COULD be made much easier to maintain and understand if it were changed. The code I will be talking about today is of the latter type. I've been writing Unit tests against the codebase at my new position. This has given me an opportunity to review the code. In order to protect the IP of the company I work for, the samples below have been changed. They represent the structure of some of the code, but are entirely unrelated to what my company does.

First, let me describe the general design of the code as it stands. In this instance, we have a method that takes an Enumeration argument. The method then calls the getInstance method of a Factory, and gets the proper implementation of an Interface. The getInstance method also takes an Enumeration. Finally, the code uses a case statement that tests the Enumeration value and uses the interface to set the values of different member variables in the class.  Here is the sample code that would implement this design:

The Container.  This is the class where our execution starts.  We call setMapValue and pass it a Type enum.

  1 package com.arciszewski.staterefactor; 
  2 import com.arciszewski.staterefactor.Type; 
  3 import java.util.Map; 
  4  
  5 public class Container {
  6     private Map<String,String> map1; 
  7     private Map<String,String> map2; 
  8     private Map<String,String> map3; 
  9      
 10     public void setMapValue(Type type) {
 11          
 12         ITypeInterface intf = TypeFactory.getInstance(type); 
 13          
 14         switch(type) { 
 15             case ONE : 
 16                 map1 = intf.getMap(); 
 17                 return; 
 18             case TWO :
 19                 map2 = intf.getMap(); 
 20                 return; 
 21             case THREE : 
 22                 map3 = intf.getMap(); 
 23                 return; 
 24             default : 
 25                 return; 
 26                  
 27                  
 28         } 
 29          
 30          
 31     } 
 32  
 33     public Map<String, String> getMap1() { 
 34         return map1; 
 35     } 
 36  
 37     public void setMap1(Map<String, String> map1) {
 38         this.map1 = map1; 
 39     } 
 40  
 41     public Map<String, String> getMap2() { 
 42         return map2; 
 43     } 
 44  
 45     public void setMap2(Map<String, String> map2) {
 46         this.map2 = map2; 
 47     } 
 48  
 49     public Map<String, String> getMap3() { 
 50         return map3; 
 51     } 
 52  
 53     public void setMap3(Map<String, String> map3) {
 54         this.map3 = map3; 
 55     } 
 56      
 57 } 
 58  
 59 

This is the Factory that creates ITypeIntf concrete classes.  For now there is only one implementation for type.ONE.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public class TypeFactory {
  4  
  5     public static ITypeInterface getInstance(Type type) {
  6          
  7         ITypeInterface typeIntf = null; 
  8         if(type.ONE == type) { 
  9           return new  TypeImplOne();  
 10         } if(type.TWO == type) { 
 11              
 12         } if(type.THREE == type) { 
 13              
 14         } 
 15         return null; 
 16     } 
 17      
 18 }

The Enum.  Not much to say here.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public enum Type { 
  4     ONE, TWO, THREE; 
  5 }

The Interface that defines getMap.

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.Map; 
  4  
  5 public interface ITypeInterface {
  6  
  7     public Map<String, String> getMap(); 
  8 }

An implementation class. Kept simple for discussion.

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.HashMap; 
  4 import java.util.Map; 
  5  
  6 public class TypeImplOne implements ITypeInterface {
  7  
  8     @Override 
  9     public Map<String, String> getMap() { 
 10         //Do something like get data from a DB. 
 11         return new HashMap<String, String>();
 12     } 
 13  
 14 }

Looking at this code, you'd probably say that the developers did some things right.  They designed to interfaces, they are using a creational pattern, and the code is pretty clean and easy to read.  I tend to agree, except when it comes to that ugly switch statement.  Here are my issues with the switch statement:

  1. Developers have to remember the return statement, or we will have NULL implementations when we shouldn't
  2. Developers will be tempted to add more logic to the case statements that are Type specific.  As these add up, the clarity of the code falls
  3. We're already verifying the type in the Factory, so this code is checking the Type value twice when it doesn't have to.
  4. Container needs to be aware of the different implementations of ITypeIntf.  Why should it need to?  Now we've added a dependency we don't need.

There is a change we can make that will improve this code.  Let's change the ITypeInterface to take a Container object in its argument list.  Then we can set the value in the method and the case statement is no longer needed.  This is a classic IOC technique.  Here is what the code looks like after the refactoring.

The new Container. Notice, there is no switch statement. None is needed. the IMPLEMENTATION of the ITypeIntf knows which attribute it needs to set. Also note that Container doesn't need to know anything about the implementation that the Factory returns.

  1 package com.arciszewski.staterefactor; 
  2 import com.arciszewski.staterefactor.Type; 
  3 import java.util.Map; 
  4  
  5 public class Container {
  6     private Map<String,String> map1; 
  7     private Map<String,String> map2; 
  8     private Map<String,String> map3; 
  9      
 10     public void setMapValue(Type type) {
 11         ITypeInterface intf = TypeFactory.getInstance(type); 
 12         intf.setMapValue(this); 
 13     } 
 14  
 15     public Map<String, String> getMap1() { 
 16         return map1; 
 17     } 
 18  
 19     public void setMap1(Map<String, String> map1) {
 20         this.map1 = map1; 
 21     } 
 22  
 23     public Map<String, String> getMap2() { 
 24         return map2; 
 25     } 
 26  
 27     public void setMap2(Map<String, String> map2) {
 28         this.map2 = map2; 
 29     } 
 30  
 31     public Map<String, String> getMap3() { 
 32         return map3; 
 33     } 
 34  
 35     public void setMap3(Map<String, String> map3) {
 36         this.map3 = map3; 
 37     } 
 38      
 39      
 40 }

The new interface. The interface definition was changed to return void and to make the name descriptive of what it does now.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public interface ITypeInterface {
  4  
  5     public void setMapValue(Container container);
  6 }

The new implementation. Notice that the new implementation now has a dependency on Container. That's OK in my mind, since the interface is intended to work on Container. Here's what we gained, though. Now ALL the logic for this condition is in ONE place. Container will never need to be changed, even if a new implementation is defined (For instance, an implementation that will set ALL the map attribute values.)

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.HashMap; 
  4  
  5 public class TypeImplOne implements ITypeInterface {
  6     // Changed the name, too. getMap no longer describes this function, but
  7     // setMapValue does. 
  8     @Override 
  9     public void setMapValue(Container container) {
 10         // Do something like get data from a DB. 
 11         container.setMap1(new HashMap<String, String>());
 12     } 
 13  
 14 }

So what pattern does this conform to? It looks a bit like a State or Strategy pattern. It also looks a bit like a Command pattern. Which would you say it is?

Wednesday, May 5, 2010

Android Application Part 2

This post is part 2 of a series.  Click here to go to part 1.

In my first post, I outlined the 3 major components of the system I am thinking about - Web site, Web service, and Android app.  At first I thought I would dive right into programming the Android application, but then I realized that I was about to make the same mistake my business users make.  I was about to develop something without first thinking through the use-cases I wanted to accommodate.   So, this post is going to deal with the use-cases I will be developing.

First let's talk about the Web site.  Here are the use cases I want available for my first revision:

  • Allow a user to set up a new account
  • Allow a user to set up a new 'Family' (or group)
  • Allow a user to send invitations to other users to sign up/join the group
  • Allow a user to add a list to the Family
  • Allow a user to add an item to a list
  • Allow a user to mark an item as purchased
  • Allow a user to mark an item as needed again
Of course, I can think of about a dozen more use cases, but I am going to limit this first build to just those 7. Now lets talk about the Android application.  Here is what I want it to do:

  • Periodically poll the server for lists
  • Synchronize the local list with the server and save it (rules for conflicts?)
  • Allow a user to view lists
  • Allow a user to mark an item as purchased
  • Allow a user to mark an item as needed again
  • Allow a user to force a sync (He may want to do this right before entering a store)
Given the functionality on the Android application, I believe the needs of the Web service become apparent
  • Provide a service to allow a user to sync the lists from his groups
Now that I look at that, I believe this is going to be a bit more work than I thought, but not too bad.  I can see that there are many more use cases for the Web application than I thought, and many fewer for the Web service.  

Next: Let's do some UML and Sequence diagrams.

Tuesday, May 4, 2010

Android Application Attempt 2

Now that my classes have finished, I am going to attempt an Android application again.  My first idea was a 'my friends' application.  It appears that Google has beat me to it.  Thanks, Latitude.

I have a second idea.  This application I call, 'Family Shopping List'.  The idea is to store a common list, say a grocery list, online, and sync it to all the family accounts tied to the list.  This way, my wife can add milk to the list, and I can pick it up on the way home.  The reason this can't be strictly an online application is simple - Cellular service is often non-existent in grocery stores.  What we can do is sync the lists while we do have service, and show the list we have when we are offline.  So, here is a basic description of the very high-level design of 'Family List'.

  • Server application - A Web site with the ability to set up a new account, view lists, send invites to users.  Accesses a backend database where all information is stored
  • Web Service - Published interface that allows clients to interact with the server.  
  • Client - Android application that communicates to the server.  This application will also have a local data store that mimics some of the tables on the server
That's it in a nutshell.  For my next post I will be going over the basic design of the application. 

Sunday, April 25, 2010

Design Patterns - Chain of Responsibility

Introduction


I am a fan of design patterns.  Patterns provide a common language and understanding of code-bases, and they help us solve problems in useful, understandable and maintainable ways.

Let's take the case I was working on a few months back.  A co-worker and I were given a project to produce some reporting.  The data being reported on was coming from 3 different data sources and needed to be normalized and scrubbed.  A decision was made to create a data-mart, where the data from the real-time production systems would be copied into the data mart weekly to allow managers to run large reports.

From discussions with managers during the discovery phase one thing became clear : There was general disagreement on how to scrub the data. This data deals with time reporting, and sometimes records didn't necessarily make sense - For instance, workers reported 'starting' and 'ending' work 1 week apart.  Clearly, they didn't work an entire week without rest, or food.  How should this record, then, be handled?  Should the number be truncated? Should we assume the worker meant the SAME day?  Should the record be thrown out? I know some of you out there are saying "Um, contact the worker and get him to fix it.".  In this case, that is not an option, and would likely be a post for a different site.  I think you can imagine that managers could think of an infinite number of ways to 'transform' the data before placing it into the data mart.

The Implementation


It is probably clear from the description about that a routine that using things like if/then's is going to be an error prone, and difficult system to maintain.  First off, when the first change comes in to modify how a record is handled, the developer will first have to find the correct if statement in a large chain of if's.  Second, the concerns are mixed together.  In addition, if a NEW type of data error is discovered that will require a new if statement.  Also, if a new variant on an existing error is discovered, a new if statement might be accidentally created if the developer making the change doesn't realize that the new requirement is simple a variant on an existing error.  Finally, given the amount of disagreement between the managers, it was clear that were going to go back and forth on what transformations they were going to want.  With the if/then implementation, this means a second level of if statements to determine if the transformation is needed, further obfuscating the intent of the code.

Design patterns to the rescue.  After a short discussion, it was clear that we wanted to use was the Chain of Responsibility (CoR).  The CoR describes a pattern that defines a series of processing objects and the operations they can perform, along with a way to add new processing objects on the end of the chain.

Let me explain how the solution was constructed.  Of course, I am not using the actual implemenation from work, but a variation on it in order to demonstrate the pattern.  First, we created an object that can needs to be operated on, in our case, I'll call it a Time object.  Then we created an abstract class called Transform that Takes a time object in its perform() method and a Transform object in its constructor. Then we created Transform implementations for the logical transformations needed.  Here are a couple of things the Implementations may have had:

  1. MultipleDayEntryTransformImpl
  2. ZeroTimeTransformImpl
  3. StartTimeAfterEndTimeImpl
  4. ExactlyFiveMinutesImpl
Here is some sample Java code:
/*Here is the class on which the Transform classes will operate.
*/
class Time {
   private Date start;
   private Date end;

   
   public Date getStart(){ return start};
   public Date getEnd() { return end};
   public void setStart(Date start){this.start = start };
   public void setEnd(Date end) {this.end = end};
}


/*Here is the abstract class that defines the interface and constructor
*/
abstract class Transform {
   /*
   */
   public Transform nextTransformation;
   public Transform(Transform nextTransformation){
      this.nextTransformation = nextTransformation;
   };


  public abstract perform(Time time);
}


/*Here is a simple, sample implementation
*/
class ZeroTimeTransformImpl {
  public perform(Time time) {
    if(time.getStart().equals(time.getEnd())) {
      //Do something because the record meets the criteria for this error
    }
    
    if(nextTransformation != null) {
       nextTransformation.transform(time);
    }
  }
}


/*Here is a partial class that might use these...
*/


class Importer {
  public static final main(String[] args) {
    //create the transformers.  this could be defined in
    //a DB, properties file, or made selectable through a GUI..
    ZeroTimeTransformImpl zeroTime = new ZeroTimeTransformImpl(new ExactlyFiveMinutesImpl(...any number of transform objects here));
    
     
    List
    //get Time objects, not implemented
    for(Time time : times) {
      //this will perform all the transformations in sequence
      zeroTime.perform(time); 
    }
    //store the normalized time records...
  }
}

As you can see from the code, the pattern has done a few things for us that are desirable when maintaining code:

  • The types of transformations are declarative and clear
  • The logic to determine if a transformation is needed, and what that transformation is are segregated from all other code and put in their own little world, making it very clear to the developer what is going on
  • Many new transformations can be added to the system without having to modify the main codebase at all.  A new instance and a change to the zeroTime instantiation, and you are done (The creation of the Transform objects can also be abstracted, but that's a different pattern.)
  • Business users can think up any number of transformations for the Time records, and the system should be able to handle it relatively easily.
  • The work of implementing the the transformations can easily be distributed among multiple developers without worrying about merges.
Best of all, I can tell my peers that we used a CoR pattern to solve this problem, and they will immediately have an idea on how the problem was solved, how the code is structured, and where to look then attempting to make changes.

Wednesday, March 3, 2010

Varying interview questions

I wonder if interviews for other professions are as varied as the interviews for software engineers.  I guess with all the charlatans and pretenders out there, companies have been burned.

With the change in ownership at my company, I have been interviewing with different companies, and the questions have been varied and interesting.  I thought I would share some experiences with you.  Here are a sample of some of the questions I have been posed with.

  • How would you handle a situation where you were handed a deadline for some functionality and you KNEW it could not be done in that time frame?
  • What is the difference between deleting rows, dropping a table, and truncating a table (NOTE: This was for a Java developer job, not a DBA job)
  • How do you do String comparison?
  • What is the difference between a Map, a List, a Set, and an Object Array (You mean besides the fact that an Object Array is a primitive part of the language and the others are not?)
  • Describe how you would manage a software development project.
  • Describe a time when you had to debug something and the tools you use.
I believe I've done reasonably well in the interviews I've been in, but the questions to me seem to be all over the place.  Perhaps employers have a variety of needs and are trying to determine where I would best fit.  Either way, its difficult to be prepared for interviews.  Last week I was reciting intricacies of JVM memory reclamation, language features and syntax, and constructs. This week I was describing my use of requirements, Use-Cases, UML and Sequence Diagrams.  I can't wait to see what next week brings.

Sunday, February 28, 2010

GoDaddy Shared Hosting Issues

I recently put up a site for a friend.  The site is pretty simple.  My friend has spent years developing a predictive model for volatility based on the VIX index.  Essentially it predicts spikes in volatility.  Professional traders can use this information to increase returns on investments or to adjust their portfolios.

The intent of the site is simple.  Allow a way for people to subscribe to the newsletter, and allow my friend to issue newsletters notifying the subscribers that that the algorithm has predicted a change.

Being a native Java guy, I chose to use Java to develop the site.  Since my friend had registered a domain with GoDaddy, I told him to just get the GoDaddy shared Tomcat hosting service.  I now believe that was a mistake.  Here are some of the things I've found along the way:

  • Although GoDaddy advertises that they support Java 1.5, the JSP compiler defaults to 1.4.  You have to specify an alternate compiler for your JSP files in web.xml if you want to use 1.5
  • You cannot restart your container.  The server recycles once a night, that's it.  This makes deployments of code/upgrades difficult, since changes to .jar files will only be recognized the next day.
  • While GoDaddy claims that you can use any Java library, just drop the .jar file into WEB-INF/lib/ and the changes will be picked up when the server restarts.  This is not the case.  I originally implemented the site using Hibernate, but when I deployed to the server on GoDaddy, I received an issue when trying to read in the configuration file.  When I submitted a support request, the response was simply, "We don't support Hibernate".
  • There doesn't seem to be any way to view Tomcat error files.  When I turned on error logging, it showed me the APACHE logs, but not the Tomcat logs.  I had to roll my own logging system in the end.
To be honest, the undocumented lack of support for libraries is the most disturbing thing I found.  When I pressed the support team for more information, like a list of unsupported libraries, they simply responded that it would be infeasible to keep one.  I understand that they can't list every library that isn't supported, but a list of common libraries would certainly be feasible.  In addition, they need to restate their claim that you can use any library as well, since that is misleading.

The net result of this rather poor policy is that if you use any library in your application, you will not be guaranteed that it will work until you try to deploy it.  That's a broken model to me.

In the future, I'm going to recommend that my clients do NOT use GoDaddy, especially their shared hosting.  I will be finding a way to migrate this friend off their service as well.

Sunday, January 3, 2010

Android Development – So Easy, Yet Not So Easy

I have recently started playing around with Android. Given the success of the Droid, Droid Eris, and what looks like a phone from Google, the NexusOne, I figure the Android is going to be either the number one or number 2 development platform for mobile devices. In either case, I want to be able to write apps for my Droid, which, I love.

So this week I have attempted to start development. I have read through the online documentation, which, in typical Google fashion, is fairly complete and detailed. The Android Developer Guide includes step by step instructions for installation of the SDK, Eclipse Plugin, and samples to get you programming quickly.

Of course, nothing is perfect. So here are a couple of issues with the tools.


  • It appears that sometimes changed resources don’t get updated when the emulator is re-launched. Even though I’ve set the flag to Wipe User Data.
  • I can get one version of the Google Maps sample to run correctly but not another. It seems that the Sample Tutorial on the Web site doesn’t work for 2.0 or 2.0.1 emulators on my machine, but the sample bundled with the toolkits do. To be honest, it appears that the only difference is WHERE the MapView is instantiated, but I am still a noob at this, so I am probably mistaken

Is this going to be enough to cause me to give up? Heck no. Even though these two items are frustrating, the toolkit is still well put together and I expect to be building apps in no time. My next posts will detail the building of an app.