Groovy: Creating an Interface Stub and Intercepting All Calls to It
Continue reading →
Most interesting links of October
Recommended Readings
- Steve Yegge's Execution in the Kingdom of Nouns - I guess you've already read this one but if not - it is a well-written and amusing post about why not having functions as first class citizens in Java causes developers to suffer. Highly recommended.
- Reply to Comparing Java Web Frameworks - a very nice and objective response to a recent blog summarizing a JavaOne presentation about the "top 4" web frameworks. The author argues that based on number of resources such as job trends, StackOverflow questions etc. (however data from each of them on its own is biased in a way) JSF is a very popular framework - and rightly so for even though JSF 1 sucked, JSF 2 is really good (and still improving). Interesting links too (such as What's new in JSF 2.2?). Corresponds to my belief that GWT and JSF are some of the best frameworks available.
- Using @Nullable - use javax.annotation.Nullable with Guava's checkNotNull to fail fast when an unexpected null appeares in method arguments
- JavaOne 2011: Migrating Spring Applications to Java EE 6 (slides) - nice (and visually attractive) comparison of JavaEE and Spring and proposal of a migration path. It's fun and worthy to see.
- xUnitPatterns - one of the elementary sources that anybody interested in testing should read through. Not only it explains all the basic concepts (mocks, stubs, fakes,...) but also many pitfalls to avoid (various test smells such as fragile tests due to Data Sensitivity, Behavior Sensitivity, Overspecified Software [due to mocks] etc.), various strategies (such as for fixture setup), and general testing principles. The materials on the site were turned into the book xUnit Test Patterns: Refactoring Test Code (2007), which is more up-to-date and thus a better source.
- Eclipse tip: Automatically insert at correct position: Semicolon, Braces - in "while(|)" type "true {" to get "while(true) {|" i.e. the '{' is moved to the end where it belongs, the same works for ';'
- Google Test Analytics - Now in Open Source - introduces Google's Attributes-Components-Capabilities (ACC) application intended to replace laborous and write&forget test plans with something much more usable and quicker to set up, it's both a methodology for determining what needs to be tested and a tool for doing so and tracking the progress and high-risk areas (based not just on estimates but also actual data such as test coverage and bug count). The article is a good and brief introduction, you may also want to check a live hosted version and a little more detailed explanation on the project's wiki.
- JSF and Facelets: build-time vs. render-time (component) tags (2007) - avoid mixing them incorrectly
- StackOverflow: What are the main disadvantages of Java Server Faces 2.0? Answer: The negative image of JSF comes from 1.x, JSF 2 is very good (and 2.2 is expected to be just perfect :-)). Nice summary and JSF history review.
- Ola Bini: JavaScript in the small - best practices for projects using partly JavaScript - the module pattern (code in the body of an immediately executed function not to polute the global var namespace), handling module dependencies with st. like RequireJS, keeping JS out of HTML, functions generating functions for more readable code, use of many anonymous functions e.g. as a kind of named parameters, testing, open questions.
Continue reading →
JSF: Beware the Difference Between Build-Time and Render-Time Tags in Facelets
A typical mistake is the nesting of ui:include (build-time) inside ui:repeat (render-time) using the var that ui:repeat declares:
Continue reading →
Never Mix Public and Private Unit Tests! (Decoupling Tests from Implementation Details)
Continue reading →
Hacking A Maven Dependency with Javassist to Fix It
The process is as follows:
- Phase process-sources - maven-dependency-plugin unpacks the dependency to classes/
- Phase compile (implicit) - compile the bytecode manipulation code
- Phase process-classes - exec-maven-plugin executes the compiled Javassist instrumenter to modify the unpacked classes
- Phase test - run tests on the instrumented code
- Phase package - let maven-jar re-package the instrumented classes, excluding the instrumenter itself
Continue reading →
Only a Masochist Would Write Unit Tests in Java. Be Smarter, Use Groovy (or Scala...).
I like writing unit tests but Java doesn't make it particularly easy. Especially if you need to create objects and object trees, transform objects for checking them etc. I miss a lot a conscise, powerful syntax, literals for regular expressions and collections, conscise, clojure-based methods for filtering and transforming collections, asserts providing more visibility into why they failed. But hey, who said I have to write tests in the same language as the production code?! I can use Groovy - with its syntax being ~ 100% Java + like thousand % more, optional usage of static/dynamic typing, closures, hundreds of utility methods added to the standard JDK classes and so on. Groovy support for example in IntelliJ IDEA (autocompletion, refactoring ...) is very good so by using it you loose nothing and gain incredibly much. So I've decided that from now on I'll only use Groovy for unit tests. And so far my experience with it was overwhelmingly positive (though few things are little more complicated by the positives more than compensate for them). Read on to find out why you should try it too.
(The arguments here focus on Groovy but I guess similar things could be said about JRuby, Scala etc. - with the exception of Java code compatibility, which you only get in Groovy.)
Few examples
Some of the example below use some Groovy magic but don't be scared. You can write Groovy just as if it was Java and only learn and introduce its magic step by step as you need it.Bean construction:
def testBean = new Customer(fname: "Bob", sname: "Newt", age: 42)
// Java: c = new Customer(); c.setFname("Bob"); c.setSname("Newt"); c.setAge(42);
(Of course this starts to pay of if either you don't want to create a constructor or if there are "many" properties and you need to set different subsets of them (constructor with 4+ arguments is hard to read).)
Reading a file:
assert test.method() == new File("expected.txt").getText()
// Java: buffered reader line by line ...; Note: == actually uses equals()
Checking the content of a collection/map:
assert customerFinder.findAll().collect {it.sname}.sort() == ["Lizard","Newt"]
// Java: too long to show here (extract only surnames, sort them, compare ...)
assert getCapitalsMap() == ["UK" : "London", "CR" : "Prague"]
Regular expressions:
assert ("dog1-and-dog2" =~ /dog\d/).getAt([0,1]) == ["dog1", "dog2"]
- Or more fail-safe regexp:
assert ("dog1-and-dog2" =~ /dog\d/).iterator().toSet() == ["dog1", "dog2"].toSet()
- With a match group:
assert ("dog11-and-dog22" =~ /dog(\d+)/).iterator().collect({it[1]}).toSet() == ["11", "22"].toSet()
Continue reading →
Comparison of Eclipse 3.6 and IntelliJ IDEA 10.5: Pros and Cons
For the impatient:
IntelliJ is a very good tool, its killing feature for me is its excellent support for other languages such as Groovy (e.g. for unit tests) and Clojure. Many details are more worked-out and with a higher usability then in Eclipse, f.ex. search & replace with match highlighting and replacement preview. Its support for navigability and refactoring across multiple languages (Java, JSP, JSF, HQL, Spring config in my case) is also an absolutely great feature for productivity. And of course I have to add it credits for being a Czech product [1] (interestingly enough, NetBeans also comes from the Czech Republic [2]; it's a pity Eclipse hasn't this link too) :-).
My main issue with IntelliJ is its performance. First, running tests is slow because IntelliJ only does (re)compile the test/source when you hit the run button as opposed to Eclipse' incremental compilation. And that makes TDD very painful. (I tried to use the old Eclipse Mode plugin but it has problems with IntelliJ 9/10.) Second, sometimes the UI freezes* and you have to wait seconds or tens of seconds for it to respond again (even after disabling most plugins and some analysis). It doesn't happen too often but often enough to be noticed, to be annoying, and to interrupt the development flow.
*) Update: UI freezes may be a specific issue of Mac 64b 1.6 JDK
So I guess I'll use either Eclipse or IntelliJ with respect to the needs of the project at hand and hope for IntelliJ to resolve its performance issues (as NetBeans did).
Continue reading →
Intro: Java Webapp Monitoring with Hyperic HQ + How to Alert on Too Many Errors in Logs
Continue reading →
hasProperty, the Hidden Gem of Hamcrest (and assertThat)
assertThat
Continue reading →
Aggregating Error Logs to Send a Warning Email When Too Many of Them - Log4j, Stat4j, SMTPAppender
Continue reading →
Spring: Make an Externally Created Object Available to Beans in applicationContext.xml
Java: Configure ApplicationContext with an Injected Bean
Continue reading →
Tools for Renaming the Package of a Dependency with Maven
- Uberize plugin (latest - org.fusesource.mvnplugins:maven-uberize-plugin:1.20) - originally inspired by the Shade plugin, intended to overcome some of its limitations. Intended primarily to merge your code and dependencies into one jar.
- Shade plugin
- package-rename-task, Ant-based Maven plugin - I'm not sure whether this is further maintained
Continue reading →
Note to Self: Running GroovyConsole with a Maven Project's Classpath
Continue reading →
Most interesting links of September
Recommended Readings
- J. Yip: It's Not Just Standing Up: Patterns for Daily Standup Meetings - it isn't easy to make stand-up meetings short, focused, energizing, and centered around continuous improvements and team spirit. This description of an example good standup, the meeting's goals, and especially the "patterns" and "bad smells" can be pretty useful to get and keep on the track towards a brighter future. TBD: standup goals: GIFTs, team spirit, appreciation where we go and are.
- M. Poppendieck: Don’t Separate Design from Implementation - according to Mary, (detailed) requirements - being it in the form of (backlog) user stories or any other - represent actually a design of the system, which shouldn't be done by the amateur product owner/business analyst but by professionals, meaning the developers, based on high-level goals and clear specification of the desired business value. She writes about a project that her factory outsourced and which she could have designed but didn't - yet it succeeded even though there were no detailed requirements. I've also read and unfortunately lost an interesting answer where the author argues that that is only possible if the developers are really experienced in the field. I tend to agree more with Mary though it is of course a question what "high" and "low" level goals/requirements are. But undeniably users/analysts tend to propose solutions disguised as requirements while often missing the technical insight to see possible other and better solutions. We also cannot expect the developers to produce a great SW if the true goals, needs, and business values behind the requested "features" aren't clearly communicated to them. (The best example - lost source again - is where a developer proposes to the client a simple process change that will solve the problem without writing a single line of code.)
- Mike Cohn: The Forgotten Layer of the Test Automation Pyramid - three levels of testing with increasing number of tests: UI/Service/Unit (or end-to-end instead of UI), each requiring a different approach. Unit tests are best because a failure points directly to its source (with higher level tests you don't immediately know the cause). The higher in the pyramid, the less tests we should have (e.g. because of their redundancy). It's important not to forget the middle, service layer - unit tests are too low-level, UI tests too difficult and brittle. Also Gojko in Specification by Examples says that acceptance/BDD tests should run mainly at the service layer because of the UI level issues. "Although automated unit testing is wonderful, it can cover only so much of an application’s testing needs. Without service-level testing to fill the gap between unit and user interface testing, all other testing ends up being performed through the user interface, resulting in tests that are expensive to run, expensive to write, and brittle." [Emphasis JH.]
- Technical Debt and the Lean Startup - Paul Dyson remarks that while quality is an essential concern for projects in established environments, in the case of lean startups the primary goal is to find out whether a product is viable and what it should be like and thus it's reasonable to accept much higher technical debt by not spending too much time on ensuring scalability, de-duplication etc. - only when the product proves viable should we start to care for its long-evity by emphasizing the quality. But one thing can never miss and that is good test suite because this is the crucial factor that makes letter payment of the technical debt possible without ruining oneself.
- Coding dojo - Real time coding competition with Extreme Startup - an inspiring report about a coding dojo lead by Johannes Brodwall in Bergen's JUG, the task being the implementation of a server that can respond to questions send over HTTP (that's all participants know at the beginning - they learn the rest during the iterations)
- Using Code Katas to Improve Programming Skills - why to use code katas + links to different proposed katas
- Kent Beck: Don’t Cross the Beams: Avoiding Interference Between Horizontal and Vertical Refactorings - when to do depth-first (more exploratory) refactoring and when to extend it into breadth (i.e. apply it to several similar objects)
Continue reading →
Inspect Your Webapp in a Live Environment Interactively with GroovyConsole
Here is a screenshot of my recent troubleshooting session, where I needed to check the state of a session-scoped JSF Managed Bean:
Continue reading →