May 122013
 

As detailed in this question on StackOverflow.com, I am dynamically loading data into a series of dropdowns via AJAX. The problem is I want the user to be able to select the first element in the list, but it becomes the default selection and you can’t select it until you have selected some other item first.

After much Googling around, I found enough clues to lead me to the solution I adopted as detailed in the answer I submitted on StackOverflow.com and in the CodePen below.

Check out this Pen!

Jan 232013
 

I can’t count how many times I have looked at some code that gets it so wrong in so many ways and is completely excused because the team is putting in a tremendous effort, doing it wrong.

The doing it wrong part gets left out, but the fact remains, that they get praise for their effort, sometimes even rewarded, even though the end result is in-effective at best and a waste of valuable resources having to maintain the code over the long run.

Teams that create solid effective maintainable code with little effort hardly ever get recognized. Is the fact that they are skilled in their craft a reason to ignore their effectiveness?

Nov 122012
 

I found a small template snippet that worked great for getting the length of an array in C++ without having to store the size in a separate variable.
But one thing wasn’t working, calling that template function on an array passed into a function/method as an parameter.
The helpful denizens of stackoverflow.com came to my rescue very quickly if you look at the time stamps on the question and the answers.

Jul 072011
 

This some considerable noise on the internet about Fluent APIs and using them. There was a question on stackoverflow.com about how to enforce calling all the required methods to guarantee you fully materialize an object when using a Builder Pattern with a Fluent API approach.

The appropriate way to achieve this is through Interfaces that represent each of the steps in the procedure. You have to make the constructor to resulting object that implements these interfaces private so that no one can directly create the object, and you probably want to make the class private as well so no one can cast directly to the resulting object from a reference to one of the intermediate Interfaces.

Here is the code for one example on how to have a Fluent API that enforces the order in which the methods are called and protects the object being built.

May 092011
 

Where is final used?

There are a lot of Java developers that don’t understand the keyword final. The keyword final is one of your greatest allies in writing bug free maintainable code. It makes reading code much more deterministic and step debugging a breeze. And it makes your code side effect free.

Side effects are on of the most common causes of bugs and instability in imperative programming, and one of the most difficult to discover and correct.

One reason most people don’t understand why final is such a powerful keyword, is that it has two distinct meanings and most people only really understand the first.

Marking a class as final

The most popular understanding of why to use the keyword final is in marking a class as final. This makes sure that no one can sub-class the class that is marked final. This is like putting a sub class lock on your code, it means that the original developer intends that this behavior should never change.

Marking a method as final

Another similar use to the class usage, but much less known, is to mark a method as final. This is a seen in much rarer cases than marking an entire class as final. It locks the method so that sub classes can’t override the behavior of the method and shows the intent of the original developer that this should never change.

Marking a variable reference as final

The second most popular understanding of why to use the keyword final is to mark variables as final, this one is also the most misunderstood. This does something completely different than its use as a class or method modifier. It shows the intention of the original developer that the reference to an object or primitive should be immutable and trying to change it should result in an error.

final vs immutable

Some clarification is in order here, because there seems to be a lot of confusion about what is actually immutable when a variable reference is marked final.

It is the variable reference that is immutable, not the Object itself.

When someone refers to an Object as immutable, such as

The String object is immutable

they mean the internal state of the String object can never change, this is completely different than

the variable X is marked final and thus immutable.

Marking a variable final doesn’t magically make the Object instance that it is refering to immutable.

Lets take the following example:

private final List people = new ArrayList();

What this states is that the reference people can not be changed to point to a different instance of List.

It does not modify the behavior of the ArrayList implemenation in any way. The instance of the ArrayList can still be modifed. Person objects can be added and removed which mutates the ArrayList as it normally would.

What the final keyword does here is shows the intention of the original developer, that what the people variable refers to should never change.

If you later executed these instructions your code would not compile.

this.people = new ArrayList();

When should I use the keyword final?

Best practices show that you should use the keyword final as liberally as possible. The restrictions that final puts on what it is modifying always makes code easier to understand the intentions of the original developer and makes understanding the logic easier and makes step debugging easier as well.

Since marking a class or method as final is pretty explanatory and you can reason fairly easily why this is done and what its benefits are I am going to discuss why you should always strive to mark as many variable references final as possible.

The first two rules are fairly easy to implement, and show the most benefit when used

Always mark arguments to constructors and methods as final

public class Person(final String firstName, final String lastName)

public int getNextDay(final Date date)

This is a very powerful tool to help create easy to understand, and maintainable code, it shows to everyone that the arguments to never change. If they never change, as you read through the code to understand it you can be guaranteed that the argument values are consistent everywhere they are reference, they always referent to the same values that were passed in.

Always mark local variable final

