Feb 04 2011

Interview Question – Name Five reasons Java is not Object Oriented?

Category: Java,Software DevelopmentPhil @ 12:53 pm

I thought it would be a really good idea to share interesting interview questions, especially the ones that caught me off guard!

I found this title to be a very interesting question… I’m not sure it was intended as an open-ended question, as I don’t think there is a right or wrong answer. It really depends on your perspective. Are you looking at it from a purely technical or logical (modeling/solution) perspective?   Even though I might be considered very technical, I prefer to stay out of the really low level stuff. Sure it is fun, to get down to the bare metal once in a while, but I get more enjoyment out of the thought process. Claiming to be a very Object Oriented person and stumbling on this question really bothered me… I came home and did some Googling, but really never found the answers that seemed to live up my expectations. Next, I sent an mail to one of my pals who just loves the nuts and bolts… In his typically witty way, he rattled off: int, float, boolean, double, long, and char. A completely valid answer! He then have me six other bullets which I have merged into the table below and tried to expand upon.

Reason Explanation
Primitives The interviewer lead me with this one, which it is actually pretty obvious when you think about it! This is really not disputable, primitives are not truly objects. I think for historical reasons, namely performance and ease of use, developers were pushed to primitives. With modern JVMs and Java 1.5 autoboxing, I feel like this flaw is slightly minimized. However, from a purest OO perspective this is a valid reason.
Constructors The interviewer also talked about the limitation where constructors can only return an instance of itself, the specific class; which has lead to the creation of factory patterns and DI frameworks. Having been a Spring Framework fanatic for so many years, I have probably developed a different style of programming which as shielded me from this issue. With some of the more  dynamic OO languages, you can apparently return a different type instance from the constructor. I need to study some more on this, but did find an interesting Ruby thread.  Ruby is definitely on my learning list, so I have to stop blogging!
First Class Objects This reason takes us to pure object orientation. I’m going to gloss over this a little and let you read more on your own as I did today, try this simple search. One of the more obvious distinctions, would probably be the meta data / class model provided by Java.
Statics This is actually one of my pet peeves. I am a no fan of static methods.  For me it is simple, statics equal functions which equal non object oriented. I have always bought into the DI propaganda which states that static objects and methods are untestable, which I fundamentally agree with. However, I did recently discover there are are several mocking frameworks that can actually mock out static classes and methods. This is pretty cool, but unnecessary in my preferred design and implementation style.
No Multiple Inheritance Coming from a C++ background, this was always a big discussion point. I generally did not recommend multiple inheritance, as it was tricky and usually implemented (and even modeled) inappropriately. I was much more interested in inheriting behavior rather than state. If I remember correctly, this is where it got interesting using C++.  Java Interfaces do a little bit to address this issue, but there is typically no why to elegantly solve the problem without a little code duplication and/or helper classes.
Strings My nuts and bolt friend gave me this one; not sure where he was going, but obviously the Java String class is its own unique creation. Personally, I was always bummed by the lack of a mutable String class. I might have prefer to see non-mutability implemented via subclasses, or something like the Collections.unmodifiableCollection() method. How about that, another static method reference! Maybe this would have been a little better, stringInstance.getImutable()!
Limited Operator Overloading Having done a lot of C++ in my early programming career, I found elegance in operator overloading and saw it as a void in Java. But, I do have to agree with the reason it was left out of Java, “it was used incorrectly to many times in C++”. Unfortunately, you can use any tool incorrectly; it might have been nice to let us decide if and how to use some of these features, rather than eliminate them. I did find an interesting thread on StackOverflow, so I will keep my thoughts short!
JNI This was another bullet from my nuts and bolt friend. In my opinion, JNI was more of a Java after thought, “bolted-on” to simply to take advantage of existing solutions and provide some level of extensibility. I have not used JNI for many years, and all I can remember is procedural nature of our solution. I don’t remember details, other than it was ugly! You could also say that ugly is not object oriented!
Package Level Scope Late breaking addition. I personally never liked the “package” level scoping provided by Java.  How is this object oriented? You are basically breaking the class level encapsulation, allowing all classes in that package access… This always felt like a little implementation hack to me… not one of my favorites!

