Below you will find pages that utilize the taxonomy term “Java”
Posts
Dirty Code Monday!
Lately I’ve been thinking about how easy it is to fall into the trap of not challenging our ideas about the code we’re working on. In order to challenge the default mindset of Clean Code, I recently proposed to institute Dirty Code Monday (a proposal that sort of got me into a bit of a big discussion).
Anyway, here is the report from the first successful Dirty Code Monday one week ago:
read morePosts
A canonical XML test
I recently did a few days of TDD training for a client. They asked me to help them test and refactor a class that created XML from an internal domain model. This gave me the opportunity to examine a bigger pattern.
I wondered where the domain model came from. Looking through the code base, I found that the same or similar data structures were dealt with many places. As often is the case, I also found a bit of code that parsed an XML structure and output the domain model.
read morePosts
A wicked Java trick to make the JVM forget to check exceptions
I’ve long time been a critic of the mechanism of compiler checked exceptions in Java. Whether you love them or hate then, one thing is sure: There’s situations where you don’t want to have to deal with them. The solution in Java is to wrap a checked exception in new RuntimeException(e) but this gives long stack traces without adding useful information. Sometimes, we just want to tell the compiler to chill.
read morePosts
Promises you can trust
JavaScript Promises provide a strong programming model for the future of JavaScript development.
So here I’m playing with promises.
First I need a bit of a package.json file:
{ "name": "promises", "scripts": { "test": "node node\_modules/mocha/bin/mocha" }, "devDependencies": { "chai": "^1.10.0", "mocha": "^2.0.1" }, "dependencies": { "q": "^1.1.2" } } Now I can write my first test (test/promises_test.js):
var Q = require('q'); var expect = require('chai').expect; describe('promises', function() { it('can be resolved', function(done) { var promise = Q.
read morePosts
Dead simple configuration
Whole frameworks have been written with the purpose of handling the configuration of your application. I prefer a simpler way.
If by configuration we mean “everything that is likely to vary between deploys”, it follows that we should try and keep configuration simple. In Java, the simplest option is the humble properties file. The downside of a properties file is that you have to restart your application when you want it to pick up changes.
read morePosts
The lepidopterist's curse: Playing with java.time
Pop quiz: What will be the output of this little program?
public class DateFun { public static void main(String[] args) { long hours = getHoursOfDay(LocalDate.now(), ZoneId.systemDefault()); System.out.println(hours); } private static long getHoursOfDay(LocalDate date, ZoneId zoneId) { ZonedDateTime startOfDay = date.atStartOfDay(zoneId); Duration duration = Duration.between(startOfDay, startOfDay.plusDays(1)); return duration.toHours(); } } The answer is, like with most interesting questions, “it depends”. How can it depend? Well, let try a few examples:
getHoursOfDay(LocalDate.of(2014, 7, 15), ZoneId.
read morePosts
The madness of layered architecture
I once visited a team that had fifteen layers in their code. That is: If you wanted to display some data in the database in a web page, that data passed through 15 classes in the application. What did these layers do? Oh, nothing much. They just copied data from one object to the next. Or sometimes the “access object layer” would perform a check that objects were valid. Or perhaps the check would be done in the “boundary object layer”.
read morePosts
Why I stopped using Spring
My post on DZone about Humble Architects sparked somewhat of a controversy, especially around my disparaging comments regarding Spring and Dependency Injection Frameworks. In this post, I expand on why I stopped using Spring.
I was one of the earliest adopter of Spring in Norway. We developed a large system where we eventually had to start thinking about things like different mechanisms for reuse of XML configuration. Eventually, this evolved into the @Autowire and component-scan which took away the problem with huge configuration files, but in return reduced the ability to reason about the whole source code - instead isolating developers in a very small island in the application.
read morePosts
Humble architects
Humility is not a very common trait with software architects. After having worked with a few awful architects and recently with a very pleasant one, I’ve compiled a few of my experiences in the way every architect loves: As a set of rules.
Rule 0: Don’t assume stupidity It seems like some architects assume that developers, if left to their own devices, would behave like monkeys. In my experience, this is very rarely the case.
read morePosts
Announcing EAXY: Making XML easier in Java
XML libraries in Java is a minefield. The amount of code required to manipulate and read XML is staggering, the risk of getting class path problems with different libraries is substantial and the handling of namespaces opens for a lot of confusion and errors. The worst thing is that the situation doesn’t seem to improve.
A colleague made me aware of the JOOX library some time back. It’s a very good attempt to patch these problems.
read morePosts
Having fun with Git
I recently read The Git Book. As I went through the Git Internals parts, it struck me how simple and elegant the structure of Git really is. I decided that I just had to create my own little library to work with Git repositories (as you do). I call the result Silly Jgit. In this article, I will be walking through the code.
This article is for you if you want to understand Git a bit deeper or perhaps even want to work directly with a Git repository in your favorite programming language.
read morePosts
Offensive programming
How to make your code more concise and well-behaved at the same time Have you ever had an application that just behaved plain weird? You know, you click a button and nothing happens. Or the screen all the sudden turns blank. Or the application get into a “strange state” and you have to restart it for things to start working again.
If you’ve experienced this, you have probably been the victim of a particular form of defensive programming which I would like to call “paranoid programming”.
read morePosts
A canonical web test
In order to smoke test web applications, I like to run-to-end smoke tests that start the web server and drives a web browser to interact with the application. Here is how this may look:
public class BookingWebTest { private DataSource dataSource; private Server server; @Before public void createServer() throws Exception { dataSource = DataSources.getTestDataSource(); new EnvEntry("jdbc/applicationDs", dataSource); server = new Server(0); server.setHandler(new WebAppContext("src/main/webapp", "/test")); server.start(); } private final WebDriver browser = new HtmlUnitDriver(); @Test public void shouldShowCreatedBookings() throws Exception { PersonDao personDao = new PersonDao(dataSource); Person person = new Person(); person.
read morePosts
Om å løse alt bortsett fra det egentlige problemet
“Problemet med Java er at det krever så mange abstraksjoner. Factories, proxies, rammeverk…” Min samtalepartner gjenfortalte inntrykket han hadde av de Java-programmerende kollegene sine.
Jeg måtte innrømme at jeg kjente meg igjen. Kulturen rundt Java-programmering har noen sykdomstrekk. Kanskje det minst flatterende er fascinasjonen for komplekse teknologiske løsninger. Et gjennomsnittlig Java-prosjekt har rammeverk (Spring, Hibernate), tjenestebusser - gjerne flere (OSB, Camel, Mule), byggverktøy (Maven, Ant, Gradle), persisteringsverktøy (JPA, Hibernate), kodegeneratorer (JAXB, JAX-WS), meldingskøer (JMS), webrammeverk (JSF, Wicket, Spring-MVC) og applikasjonsservere (WebSphere, WebLogic, JBoss).
read morePosts
A jQuery inspired server side view model for Java
In HTML applications, jQuery has changed the way people thing about view rendering. Instead of an input or a text field in the view pulling data into it, the jQuery code pushes data into the view. How could this look in a server side situation like Java?
In this code example, I read an HTML template file from the classpath, set the value of an input field and append more data based on a template (also in the HTML file).
read morePosts
A canonical Repository test
There are only so many ways to test that your persistence layer is implemented correctly or that you’re using an ORM correctly. Here’s my canonical tests for a repository (Java-version):
import static org.fest.assertions.api.Assertions.*; public class PersonRepositoryTest { private PersonRepository repository; // TODO < == you must initialize this @Test public void shouldSaveAllProperties() { Person person = samplePerson(); repository.save(person); // TODO: Make sure your repository flushes! assertThat(repository.find(person.getId()) .isNotSameAs(person) .isEqualTo(person) .isEqualsToByComparingFields(person); } @Test public void shouldFindByCaseInsensitiveSubstringOfName() { Person matching = samplePerson(); Person nonMatching = samplePerson(); matching.
read morePosts
Loud failures are better than silent, faulty behavior
Sometimes, small questions lead to big answers. Sometimes these answers are controversial. One such question is “What does this warning about serialVersionUID mean”? All the advice out there basically is for developers who don’t know what’s going on to write code that will ignore errors when something unexpected happens. In my view - this is exactly the wrong approach. The safe way to act is to make sure that your program crashes if you don’t have control.
read morePosts
Teaser: Bare-knuckle SOA
I’m working on this idea, and I don’t know if it appeals to you guys. I’d like your input on whether this is something to explore further.
Here’s the deal: I’ve encountered teams who, when working with SOA technologies have been dragged into the mud by the sheer complexity of their tools. I’ve only seen this in Java, but I’ve heard from some C# developers that they recognize the phenomenon there as well.
read morePosts
How changing Java package names transformed my system architecture
Changing your perspective even a small amount can have profound effects on how you approach your system.
Let’s say you’re writing a web application in Java. In the system you deal with orders, customers and products. As a web application, your classes include staples like PersonController, PersonRepository, CustomerController and OrderService. How do you organize your classes into packages?
There are two fundamental ways to structure your packages. Either you can focus on the logical tiers, like com.
read morePosts
The Architecture Spike Kata
Do you know how to apply coding practices the technology stack that you use on a daily basis? Do you know how the technology stack works? For many programmers, it’s easy enough to use test-driven development with a trivial example, but it can be very hard to know how to apply it to the problems you face every day in your job.
Java web+database applications are usually filled to the brim with technologies.
read morePosts
Can we replace requirement specification with better understanding?
On larger projects, I’ve always ended up resorting to writing down a lot of detailed specifications, many of which are wrong, irrelevant or we might not be ready to answer them yet. On small projects, the dialogue between the customer and the developers can flow easy, and good things happen.
The quick analysis Developer: … so we’re going to complete the current task tomorrow or the day after. Could we discuss what to do next before you’re off to your next meeting?
read morePosts
What will Java 7 mean for you?
Oracle released Java 7 on July 28, 2011. This is nearly 5 years after the release of Java 6 in December 2006. The release received a lot of bad press, both because it is very meager on features, and because it shipped with a severe bug. Nevertheless, once the most serious bugs have been fixed, you might think about starting to use Java 7. What will this mean?
New language features Java 7 has a few new language features.
read morePosts
This dependency injection madness must end!
Or: Poor man’s dependency injection: Singleton-initialized field
As dependency injection frameworks like Spring have become central in software applications in the last few years, the conventional view is now that the Singleton pattern is evil and should never be used. Instead, relationships between objects in your system should be managed by a dependency injection container. I have started disliking the consequence of this strategy very much: All coupling in my system becomes implicit and harder to understand.
read morePosts
Video: No-red refactoring
The more I code, the more I’ve learned to appreciate keeping the code clean even during complex refactorings. By “clean”, I mean that the code always compiles and the test always run.
I often find myself in a situation where I have a method call that’s starting to accumulate parameters. Something like this:
showPersonCreateForm(writer, firstName, firstNameErrorMessage, lastName, lastNameErrorMessage,....); After three or four parameters, the need to refactor is starting to become evident.
read morePosts
Cross-cutting code, the homemade way
I though I’d do something different this time. Instead of describing something technical, I have recorded a five minute video that shows a very neat trick in Java: How to create a bit of code that wraps existing method calls to an object with any behavior you may desire.
This is nothing new, but I’ve noticed that not many developers know how to use it, so I hope this video may be useful:
read morePosts
Eclipse telepathy: Your IDE can guess what you want
Ctrl-1 is the magic “do what I think” button in Eclipse. Whenever I press it, Eclipse seems to come up with something that’s helpful in the current context. In this blog post, I illustrate 10 things that Eclipse hide under the ctrl-1 keypress. This is a follow up on my post on Eclipse stenography.
I got some comments on my last post about Eclipse stenography about the animated gifs. I know this can be annoying, but I considered the alternative: To have you mouse-over or click a picture to animate it.
read morePosts
How pair programming and test-driven development looks in real life
Pair programming and test-driven development are some of the practices that are most often talked about and least often actually understood. So I’ve decided to undertake the task to teach myself to program a simple, yet realistic problem with a pair programming partner. The goal is to create an entertaining and realistic performance that portrays what it feels like to work like this.
I’ve been extremely lucky. I’ve found not one, but two programmers that have been willing to train enough with me to make a smooth performance of a pair programming session.
read morePosts
Eclipse stenography: Create code faster
According to Wikipedia, stenography or shorthand is “is an abbreviated symbolic writing method that increases speed or brevity of writing as compared to a normal method of writing a language”.
Just as a stenographer learns to take down information really fast, a good programmer can learn to write code really fast by taking advantage of his or her tools. In this post I’ll show you my secret code stenography tricks.
read morePosts
Dynamic subclass APIs make Java seem young again
At JavaZone 2010 I will be giving a lightning talk on APIs that use dynamic subclasses. These APIs make it possible to do things in Java that seem like pure magic. Here are some ideas of what you can get from these APIs and a look under the hood, so you really understand what’s going on.
Mockito - “the best Java library named after a summery drink” Mocking is a hotly debated subject within testing camps.
read morePosts
Six ideas that improve your software design
“Design” is a verb, not a noun. If I want to create a good program, studying the process of getting there is much more important than the resulting software. This is why I use coding katas as a form of study. I find an interesting problem problem and then solve the same problem over and over again. In this blog post, I will focus on six principles of software design. I will illustrate each with a screencast from a kata.
read morePosts
Why TDD makes a lot of sense for Sudoko
My colleague Thomas sent me a very interesting link about attempts to solve Sudoku using test-driven development. The article, somewhat unfairly, pits Ron Jeffries’ explorations of Sudoku using test-driven development against Peter Norvig’s “design driven” approach.
I found both attempts lacking. However, while Ron Jeffries freely admitted that he didn’t even know the rules of Sudoku when he started, both Norvig himself and his readers fawn over his solution. I didn’t find it very understandable.
read morePosts
Why and how to use Jetty in mission-critical production
This article is a summary of a seminar I had on the topic. If it seems like it’s a continuation of an existing discussion that’s because, to some extent, it is. If you haven’t been discussing exchanging your app server, this article probably isn’t very interesting to you.
By putting the application server inside my application instead of the other way around, I was able to leap tall buildings in a single bound.
read morePosts
Using Eclipse Better
I’ve pair programmed the Java EE spike kata in Eclipse with a number of people, I’ve found that a number of keyboard short cuts and preference settings recur as useful new information. I’ve compiled the most popular ones in this article. The article is subject to change, but I won’t change the number of shortcuts.
Top five shortcuts There are some keyboard short cuts that everyone who uses Eclipse should know:
read morePosts
My first katacast
After seeing some of the great examples of coders working on practiced problems on KataCasts, I decided to try make my own. I am not happy with the pacing of the video. I’m about a minute too early relative to the music.
But I thought I’d post the video here, to see what you all think. Comments are welcome!
I hope the video will demonstrate how to use refactoring effectively to drive the design of a program.
read morePosts
Observations from katas
Lately, I’ve been working on two code katas, that is, programming exercises that I repeat until the motions are secure in my muscle memory. The katas I’ve chosen are:
Java EE Spike: An application that stores People with names to a database and lets me search for them. I’ve repeated this pair programming with several different programmers. Programmable Fizz Buzz: Create a sequence of numbers 1,2,fizz,4,buzz,fizz,… you know the one. And the twist: Make it programmable, so that for example numbers divisible by 7 should be replaced with “coconut”.
read morePosts
Å trene på Java EE
For å bli bedre må man trene. For å bli bedre med avanserte ting, må man forstå de grunnleggende tingene bra. For å vite hvorfor man bruker avanserte verktøy, må man prøve å jobbe uten dem. Derfor har jeg de siste ukene trent mange ganger på å lage en veldig enkel webapplikasjon i Java. For hele applikasjonen har jeg startet med å skrive testene før koden som implementerer funksjonaliteten.
Dersom du vil prøve deg på samme øvelse, inneholder denne artikkelen litt informasjon for å komme i gang.
read morePosts
Effective Enterprise Java at Øredev
Just three weeks ago, I was asked to step in for Ted Neward to give a tutorial at Øredev on Effective Enterprise Java. As I did not have time to get the tutorial materials printed, I present them here on the web for the participants and others.
1. Effect Enterprise Java architecture in 2009 Since the Effective Enterprise Java book was written, many of the topics regarding transactions, concurrency and shared state have been resolved.
read morePosts
Testing Servlets with Mockito
When I write Java-projects that produce web pages, I test on several levels. First, I use Jetty and WebDriver to test the result via http. (WebDriver even lets me test JavaScript!)
But for speed and agility, unit-level tests beat even the fastest integration level tests. Unit tests run much much faster, and lets me pinpoint problems much more accurately. As a general rule: If you introduce a bug, you want a unit test to be the one that sees it first.
read morePosts
Extreme Integration: The future of software development?
What will the daily experience of software development look like, say, five years from now? Have our current processes reached their peak, or will the world continue to change? Alan Kay said “the easiest way to predict the future is to invent it.” Here are some ideas of the future I want to invent: I hope it will be dramatically better than what we currently do.
[caption id="" align=“alignright” width=“240” caption=“Steel pipes (by monkeyc.
read morePosts
Unit testing tricks: Using unit tests to validate static code
In my current project, we use Flex as the user interface framework of choice. Flex has some nice features, but it takes a long time to build changes and start up, so it takes a while to validate our changes. Yesterday, we found a problem with one our UI components, and used JUnit to hunt down the same problem all over our code.
The problem was with tables. We had a table where we had set the percentage width of each column, but the total did not add up to 100%.
read morePosts
Unit testing tricks: Look ma, no setters!
Here’s a neat trick if you want set an object in a specific state in a unit test, but you don’t want to violate encapsulation:
@Test public void withdrawShouldReduceBalance() { Account account = new Account() {{ super.balance = 100; }}; account.withdraw(10); assertEquals(90, account.getBalance()); } @Test(expected=IllegalStateException.class) public void overdraftShouldThrow() { Account account = new Account() {{ super.balance = 5; }}; account.withdraw(10); } This seemingly magic code lets me have a protected (but sadly not private) field Account#balance.
read morePosts
How to stay ahead
This is a test case from my current project:
Scenario: Finish gathering information Given I have an open case And the case has a task "gather information from X" And the case has a task "gather information from Y" When the user confirms that task "gather information from X" is completed And the user confirms that task "gather information from Y" is completed Then the case should generate a new task "evaluate customer standing" It seems pretty run of the mill.
read morePosts
Refactoring on @Ignore
Doing the Code Dojo at Oslo XP meetup last Monday, I realized a new concept that I’ve been using unconsciously for a while: I only add to the structure of my system when I have a test that cannot be satisfied by the current design. The rules of test-driven development tells me to wait to create a more advanced design until I have a reason to do so. And that reason should be a failing test.
read morePosts
Planning by value
Agile development is easy to understand and hard to do. One of the hardest things to do is to base plans and actions on value instead of effort.
An article by Alistair Cockburn includes a story that illustrates the point:
A boy is behind on his German language home work. He now has to read ten stories and answer a set of question for each. He will be graded on the number of correct answers.
read morePosts
Five unit testing tips #4: Don't mock your way into accidental complexity
I’ve all but stopped using mock objects in my tests. The reason is that mocking have had a detrimental effect on the design of my systems. I’ve often ended up having the mocks trick me into adding a needless layer of indirection that does nothing except delegate to the next layer, just to satisfy the mocks.
For a while, I was wondering whether I was the only one with this problem, but then I saw this tutorial on JBehave, which so perfectly illustrates the problem I saw myself doing.
read morePosts
... but please do repeat me
The hard choice between duplication, paralysis and chaos A common programmer credo is “Don’t Repeat Yourself” (Pragmatic Programmer) or “Once and only once” (Extreme Programming). Like all credos, we risk following it even when it is not appropriate.
The larger truth is that we have choice between three evils:
We can duplicate our code, thus duplicating effort, understanding and being forced to hunt down twice. We can share code and affect everyone who shares the code every time we change to code to better fit our needs.
read morePosts
Five Unit Tests Tips #3: Parametrized test methods
The following is a trick I don’t use very often, but when I do need it, it comes in very handy. It’s a trick that many developers aren’t aware of, even though it’s been possible to do with JUnit at least since version 3.
Sometimes you want to have a lot of tests that are almost the same, but that contain different arguments. For example, for a yahtzee calculator, you might want to have the following tests:
read morePosts
Architecture as tidying up
[caption id="" align=“alignleft” width=“165” caption=“Unstructured picture”][/caption]
I recently started on a new project. Looking over the code base, I saw the familiar structure of many projects: Definitions of classes goes here, persistence logic goes over there, interfaces to the persistence logic goes this other place, code for transforming from one structure to another in yet another place and so on. This is common, neat, and unfortunate.
As an exercise to understand the architecture of this system, I decided to add some new functionality: Displaying some data to the user.
read morePosts
Simpler Java deployment?
“The service went down because another service running on the same application server went down.” “You can’t use the improved version of your programming language because you’re running on the same application server as some old applications.” “We can’t help you deploy your application on the application server, because we’re busy with some other application.”
If you’ve ever heard any of these statements, you’ve been victim to the accidental complexity of the application server.
read morePosts
Keep the build clean
Have you ever looked at a list of compiler warnings the length of an essay on bad coding and thought to yourself: “You know, I really should do something about that… but I don’t have time just now”? On the other hand, have you ever looked at a lone warning that just appeared in a compilation and just fixed it?
When I start a new project from scratch, there are no warnings, no clutter, no problems.
read morePosts
Programmers who write tests get more time to program
I became a programmer so that I could spend time creating software by programming. I don’t want to waste my time managing low-quality code.
Does your code work the first time your test it out? Mine certainly never does. So if I hand over the code to someone else, I’m sure to get a bug report back that will take up my valuable programming time. This much is obvious to most developers.
read morePosts
What you didn't think you needed to know about hashCode and equals
This article is a repost of my comments to the question on how to implement hashCode and equals on stackoverflow
There are some issues worth noticing if you’re implementing hashCode and equals for classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate. If you didn’t think this topic is stupidly overcomplicated already!
Lazy loaded objects are subclasses If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store.
read morePosts
Verbose logging will disturb your sleep
When I encounter a system that has already been in development or production for a while, the first sign of real trouble is always a dirty log. You know what I’m talking about. When clicking a single link on a normal flow on a web page results in a deluge of messages in the only log that the system provides. Too much logging is as useless as none at all.
read morePosts
Video of my JavaZone talk about Continuous Integration
The videos from JavaZone are up.
Here’s my talk about Extending Continuous Integration, which talks about how I automatically run system level integration tests after every build.
read morePosts
Five Unit Test Tips: #2: Change your code to make testing easier
It’s been a while since I promised to write top five unit testing tips, so I guess I should better start writing #2. As with my first example this one is based on a real-life story.
Your code is worth nothing if it can’t be tested. Change your code to make it more testable.
In my last project, we used a pipes and filter architecture, with messages being passed forward through a chain of services.
read morePosts
The best way to clean things up is to avoid them getting dirty in the first place
Warnings are useful. You get warnings from your IDE when you write something that might be a bug. You have probably made your program print out warnings or error messages when something goes wrong.
But too often, we down in the sheer volume of warnings. Then it’s impossible to separate the relevant and important warnings from the noise.
To make warnings useful again, I use a zero-warning tolerance policy. Even if the warning is irrelevant, I fix it.
read morePosts
JBehave 2.0 released
I’ve learned the value of dealing seriously with connecting requirements to the actual code. The JBehave project started work to make formal, “business friendly” requirements into executable specifications, but due to limitations in Java, it was very clunky to use. JBehave 2.0 has just been released, and it has a much better model.
Here’s a specification:
Story: Play Tabs As a music fan I would like to convert guitar tabs to music So that I can hear what they sound like Scenario: My My Hey Hey Given tab e|--------------------------------- B|--------------------------------- G|--------------------------------- D|----------0--0------------------- A|-0--2--3----------2--0-----0--0-- E|------------------------3-------- When the guitar plays Then the following notes will be played A0 A2 A3 D0 D0 A2 A0 E3 A0 A0 The scenario is connected to Java code.
read morePosts
Five Unit Test Tips: #1: Use the data store
I’ve looked over some of my code lately, and found ways that I often improve my tests. I’m planning on writing a blog post for each of my five favorites.
First out: Using the data storage. I upgraded our API for billing customers. I had a few compilation errors in my code, as the API had changed somewhat. After fixing these errors, I was left with a test that broke mysteriously with a MethodNotFoundException.
read morePosts
A small library to test persistent objects
When the building blocks of your program fail and you don’t notice, the problem can be very hard to diagnose. In most of my projects, the building blocks are the persistent objects. Using Hibernate makes it easy to create a data access layer, but if you don’t watch out, errors can sneak into equals or hashCode, bidirectional relationships or properties that for some reason don’t get persisted correctly. Or the code you use to search for your objects can be wrong.
read morePosts
[link] Package by feature
Stand up and be counted. Which one do you think is best of the following?
Package by layer:
com.app.controllers com.app.model com.app.repositories com.app.exception Or package by feature:
com.app.orders com.app.invoices com.app.products I recently added a new site to my RSS reader. John O’Hanly just published a though provoking article about harmful java code idioms on JavaWorld. I don’t agree with everything he suggests, but I do find his point about “Package-by-layer: Preventing the use of package-private scope” very intriguing.
read morePosts
Testing: Avoid setUp and tearDown
In Let your examples flow, Dan North describes how “Don’t Repeat Yourself” (DRY) isn’t necessarily the most important guideline for tests. While I agree with his conclusions, I think the DRY principle is still extremely important for tests.
Dan’s point is that the most important attribute of tests is that they can be read like a story. “Store a page with the text ‘foo’ in the database, simulate a web request, check that the word ‘foo’ is present in the response”.
read morePosts
Some FitNesse tricks: Classpath and debugging
On my project, we use Maven to build our software and FitNesse to write functional specifications. However, it was obvious that FitNesse wasn’t designed by Maven-fans. When I use Maven, I already have control over my classpath, and specifying it in every FitNesse test gets to be old really fast. Why can’t I just inherit the project class path, and start FitNesse using maven-antrun-plugin or just from my IDE?
I found a neat way to implement this by overriding FitNesse.
read morePosts
Quality code starts with the details of the language
The code I write in Ruby is higher quality than the code I write in Java. Why? Because the language supports better abstractions. It lets me express a problem once, and reuse it many places. The strength of an environment comes from the quality of the libraries, and the qualities of the libraries comes from the features of the language. In this post, I will review a proposal to make Java a better language: First-Class Methods.
read morePosts
Lightweight Container Life Cycle
My talk at JavaZone went surprisingly well. The fact that the projector went dead and that I was planning on opening with a demo raised my pulse, but I felt I managed to get my message across and that people were happy.
The talk was about how we use Jetty to manage the full deployment life cycle of our application. I explained how we had implemented this and what problems we had solved.
read morePosts
Evil Behavior with Unchecked Checked Exceptions
Anders Nordås shows how to throw a checked exception without declaring a throws clause. The method uses some inherently evil mechanisms (the name of the class “sun.misc.Unsafe” should be a tip of), and like Anders says, this should probably never be used in production. Basically, calling sun.misc.Unsafe.throwException will throw a checked exception without alerting the compiler. The exception is not wrapped, but it cannot be caught by its class name, as it is not declared.
read morePosts
A Hopeful Idea: The End of Checked Exceptions?
Java.net’s latest poll asks: should checked exceptions be removed from the Java language. Sadly, the poll is not going the way it should right now. Many people feel checked exceptions are key to reliable programming. They are wrong. Please: Read this post, and help improve the Java programming language by voting “Yes” to remove checked exceptions.
Checked exceptions is a concept that is unique to Java as a programming language. That is right: It was an experiment.
read morePosts
What makes a test suite good?
Many people enjoy splitting testing up in a myriad of test types: Acceptance Tests, Functional Tests, Integration Tests, Performance Test, Technical Tests, Unit Tests. I have myself been guilty of such terminology as “embedded integration tests” and “requirement tests”. However, what unites the tests are more important than what divides them. The divisions are fuzzy, and they should be.
All tests have but two purposes: To tell you if you’ve completed a new requirement, and to ensure that you haven’t broken something that worked.
read morePosts
The Maven Application Server
After spending more time than I care to indulge trying to get commercial application servers to behave, I finally decided to Do the Simplest Thing that Could Possibly Work, and create a new application server from scratch. Well, not really a full application server. For 90 % of the Java applications out there, all that you really need is Servlets, so I limit myself to that. And not really from scratch.
read morePosts
Spring - You've Failed Me
Last night, I worked until after midnight trying to get our application up and running after some seemingly inconsequential changes in Spring-XML configuration. Our application consists of a total of 32 modules (including 6 wars and one “server” module that packages them, and 11 modules that are shared with other projects). Most of these modules have Spring-XML fragments that are included in a few different ways, with the result that a nobody on the team actually understands how it fits together.
read morePosts
A Brief Adventure with Universal Repositories and REST Web Services
Inspired by Per Mellqvist (and myself, to be fair), I wanted to explore the possibility of using a generic DAO or Repository interface for REST. Based on this simple idea, I was able to create a very cute and testable prototype of a full Web Service stack for REST based Web Services. The most interesting aspect was creating a universal test case for Repositories.
This article shows how little code is required to implement and test a REST based Web Service in Java, despite the horror of the Java HTTP client API.
read morePosts
commons-logging: you're on notice!
Hey, commons-logging team, you’re on notice!
Here is a dump of the Maven 2 dependencies from the project I use for my article on embedded integration testing:
no.brodwall.demo:web-demo:war:1.0-SNAPSHOT org.springframework:spring:jar:2.0.1:compile _commons-logging:commons-logging:jar:1.1:compile_ avalon-framework:avalon-framework:jar:4.1.3:compile javax.servlet:servlet-api:jar:2.5:test **_javax.servlet:servlet-api:jar:2.5:compile_** logkit:logkit:jar:1.0.1:compile log4j:log4j:jar:1.2.12:compile Never mind the fact that commons-logging was meant to be a thin facade on top of other logging frameworks. commons-logging 1.1 actually include compile dependencies on: log4j, servlet-api, avalon-framework, and logkit! servlet-api!?! WTF!?
Maven 2 is extremely susceptible to bad POMs because dependencies are resolved transitively.
read morePosts
Superceeded Article: Embedded Web Integration Testing with Jetty
Do you speak test? In that case: Hello web application:
public class WebIntegrationTest extends net.sourceforge.jwebunit.WebTestCase { public void testIndex() { beginAt("/index.html"); assertTextPresent("Hello world"); } private org.mortbay.jetty.Server server; protected void setUp() throws Exception { server = new org.mortbay.jetty.Server(0); server.addHandler( new org.mortbay.jetty.webapp.WebAppContext("src/main/webapp", "/my-context")); server.start(); int actualPort = server.getConnectors()[0].getLocalPort(); getTestContext().setBaseUrl("http://localhost:" + actualPort + "/my-context"); } } This code runs with no application server, no separate deployment step, just like that.
If this looks interesting, see my full-sized article on java.
read morePosts
The java.util.Map DAO
The more I code, the fewer dependencies I am willing to create.
For example, I used to have a common super interface that all persistent objects must inherit from in order to have an id-field. I used to have a common DAO interface that all DAOs implemented. But these add hard dependencies in my code.
Hiding the super interface for all entities was easy. Doing away with the DAO is harder.
read morePosts
Integration testing: Many-to-one relationships with select-fields
This post is an entry in my ongoing series about web integration testing with Jetty. See post 1, 2 and 3 in the series for more information.
I often find that a web interface needs to let a user select one of a list of objects as a relation to the object he is editing. This is the basic and simple way of dealing with many-to-one relationships. However, most web frameworks don’t make this as easy or well-documented as it should be.
read morePosts
Integration testing: Validation and relationships
In my previous two posts about integration testing with jetty [1][2], I have showed how to test a simple web application with Jetty and how to expand this application with a fake DAO implementation to test display and updates of data through the web interface. In this penultimate post, I will describe how to work with more advanced edit scenarios.
Most web applications have some degree of requirements for validation of input and a bit more advanced data structure than the one we’ve worked with so far.
read morePosts
In-process Web Integration Tests with Jetty and JWebUnit
Do you speak test? In that case: Hello web application:
public class WebIntegrationTest extends net.sourceforge.jwebunit.WebTestCase { public void testIndex() { beginAt("/index.html"); assertTextPresent("Hello world"); } private org.mortbay.jetty.Server server; protected void setUp() throws Exception { server = new org.mortbay.jetty.Server(0); server.addHandler( new org.mortbay.jetty.webapp.WebAppContext("src/main/webapp", "/my-context")); server.start(); int actualPort = server.getConnectors()[0].getLocalPort(); getTestContext().setBaseUrl("http://localhost:" + actualPort + "/my-context"); } } This code runs with no application server, no separate deployment step, just like that.
If this looks interesting, see my full-sized article on java.
read morePosts
Transparent encryption with Hibernate
The security people at my were suggesting that we needed to create an encryption service, to securely store passwords so that even rogue DBAs could not get at them. The idea is that no matter how good your access is to the database, you shouldn’t be able to decrypt the passwords unless you have the secret key. In a solution like this, the key is generally stored offline with the application and loaded into memory sometime during startup.
read morePosts
developerWork: Don't Repeat the DAO
I am happy to see others express positive opinions about universal DAO interfaces in Java. Per Mellqvist writes in developerWorks: “Don’t Repeat the DAO” about creating a GenericDao interface:
public interface GenericDao <T, PK extends Serializable> { /** Persist the newInstance object into database */ PK create(T newInstance); /** Retrieve an object that was previously persisted to the database using * the indicated id as primary key */ T read(PK id); /** Save changes made to a persistent object.
read morePosts
Hello Lazy Loading
Due to popular demand, I will post a very short version of my Lazy Loading article:
Why? Because this is bad:
Category category = dao.get(1); Category parent = dao.get(category.parentId); int sumChildValue = 0; for (Long childId : parent.subcategoryIds) { sumChildValue += dao.get(childId).getValue(); } System.out.println(sumChildValue); This is good:
Category category = dao.get(1); int sumChildValue = 0; for (Category sibling : category.getParent().getChildren()) { sumChildValue += sibling.getValue(); } System.out.println(sumChildValue); And this is better:
read morePosts
The Joys and Sorrows of Exceptions
Updated for republication in Mr Bool
In my experience, the most serious bugs in programs in production are in error handling routines. Inventive programmers often try fancy things when dealing with errors, but error situations are often omitted during testing. This article examines the fundamental questions of exceptions: What causes exceptions, and what can be done with them?
Bad User, Bad Server, or Bad Programmer Practices of an Agile Developer puts exceptional events into three categories:
read morePosts
Lazy Loading on Java.net
My article series on Lazy Loading will be published on java.net tomorrow. In relationship to the publication, I am taking down the original articles from my blog. Please go to Java.net for to read about lazy loading.
Update: The article was just posted last Tuesday. I have updated the links in this post.
read morePosts
Top 5 Reasons .NET is Better Than Java
Attributes. Keeps getting better ’n better. Check out Extensible C#, Clemens Vasters new demos, and the underutilized ContextBoundObject ADO.NET. The ADO.NET model for modeling and transporting data hits right on the spot. Better FFI. P/Invoke wins against JNI, hands down (too bad it is probably overused, though) Not EJBs! Getting rid of the defunct EJB model saves a lot of headaches. Better UI. For the user, that is, not the developer!
read morePosts
Top 5 Reasons Java is Better Than .NET
Open Source Community. The number of excellent open-source tools for Java is staggering. Look at HSqlDb, BeanShell, Eclipse, Recoder, JGraph, Tomcat, JBoss, and many more. More importantly, the Java community has proven much more interested in doing it the open-source way. Eclipse. Already mentioned, but it deserves a point of its own. Eclipse is a better IDE than VS.NET! Checked Exceptions. Less Native Code & more code reliability. .NET still has some weird crashes.
read more