One of the hardest things to debug is some long method that re-assigns a value over and over again in many different decision making constructs. Nested if/elseif/else statements and try/catch/finally blocks that re-use and mutate a local variable make it very difficult to statically reason what the expected behavior of the code is. It makes the method one big ad-hoc state machine. And the only way to understand the behavior is to step debug through the code, or worse pepper it with print statements all through it in an attempt to trace what the behavior is depending on the inputs.

It also makes it very easy for someone to come along behind you and break something un-intentionally because they have re-assigned something and broken your ad-hoc state machine.

Functional languages like Erlang have single assignment variables as a core part of their paradigm, and they tend to be more deterministic, easier to read and reason about what the intention of the logic is and less buggy because there is never a huge ad-hoc state machine.

Marking all instance variable references final

This one is harder to stick to consistently from a conceptual stand point. Mainly because it goes against everything most Java developers have ever know. But the rewards for learning to apply this practice are tremendous.

The first benefit is you get all the same benefits as marking arguments and local variables as final. You get easier to read and understand the intention of the original developer, you get simpler debugging and no side effects.

The second benefit of marking all instance variables as final is that you gain thread safety immediately, when all instance variables are final it makes the instance of the class immutable. Immutable instances can be shared without any locking semantics among as many threads as you wish since there is never the chance of data changing, so that means no contention and no race conditions.

Dealing with immutable data might seem like a hassle, but as soon as you start working with the data structures concurrently, dealing with immutable data structures is simple compared to dealing with concurrency primitives, locks, semaphores, synchronized blocks, counters and all the other baggage and boilerplate overhead that comes with concurrency in Java. All that concurrency overhead is extra code to be tested, debugged and maintained.

There is a performance angle as well

In previous versions of the JVM marking any variable references, instance, local and arguments as final allowed the compiler to do some advanced optimizations through caching because it could be sure that the contents of the variable reference never changed. This combined with immutable objects made a significant difference in concurrent code execution. In the case of final String declarations the compiler can aggressively optimize those out to almost nothing, since final String declarations are considered string literals if you concatenate string literals with + it can just convert them all to one single string literal.

Some of the performance aspects of the final keyword from previous compilers are handled with the most current JIT, but using final just for performance isn’t what this article is about, it is about increasing the quality of your code base, making your logic easier to discern the intention of the developer and making it more maintainable over the long run. Performance enhancements are just a bonus to these practices.

So the final word on final is

Try to apply the final modifier everywhere you can to make as many variables as possible single assignment, the more you do it the more you will appreciate the entire class of bugs and logic complications it allows you to eliminate through the single assignment variable idiom.

May 042011
 

Certifications show you can study and take a test

They don’t demonstrate that you actually comprehend any thing that was on the test. In the worse case certifications can turn off a lot of hiring managers as they got burned in the dotCom bubble boom with unqualified staff but were “certified”, it looks like someone trying to take a short cut to actual knowledge and experience that they can’t demonstrate.

I think twice about people with lots of certifications, especially in things they have little or no demonstrable experience in. I had so many real estate agents in the 1990′s applying for developer positions with a arms length of certifications and bogus years of experience it was sickening. Lots of my peers experienced the same thing.

Look at it this way

Which would you hire? A graphic designer with a bunch of Photoshop certifications or one with a portfolio of demonstrable work using Photoshop, given that they claimed the same number of years of experience?

Certifications don’t make you more marketable

Better marketing makes you more marketable. You should invest in learning how to sell yourself on what you know and learn how to demonstratewhat you know, don’t spend money on taking tests about things you partially know in an attempt to prove something to someone.

Demonstrable knowledge isn’t about years of experience, it is about demonstration

Spend some time writing an open source application, no matter how trival, that demonstrates your knowledge, put it on GitHub, put it on FreshMeat.net, put links to those sites on your resume.

Spend time writing about development on a blog, people with experience have personal opinions about what they do. Blog about your open source development and your opinions about .Net and its libraries. Opinions, even ones I don’t agree with demonstrate your knowledge about something.

I know this will sound silly, but your job isn’t what you do, it is selling yourself. You need to be able communicate that as quickly and clearly as possible. Marketing and Sales is all about communication. Demonstrating something is the most effective form of communication.

Generalists usually make more valuable employees

Generalist usually make better employees since they have a broader range of experience to draw from. Later on in your career when you get totally burned out on programming, you will want to be able move into some position where you lead teams and then eventually move on into management. Generalists can mentor and manager a broader range of talent and demonstrate more flexibility.

In golf you need to know how to use every club, only knowing the putter won’t get you far on a full size golf course.

Being a .Net guru won’t get you a management position, it will get you a glass ceiling of Senior .Net Developer. Being able to demonstrate a broad range of expertise will get you farther toward management than being a .Net guru. And it will open more doors outside the .Net world.