My thoughts might not be completely baked, but I need to keep on moving; so please let me know if you think I missed the point! Generally speaking, I have been very happy with Java as a implementation language. All languages have their warts, and Java is no different. The vast number of tools and frameworks allow Java applications to be effectively developed, tested, and deployed.  I also believe that Java is pretty forgiving, allowing developers of all levels to build solutions; from being barely object oriented to insanely obscure. Hopefully, we end up in the middle with simple elegance. I hope to have the opportunity to explore some of these Java flaws in a Ruby, so please check back and see what I have learned!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Nov 22 2009

Self-Documenting Code… Interesting thoughts about comments…

Category: Java,Software DevelopmentPhil @ 2:30 pm

I recently found an interesting web site called Making Good Software. I really liked this guy’s site, he might just save me from writing down a lot of my own thoughts! Unlike my typical post, his are very short and easy to read. I highly recommend checking it out and popping through his other recent posts too. Nothing revolutionary, but just great reminders of how we should be thinking as we write new software. The following blog entries caught my attention:

The Comments are Evil statement really hit home with me… I have always said that code should basically be self-documenting. This statement is usually frowned upon some developers and managers; some people might think I’m just lazy. Farthest thing from the truth! By enforcing good coding practices with automation like Checkstyle, PMD, and FindBugs, combined with placing a high value on class and variable names, placing logic in the proper place, and keeping methods and classes small, most comments are redundant and typically provide little value. It was very interesting how the author associated comments with the DRY (Don’t Repeat Yourself) principal. Interesting thought, when your comments simply repeat what the code is already saying!

I also place a huge value on refactoring. I borrowed the image at the right to further highlight the point. There are many articles on the “Red Green Refactor” approach worth reading, helping to tie this all together. I guess one of my personal goals is always to create that elegant (simple and clean) solutions, which never happens the first time! Looping through R-G-R a few time helps achieve that elegance, and you end up with code that requires less comments.

Some of the comments in the Making Good Software blog are very interesting has well; many people throwing in their two cents, both pro and con on the value of comments. The author also states that comments cannot be completely eliminated. The code we write is never perfect and probably needs a little extra context to explain the hopefully infrequent imperfections.  I think the bottom line is to focus on quality code; eliminate the obvious, limited value comments, and comment the pieces that are truly intricate. If you are writing a lot of comments, then you better go back and look at your design, as something is probably not quite right.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Nov 09 2009

NetBeans Unit Test Creation better than Eclipse? And where should unit test live?

Category: Eclipse,Java,TestingPhil @ 5:00 am

I seem to work on a variety of Java applications and find that unit testing is one of the most varied (implementation-wise) pieces of the development process. These applications, created by different development staffs, many which have evolved over the pass few years are all very unique… kind of makes me wonder why? That is a topic for another post!

One debate I always seem to encounter is around where to actually save the unit tests? Should we do in-package testing or rely on the public API. My preferences are pretty simple:

  • Unit test should not be stored with the code, but rather created under a secondary source root. On my early projects, I created a sub-package under each package, called test, to manage the relevant files (tests and data). I later realized that I could simplify the Ant build process and enable in-package testing by creating a separate source tree. I have seen projects commingle the actual source code, unit tests, and even the test data files, all within the single source tree. This defaults the testing strategy to in-package testing, and discourages (or even prevents) API testing. I find this approach rather messy and unclear. This approach also complicates the Ant build process; at some point during the process, the unit tests, supporting classes and files should be separated from the actual deployable content.
  • I like to name my secondary source root tdd. I know it is not widely practiced, but my hope is that if the developers see that TDD directory every time the open up their IDE, the concept might actually wear off! Maybe someday, one developer (hopefully more) will actually be challenged to write their unit tests first. With Eclipse and jUnit 4.x annotations, I seem to always start with my unit test, and sometimes even refactor code from the unit test into the actual class; kind of a high-bread TDD process, but the thought is always there!
  • I also prefer the public API testing strategy verses in-package testing. This line of thinking always takes me back to the Testability Explorer. The concepts behind this metric enforce the idea public API testing and is worth a quick read. Add the Spring Framework to the mix, enabling dependency injection and I see little need for in-package testing. This is typically accomplished by creating a “test” package as the root of the secondary source tree, with sub-packages reflecting the package hierarchy of your classes to be tested. I truly believe that defaulting to in-package testing allows the developers to be very sloppy and even unaware that they are testing a specific internal implementation, rather than externalized behavior presented by the API… This is VERY bad practice in my opinion.
  • If there is a need for in-package testing, then the sub-package structure of the classes to be tested can be recreated under the secondary source tree, maintaining a clean separation between the source and test cases. These test should be considered an exception to the norm, rather than common practice. I would hope for a 90-10 or 80-20 ratio, with a majority of the test falling under the test package root (in-package is the minority).

I am kind of tied to Eclipse as my IDE, but do play with NetBeans every so often. I think I could switch to NetBeans, my only real requirement is that the IDE must have Emacs key bindings; some habits are just too hard to break! NetBeans looks like an pretty good tool and seems to be very responsive on my Ubuntu box; I especially like the way it manages plug-ins.  One interesting thing that NetBeans does (maybe a little better than Eclipse), is manage unit testing. NetBeans will automatically create the secondary source tree, but seems to default to in-package testing. It is very easy to add the additional test package into the package structure to enable API testing. I also like the way that NetBeans separates the Test Libraries from the regular Libraries. I’m not sure how well this would work when you use a tool like Ivy, but does make it more obvious, as to which libraries are used for execution verses unit testing… If you do happen to generate a unit test from an existing class, NetBeans will generate more code than Eclipse. I’m not sure how useful this code is, but it does try to create the object under test, invoke the get() methods and perform assertions on the returned values. Might be more noise that it is worth, and anyway, you should be writing the unit test first!

The bottom line is that Unit testing should be easy and valuable. If it becomes too hard or complicated, it might be time to re-address how the unit test strategy is being implemented.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Oct 19 2009

Spring Framework Anti-Patterns

Category: Java,Software Development,TestingPhil @ 4:40 pm

Not that I’m a big fan of the whole “Anti-Pattern” concept, but there is some subtle irony in the title of this post; some of my coworkers will actually understand. Sorry about the mystery for the rest of you, but I think this post is really relevant for those trying to use Spring for the first time. After building my first Spring-based application, I was on the fence concerning Spring’s actual value. Obviously, I made lots of mistakes in my first implementation; I think many of the following anti-patterns can typically happen on your first Spring project; my goal is to make you aware of these pitfalls, such that you can skip past the mistakes made by myself and others.

Interesting Thought Tangent?
While looking for the title to my post, I have found a little snippet that calling “Spring a direct attack on J2EE“. I thought this was a unique way of describing the Spring Framework. For sometime now, I have been on the bandwagon to simplify the development practice through Spring (Spring Core, Security and Remoting). I never really thought about Spring as another religious battle front; such as the classic emacs/vi or mac/pc wars. In essence, I was picking a side: No more J2EE! I guess it was not obvious to me before today, as I really can’t escape the J2EE container; I’m are required to deploy in a J2EE container, even though I make no use of its capabilities; a Servlet container is all most of us really need! Just an interesting thought! Agree or Not?

So where to begin, I guess the first question is: Why do you want to use Spring? What service(s) will it provide for you? I think many developers simply wanted to slam it on their resume! Let’s start with the the most obvious use of Spring, Dependency Injection (WIKI, Fowler). I think this is the hardest thing for most developers to actually understand! If you think you are just writing XML code to create your instances rather than writing Java code, you have already missed the boat. I really believe that most developers have not actually taken advantage of DI in their applications.  They just use Spring to create an alternative static (hard-wired) bean creation strategies. Just for fun, I thought I would highlight some anti-patterns I have seen used before and hopefully never again!