Success != scoring good on tests

Think about it, nobody in the software development field that is a big name got there because of some test they took. They all built something or wrote something that demonstrated that they knew what they were doing. Mark Zuckerberg didn’t get where he is by taking tests or years of experience, he demonstrated to venture capitalist what he could do by just going and building FaceBook. He didn’t try and convince them to give him money for something he was going to do, he did it, and they came to him. He demonstrated he could deliver and they believed he could continue to deliver.

Years experience != proficiency

I have worked with many developers that claimed 10+ years of experience in Java. 9 out of 10 of them wrote code like it was 10 years ago. They had 10 years of doing the same thing they did the first year. 10 years of 1 year of experience isn’t valuable to me.

The 1 out of the 9 could easily demonstrate their proficiency either with examples or their opinions about current modern Java. The others were still using Enumeration, Vector and Hashmap in 2009 and didn’t even know or care about Generics or the Collections API, this was a negative demonstration of their experience.

On a Personal Note

If you want to go and take certifications for yourself, to see what the testing organization thinks is important or valuable then there may be some value to it for you personally. It might show you where the holes in your knowledge of a particular technology is and give some direction of knowing what you don’t know you don’t know. But to most hiring managers they are not a decision maker.

Mar 222011
 

I have released my first Maven artifacts to the Central Repository through Sonatype’s Open Source Nexus Server.

You have to jump through some hoops to get everything just right to be able to release to the Sonatype Nexus repository, and I could not find all the information I needed in one place so I will document what I had trouble with here.

I followed these instructions and I had no trouble on Linux or OSX with getting anything to work, Windows 7 was a different story.

First thing I had trouble with on Windows 7 was getting GPG setup to sign my artifacts. I am using the GitBash shell that comes with the Git distribution for Windows. It doesn’t have everything you need to work with gpg as per the Sonatype Blog instructions. What I had to do was download the Windows installer for GPG from GnuPG.org

Then I copied all the .exe and iconv.dll files from C:\Program Files (x86)\GNU\GnuPG into C:\Program Files (x86)\Git\bin. These were the default installation locations for each of these packages, your locations may differ if you put them somewhere else.

The one other thing is I had a hard time getting the gpg goal to fire and sign all my artifacts when using the maven-release-plugin. I ended up with the following command line that did the trick.

mvn clean package verify release:preform -Darguments=-Dgpg.passphrase=PASSPHRASE

Mar 112011
 

Make your pom.xml dependency entry for Jasper Reports look like this
If you don’t use the excludes directive you get the java.lang.NoSuchFieldError: reportUnusedDeclaredThrownExceptionIncludeDocCommentReference error.

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>3.7.4</version>
    <exclusions>
       <exclusion>
            <artifactId>jdtcore</artifactId>
            <groupId>eclipse</groupId>
          </exclusion>

    </exclusions>
</dependency>
Feb 282011
 

Name your Interface what it is

If your interface is a Truck, call it Truck. Not ITruck because it isn’t an ITruck it is a Truck. An Interface in Java is a Type. Then you have implementations of DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc. When you are using the Interface Truck in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just crappy Hungarian style notation tautology that adds nothing but more stuff to type to your code.

All modern Java IDEs mark Interfaces and Implementations and what not without this silly notation. Don’t call it TruckClass that is tautology just as bad as the IInterface tautology.

The only real exception to this rule that I accept, and there are always exceptions is AbstractTruck when the class is package local. Since only the sub-classes will every see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck or some other more descriptive name instead. But since Abstract classes should never be part of any public facing interface it is an acceptable exception to the rule.

If it is an class it is an implementation

And the Impl suffix is just more noise as well. More tautology. Anything that isn’t an Interface is an Implementation, even Abstract classes which are just partial implementations. Are you going to put that silly Impl suffix on every name of every Class? It makes no more sense than suffixing every Class with Class.

The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.

Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No you see. List and ArrayList and LinkedList. Any of these silly prefix/suffix naming conventions all violate the DRY principal as well.

Also if you find yourself adding DTO, JDO, BEAN or other silly repetitive prefixes or suffixes to object names then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don’t even adhere to in a consistent manner. If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have an situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don’t need the Interface.

If you can’t give unique descriptive names to your Interfaces and Classes, you are doing it wrong.

Mocking the Mocking Argument

It has been argued that putting a Mock prefix or suffix on classes is a good idiom to mark the classes as Mock implementations, why not call them MockImpl if you are going to argue that?
Assuming that the real classes are in com.company.app.service. Mock implementations should be in their own com.company.app.service.mock package, ideally in a different directory structure with the Test classes, as in Maven, which will allow them to have the same names as the non-Mock classes, and still document that they are Mocks for testing only, and not pollute the name space of the production code and make it easy to not-include that code in the deployment.