Create a Factory.
Factories are so 1990. This is one hurdle that some developers have a tough time understanding. They continue to think about creating objects via factories. There is NO need to ever create a factory when using Spring. Spring is essentially the a super factory, plus it is actually responsible for the life-cycle of those vended objects. There are scenarios where you need to specifically create objects that Spring manages, in a loop for example; but these are very uncommon. The proper way to solve this problem, is to create a bean that is ApplicationContextAware.  When this bean is created (by Spring itself), Spring will set the application context on this bean. Now, you have the ability to ask for any bean that Spring is managing.
Ask Spring for objects.
This is probably the toughest habit to break and is easiest pattern to get stuck in. This is especially true if you are trying to integrate Spring into an existing project and is your first attempt at Inversion of Control. You will have a much better chance understanding these constructs, if you can start from a clean slate (or at least create a bunch of samples). Spring done right, is truly is a different way of thinking. For example, when working with a context-aware Servlet, you fundamentally NEVER need to ask Spring for a single instance; this is almost a perfect example of IOC and DI.  The whole point of DI is the INJECTION. It is not about ASKING for an instance, it is about being GIVEN an instance;  throw in the IOC principle and your bean will be invoked at the RIGHT time to provide the appropriate behavior.
Domain Object DI.
This was an unusual one for me. I recently observed a project that used Spring to created multiple static Singleton factories to vend out a variety of instances, each factory with it’s own Spring context file. Needless to say, this application was far from easy to understand. To my surprise, there was even a factory specifically implemented for creating the business domain objects. Why this was done is still a mystery to me and seems to violate the true spirit of Spring. Why would I ever want to call DomainFactory.getNewWidget() or DomainFactory.getNewGadget()? The configuration had the domain beans defined in a separate Spring context file and oddly, used static methods to initialize specific properties of these new bean instances. There was no way which enabled the XML configuration to be overridden, allowing for different implementations. Worse yet, you were tied to the initialization behavior of the factory methods! Depending on your definition of a domain object, I see very little reason domain object dependency injection.
Use Ant to create Spring Configurations.
This is an interesting use of Ant in a Spring-based application. The idea here is to generate the Spring configuration and properties file from an Ant task, to specifically configure the context files to each deployment environment. They values are essentially baked into the application and unchangeable.  It is bad enough to substitute property file values, but some developers actually substitute bean name references. This might be a little hard to follow, but the Spring XML configuration would define two different implementations of the same basic function, each with its own name. When the application is built, the Ant tasks would substitute ref=”bean1” for some environments and ref=”bean2” for others; everywhere that implementation was referenced in the configuration files. Call me crazy, but I don’t think this what the Spring creators ever intended!

As I have developed a better understanding of Spring and how to take advantage of it features, we have evolved our Spring applications to a state of “environmental awareness”. Using this solution, all of the context and property files are packaged into the application, for all known environments at build time. This enables us to build the deployment image (jar/war file) one time, using simple Ant tasks, no more templates, no more substitutions, no complexity. At execution time, Spring is now intelligent and can determine it’s execution environment; we can use specific property files for specific environments, as well as use alternate implementations (via DI) for each environment. This is where DI really pays off, allowing us to use the appropriate objects, not just properties, but objects for each environment! No code changes, no crazy Ant tasks, you build once and deploy anywhere. I think this is actually pretty slick and what Spring (core functionality) is all about.

I do have to put in a plug in for testability. Taking advantage of jUnit 4.x annotations and Spring integration, makes unit testing a snap. Using the @Resouce annotation to inject everything (instances) you need into your unit test is amazingly elegant; unit testing could not be made any easier. This approach allows us to have highly controlled, customizable execution environments; we can seamlessly manage unique configurations for local development, continuous integration, as well as any actual deployment environment almost magically.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Sep 12 2009

Capturing Values with Java Regular Expression Groups

Category: JavaPhil @ 6:48 pm

For whatever reason, I have been using a lot of Java Regular expressions at work lately; I started taking advantage of the grouping abilities provided by the standard Java Regular Expression implementation. I am certainly no RegEx expert, especial after reading this overview of backreferences and forward references! I use them every so often, probably not as much as I should; I know just enough to be dangerous! With my new exposure to grouping, I will probably use regular expressions much more frequently. Historically, if I needed to split a String into pieces, my goto class was the StringTokenizer. More often than not, I now use the String.split() method; you use create a simple regular expression and the method returns an array of the split values;  It is actually easier to use and handles the case where no matches are discovered fairly well.

If you are going to create and use regular expressions, you are probably going to need to test them. I have been using web-based expression testers for several years; here is one that I use often; Tonight, I found a FireFox plug-in I like ever better!

The point of this post was to show how easy it is to capture data using regular expressions. I created a little class to decode an id and status from a String. As illustrated in this simple example, you can use the Matcher class to do more than simply determine if the regular expression matched. With the addition of round brackets (parentheses) to the regular expression, we can actually capture the matched values in one simple step. This approach can also be used to capture optional values, the id and status, as in the included example. Unlike using a tokenizer or the split method, the Matcher class maintains the expected positions of non-specified, optional values; simply including an empty String for the optional attributes, when they are not provided.  As you can see the following Eclipse debugger screen shot, the groups are easily accessible, even allowing you to build nested groups, as my example demonstrates. You can play with the example or give the Matcher JavaDoc a quick read to learn more about how this class works.

public class StringDecoder {

    private static final Logger LOGGER = LoggerFactory.getLogger(StringDecoder.class);

    private Collection<String>  transactionIdentiferPatterns;

    public class Result {

        private long   transactionId;
        private String status;
        private String filename;

        public long getTransactionId() {
            return transactionId;
        }

        public void setTransactionId(long transactionId) {
            this.transactionId = transactionId;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getFilename() {
            return filename;
        }

        public void setFilename(String filename) {
            this.filename = filename;
        }
    }

    private class Match {

        private String[] group;
        private int      start;
        private int      end;

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("Match [end=" + end + ", start=" + start + ", value=");
            String comma = "";
            for (String s : group) {
                sb.append(comma).append(s);
                comma = ",";
            }
            sb.append("]");
            return sb.toString();
        }
    }

    public void setTransactionIdentiferPatterns(final Collection<String> patterns) {
        this.transactionIdentiferPatterns = patterns;
    }

    public Result decode(final String filename) {
        Result rc = null;
        for (final String pattern : transactionIdentiferPatterns) {
            final Match match = find(StringUtils.trim(pattern), filename);
            if (match == null) {
                LOGGER.warn("No match found using pattern [{}]", pattern);
            }
            else {
                LOGGER.info("Mache found {}", match);
                rc = new Result();
                rc.setTransactionId(Long.valueOf(match.group[2]));
                rc.setStatus(match.group[3]);
                rc.setFilename(filename.substring(0, match.start) + filename.substring(match.end));
                return rc;
            }
        }

        return null;

    }

    private Match find(final String patternStr, final String valueStr) {

        final Pattern pattern = Pattern.compile(patternStr);
        final Matcher matcher = pattern.matcher(valueStr);

        if (matcher.find()) {
            final int groupCount = matcher.groupCount();
            final Match match = new Match();

            match.group = new String[groupCount + 1];
            for (int i = 0; i <= groupCount; i++) {
                match.group[i] = matcher.group(i);
                if (i == 0) {
                    match.start = matcher.start();
                    match.end = matcher.end();
                }
            }

            LOGGER.debug("Good {}", match);

            return match;
        }

        return null;

    }

    @Test
    public void simple() {
        Collection<String> patterns = new ArrayList<String>();
        patterns.add("(###OID([0-9]+)([F|S]?)###)");
        this.setTransactionIdentiferPatterns(patterns);

        String name = "SomeStuff###OID122325F###.csv";
        Result result = this.decode(name);

        assertEquals(122325, result.getTransactionId());
        assertEquals("SomeStuff.csv", result.getFilename());
        assertEquals("F", result.getStatus());

    }
}
https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Sep 07 2009

Cleaning out my inbox!!!

Category: Blogging,JavaPhil @ 8:16 pm

I have been so busy with work and life, that my blogging had basically stopped for the summer.  I keep sending myself topics and notes about things that I would like to write about. Unfortunately, I have not had a chance to do anything with them and the topics keep piling up! I was talking with one of my coworkers last month, and he mentioned that he also had a blog. I mailed myself the link to his site, http://blogs.averconsulting.com/, and forgot all about it!

I thought It would be a good idea to share it, since many of my readers are coworkers as well! He has written some good stuff on the Spring Batch Framework,  REST, and Flex.  Please check it out…

Here is a  link to another one of my coworkers blogs… He  like to write about blogging and web security, you might find that interesting too… http://tdot-blog.com/.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Sep 06 2009

Freemarker: Java Template Engine

Category: JavaPhil @ 8:35 pm

Freemarker has been around for several years and is an unbelievably simple and powerful tool. Freemarker is used by numerous tools and frameworks, just click the “powered by” link to the right. Although it has not had a major release for some time, it is still an active project. I believe the tool is so mature, that it essentially does exactly what it needs to, minimizing the need for new features/releases. I first became aware of Freemarker using the Hibernate reverse engineering tool. We had some specific code fragments and styles we wanted to generate; it was very simple to augment and override the base code generation functionality, once you knew what was going on! I also worked on a Struts2-based project, which also utilized Freemarker.

I liked the Freemarker overview picture, taken from the project’s web site; it shows just how simple the tool is to understand and use. I thought I would highlight a non-traditional use of Freemarker to demonstrate how easily it can be integrated into any project. And, hopefully get you thinking about some interesting ways it can be utilized. The API is extremely configurable, capable of utilizing multiple types of input, such as databases or files, and can even be used as an alternative to XSLT. Please read the feature page for a full list of capabilities.

To start with, I created a simple little wrapper class to hide the Freemarker specifics and make it easier to deal with different type input objects. Freemarker can populate templates using a Map or simple Java bean, my preferred method of interaction. The helper class has a simple API, one overloaded method named process. You simply provide the template as a String, along with the input object; the generated result String is returned from the method. I have not really needed to do anything super fancy and the helper class meets all of my needs, from conditional logic, iteration, to custom formating, which is all implemented in the template.

public class FreemarkerHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerHelper.class);

    public String process(final String template, final Object input) {
       final Configuration cfg = new Configuration();
       cfg.setObjectWrapper(new DefaultObjectWrapper());
       return process(cfg, template, input);
    }

    public String process(final String template, final Map<String, Object> input) {
	return process(new Configuration(), template, input);
    }

    private String process(final Configuration cfg, final String template, final Object input) {
        String rc = null;

       try {
           final Template temp =new Template("TemporaryTemplate", new StringReader(template), cfg);

           final Writer out = new StringWriter();
	   temp.process(input, out);
	   rc = out.toString();
	   out.close();
       }
       catch (final Exception e) {
           LOGGER.error("Problem",e));
       }

       return rc;
    }
}

In a recent project, I used Freemarker for multiple purposes, generating dynamic filenames and simple XML files. The system needed to dynamically generate filenames based on a specific set of meta data, such as the object id, user id, date, and other application specific data. We allowed the files names to be specified as a Freemarker template, such as….

String template = “MyFile_${userid}_${date?string(\”yyyyMMddHHmmss\”)}_${oid?string(\”#\”)}.xml“;
String template2 = “${oid?string(\”0000000000\”)}.${filename}“;

Using the basic formatting features, Freemarker allowed us to generate any filename (format) that was required, without changing the code. We could format the numeric object id as a simple number or padded with leading zeros. Likewise, dates could also be formatted using any combination of the date’s components, using just part of the date or the time. The more interesting part is that you just pass in a Java bean or map with those attributes defined and Freemarker does the real work. This is a pretty trivial usage of Freemarker, and might not be the most common usage pattern. However, I literally did not have to write any code, other than my little helper class, which I have used on multiple projects, and I can support unlimited filename combinations; Huge bang for the buck! Once I had the filename generated, I needed to generate a simple XML file to control some external processing. The file always had the same structure, just different values. This was perfect use of Freemarker, no need for for any heavy frameworks such as XML Beans or Castor. I just created a simple Java bean that captured the descriptive data and an XML template; within minutes, my XML control file was generated.

Another quick example, I recently built a little Servlet to act as a web service for a function that we wanted to make available to multiple applications. The primary output from was either a JSON or XML stream, but I also added a basic HTML response for testing and demonstrations purposes. I hacked together some basic HTML, but was disappointed by how ugly the application was! I Google for a free CSS template, and integrated it with my Servlet. I created a single page as a template and added variables for the title, menu, and body. Using my helper class, I was able to conditionally control the menus, as well as dynamically add the main body contents. Once again, this only took minutes to implement, and was quite a bit simpler than messing with Tiles or Sitemesh!

<#if current == "home" >
      <li id="current"><a href="/Context">Home</a></li>
<#else>
      <li><a href="/Context">Home</a></li>
</#if>
https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Jun 23 2009

Doing more with jUnit: faster, cleaner unit testing

Category: Java,TestingPhil @ 9:20 pm

These are not really new features, but I bet most developers (like myself) have not given them the attention they deserve! Earlier this month, I read an interesting article on the Atlassian Developer Blog which peaked my jUnit interest. I remember reading about these features when jUnit 4.4 was released a couple of years ago (release notes), but I never took the time to try them out. JUnit included new abilities and concepts, such as Assumptions and Theories. To be real honest, the Assumptions and Theories sound really good in theory, but I’m not sure how practical they are in the real world! How can you argue with definition of a Theory… More flexible and expressive assertions, combined with the ability to state assumptions clearly, lead to a new kind of statement of intent.

First, I’m not sure how well Spring and Theories actually play together. They both need to have their own @RunWith annotation. Second, it is hard enough to get some developers to create a simple unit test! I will have to do some more pondering on Theories. Also, don’t get too carried away with the assumptions without doing some more reading; they have some rather unexpected behavior. Assumptions cause future assertions to pass, irregardless of the asserted value! Interesting?

The real power is in the “Matcher” functionality provided by Hamcrest, creating new capabilities (without writing additional code), a cleaner assertion syntax, creating more readable unit test code. Check out the multitude of convenince Matchers that are provided from Hamcrest. I focused on the power of the assertThat() method. The following code snippet demonstrates a couple of the matchers that I could have used a dozen times in the past and probably implemented my own nasty, non-reusable solution!

	@Test
	public void assertions() {

		final String colors = "color me crazy";
		final Collection<String> colorList = new ArrayList<String>();
		colorList.add("color");

		assertThat(colors, either(containsString("color")).or(containsString("colour")));

		assertThat(colorList, either(contains("color")).or(contains("colour")));

		assertThat("custom error message", colorList, //
				not(either(contains("red")).or(contains("green"))));

		assumeThat(colorList, contains("red"));
		fail("jUnit Still successful!! Does not fail!");
	}

Random Thoughts…

  • jUnit 4.6 was recently released (release notes). I did not see anything exciting in new new release, other that some new integration with JUnit Max.
  • As cool as JUnit Max sounds, it is now dead to me! The subscription fee has jumped to $10 per month… That is more than my XM Radio subscription!!! If continuous testing is really that cool, hopefully, other smart people are working on even better, open-source alternatives!
  • The Spring 2.x framework integration was broken with jUnit 4.5 and required version 4.4. The new 3.x version of Spring, still in beta, works with both 4.5 and 4.6. It actually no longer works with 4.4!
https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Jun 07 2009

Spring Framework XML Schema Extensions…

Category: JavaPhil @ 8:20 pm

Seems like every time I dig into Spring, I learn something new. This week, it was the Spring Util schema. Like most developers, I never take the time to read the manual and usually only have enough time to get the job done. Unfortunately, the rush to get done typically highlights some features that I really did not understand or used improperly. I seem to get a lot more out of reading the documentation after seeing how all of the pieces go together. Fortunately, I’m usually not satisfied with this level of mis-understanding, so you are forced to read about how I fixed my mistakes!
Generally, if you are only using the IoC container feature of Spring (dependency injection), you can usually get by using the simple bean schema. I have messed around with Aspect Oriented Programming (AOP) integration using the AOP schema, but never used it in a real project and I always use the Transaction annotations, so I never bother with the Transaction schema either! When I started integrating the Spring Security framework into my last project, my Spring XML files started looking a little different, I started qualifying all of my bean tags.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
                         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
                         http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
<security:global-method-security
secured-annotations="enabled" jsr250-annotations="enabled">
</security:global-method-security>
<beans:beans id="dateTimeBean" class="org.beilers.DateTimeBean">
</beans:beans>
<beans:beans id="timeDependentBean" class="org.beilers.TimeDependentBean">
<beans:property name="currenttime">
<util:property-path id="name" path="dateTimeBean.currentTime" />
</beans:property>
</beans:beans>
</beans>

I will write about the Spring Security framework in future post, but I wanted to highlight the Spring Util schema. I ran into a scenario last week where I wanted to use a property in an existing bean, to set a value in another bean; I could not pass in the bean, only the property. With the standard bean tags, there is no way to navigate a bean property path, such as bean.bean2.property. I knew there had to be solution to this problem, it seemed too common. With a little Google-ing help from a friend, we ran across the Util schema. There are some really convenient tags to help you manage your Spring configuration files. In the above example, I demonstrated the property-path tag to demonstrate path navigation. There as also other tags for accessing constants and fields, creating reusable lists and maps. Make sure you give this document a read, it can save you time and make your code cleaner and even add some type-safety to your XML.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 21 2009

Unbelievably Simple Java Zip Example… And What About Reuse?

Category: Java,Software DevelopmentPhil @ 5:15 pm

I was working on a typical web portal application today and needed to support a multi-file download. Luckily, I had some code which I had used several times before. I started to tweak it for my specific requirements, realizing it was such a bad fit, I quickly tossed it out. My previous implementation worked with physical files and was tightly coupled to a legacy framework. This time, the files were already in memory. I was hoping to find some code that allowed me to build the zip file in memory, rather than dealing with the file system and temporary files. Since the portal user could only download a limited number of files at one time and the files were very small, I didn’t have to worry about memory constraints.

Bottom line, I found the perfect piece of code on Trip over IT. Within 15 minutes, my application was downloading a sweet little zip file! The code was so simple and concise, I had to share it. I will definitely put the code in my tool box of handy snippets. 

Here is a provocative thought: What is the point of a reusable library? Do we focus on reuse because we continually over-design and over-build our software, thinking that we are saving time by building these reusable libraries? Are there alternatives? What about simple, small, and disposable code? Don’t be so attached to your masterpiece. I promise, it will not look so elegant tomorrow! All you really need is Google to find some code to start with. I found this little snippet of code, changed it to fit my problem, and I was done within a few minutes, no support and minimal overhead. Maybe the real reuse is my memory and ability to relocate this snippet in the future… Or am I just crazy?

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Next Page »