Below you will find pages that utilize the taxonomy term “Java”
fallingdreams my very own tetris clone
This will come as no surprise to my closest friends, but I am a long time game development admirer. Although I've never done anything professionally I did spend some time in the past studying this amazingly interesting field - it's my dark hobby. As hardware evolves and gamers demand more and more reality from their consoles, the game development industry is one of the few that basically didn't suffer with the latest economic crisis.
3D games are getting more and more sophisticated to the point that it's very hard for a single person, or even a small team, to develop something worthwhile - think of all the people you need to develop a game such as God of War III: screenwriters, artists, musicians, sound engineers, 3D artists, animators, programmers, level designers, combat designers, actors, voiceovers...
So I just wanted to have the experience of writing a full game, end-to-end, and that's where FallingDreams comes in. To be able to do that in a short amount of time, it had to be something simple and that's why I chose Tetris. Although simple, it does share most of the steps common to modern games development. It was a very interesting project to work at and you can grab the result here. The source code is also available on my github account, here.
FallingDreams is written in Java (JDK 6) and as such it should work fine on Windows, Linux and Mac OS. I tried to be as loyal as possible to the original Tetris rules, but you might find one thing or two that don't work as one'd exepct.
Enjoy! ;)
Disclaimer: This was my first 'full game' and is not intended to be production ready. The code has definitely got room for improvement and it served as my playground where I experimented different design techniques, both game and general software related. And it doesn't have a single line of tests - crucify me :P
As I said, it's not supposed to be considered bug free but I'm sure people interested in games development can benefit from the source files. Feel free to fork it as well! It would be cool to see what people would do with it :)
a few more thoughts on final classes
I said final classes are evil and that post got some attention with interesting comments. Maybe because of the title and the tone I wrote it, a few comments didn't get my real intention and perhaps I should have been more explicit about it. Go ahead and read it. I'll wait. :)
Anyway, I thought I'd expand a little more on that subject, explaining my motivation to write that post and going through the topics I think were raised by my dear readers.
First off, final classes are evil for testing. And that's what it was all about in my previous post.
If you depend on a final class, your code will be harder to test. Unless the final class provides an interface that captures its intent - or you wrap that dependency.
But this affirmation has some implications that were pointed out by a few comments, some of which I agree with - others, not so much. So let's start!
- Immutability
Someone said "Why make a class final ? To make it immutable". This is not entirely true. Only by marking it final you do not ensure immutability. There is no point in doing that if you provide mutators - e.g. setters. - and don't declare your members private and final.
I think it's important to make this clear and understand that the immutability part you achieve by marking a class final is the one of preventing inheritance. Subclasses could possibly contain malicious/careless code and change the internal state of the class.
But there is another way of preventing subclassing without marking the parent final: declare its constructor private and provide a static factory.
- Designing for extensibility
This is hard. It basically means that if you don't mark a class final, you should document it for inheritance.
And this is why inheritance is, in general, a bad OO practice. By documenting the class you basically break encapsulation since you tell the world about your internals.
Therefore, the recommendation is to mark a class final if you're not sure if it's safe to subclass it - or if you just don't wanna bother writing documentation and thinking too much about your "client" subclasses.
- Coding against interfaces
This one is simple but yet often forgotten. Do not code to concrete classes. Always choose interfaces where possible.
It roughly means to do this:
List args = new ArrayList();
instead of this:
ArrayList args = new ArrayList();
By doing so you have the flexibility to not care about the implementation you're working with, as long as it obeys the interface. That way, the implementations can be swapped at any time without breaking any client's code.
- The problem with testing
All items listed here so far are widely regarded as best practices and the bullet I raised about hard testing usually happens when you "violate" some of them.
Specifically, if you decide not to design a class for inheritance and mark it as final, it's wise - in my opinion - to try and capture the class's intent through an interface.
That way you can safely mark your class final and users of your class can easily use the interface to extend it - by favoring composition over inheritance - or by providing it to mocking frameworks for easy testing.
- Conclusion
I don't really think there is a rule of thumb here. Java's standard library shows many examples of both approaches and some of them are now considered bad practices but yet are there for backward compatibility. Nevertheless, these are points to consider when designing your classes.
As pointed out by Josua Bloch in his awesome book Effective Java, "If a concrete class does not implement a standard interface, then you may inconvenience some programmers by prohibiting inheritance".
As usual, comments are more than welcome :)
jvm language preferences poll results
- Overall results
First off, I'd like to thank everyone who voted on this poll.
With a total of 236 votes, here is the summary of the first two questions:
- Are you currently working with or researching about language alternatives for the JVM? - e.g. JRuby, Scala, Groovy
{% img /assets/images/scala_improvements.png %}
Tooling. The majority of comment urge for better tooling and IDE support. That simple.
- Others
People who chose others mentioned Clojure, Fan and Jython, with a clear advantage for Clojure.
- Disclaimer
This poll has no scientific foundations whatsoever and its sole purpose is to summarize the feelings and personal choices of the people who answered it. If you would like the original spreadsheet with the answers, you can find it here and do your own analyzis.
jruby on rails and legacy java apps managing dependencies
The motivation for this post came from a couple of messages I've seen on the jruby's google group and because I think it's pretty cool to share how we tackled this problem.
- A little bit of context
We, as a vast amount of people out there, have legacy Java code. A lot. In our case this legacy is pretty much crucial to our business. We can't just trash it and start from scratch. Bad idea.
On the other hand we do have new features to be built on top of it. But we wanted an easier way to develop this new stuff and decided for a JRuby on Rails solution, using it as a front-end to our existing services.
- What we decided to do
Our final rails project would make use of a specially created jar file containing our Java application. This Jar would also contain a public interface of the services we'd have to interact with from rails.
As any Java application, ours depend on a number of external jar files that correspond to the various framewoks we usually have in place. e.g.: Hibernate, Spring, apache-commons ...
Which means we need to make our app's jar and all it's dependencies available in the JRuby classpath in order to use it.
Given we're using warbler to package our application as a war file, we just need to place all jars needed into our rails app's lib folder. Warbler then takes care of copying any jar files located in there into the war.
- The problem
So we needed a smart way to include all these dependencies into the project, and copy/paste isn't an option.
In the Java world we use Maven to manage our projects dependencies - and you should too. Because of that our approach involved turning our rails application into a Maven aware project.
Basically we needed a pom file that would declaratively list our java project as a dependency. From there on, Maven knows what the dependencies are and downloads them to your local repository.
Which leaves us with one more task. We need to put all these dependencies into our lib folder after maven has downloaded them.
Below you'll find the pom.xml file that we use to achieve this with inline comments explaining each bit:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company</groupId>
<!-- notice how we specify the packaging to be a war,
that way, maven knows where to copy the jar files -->
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<artifactId>railsApp</artifactId>
<name>railsApp</name>
<dependencies>
<dependency>
<groupId>com.company</groupId>
<artifactId>java-legacy-app</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>railsApp</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<!-- This tasks only creates a basic structure expected by maven,
so it can do its work -->
<id>create-mock-web-descriptor</id>
<phase>compile</phase>
<configuration>
<executable>/bin/sh</executable>
<workingDirectory>.</workingDirectory>
<arguments>
<argument>-c</argument>
<argument>
mkdir -p src/main/webapp/WEB-INF
touch src/main/webapp/WEB-INF/web.xml
</argument>
</arguments>
</configuration>
<goals>
<goal>exec</goal>
</goals>
</execution>
<execution>
<!-- Now in the package phase we copy the jar files
that maven put into the fake web app to our rails' lib folder -->
<id>copy-needed-jars-into-lib</id>
<phase>package</phase>
<configuration>
<executable>/bin/sh</executable>
<workingDirectory>.</workingDirectory>
<arguments>
<argument>-c</argument>
<argument>
rm -f lib/*.jar
cp target/railsApp/WEB-INF/lib/*.jar lib
rm -rf target/railsApp*
rm -rf src
</argument>
</arguments>
</configuration>
<goals>
<goal>exec</goal>
</goals>
</execution>
<execution>
<!-- Here we optionally create the final war file containing our rails app using warbler,
doing a small cleanup of the files and folders maven created -->
<id>create-final-war</id>
<phase>package</phase>
<configuration>
<executable>/bin/sh</executable>
<workingDirectory>.</workingDirectory>
<arguments>
<argument>-c</argument>
<argument>
rm -rf *.war tmp/war
jruby -S warble && \
mv *.war target/railsApp.war
</argument>
</arguments>
</configuration>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Now from the command line we can just run mvn package and we’re good to go.
Maven will start to package the application as a war file. Since it’s not a Java application we create the empty web.xml file in the compile phase, to fool maven.
After it has copied all the dependencies into WEB-INF/lib the next packaging goals will make sure we copy them to our rails’ lib folder, also creating the final war file, ready for deployment.
Note that once done, you can use a simple code snippet similar to this one as an initializer and load all dependencies:
Dir.entries("#{RAILS_ROOT}/lib").sort.each do |entry|
if entry =~ /.jar$/
require entry
end
end
Then we can just use script/console, script/server and so on, as we normally would.
Sorry for the long post, I tried to pack in as much as I could and I certainly hope it’s useful to someone. Any doubts, comments and etc… just drop me a line. :)
google io thoughtworks on gae
I've just watched a video from Google IO where Martin Fowler and Rebecca Parsons went through some of the aspects that involves the development of an application for the cloud - focusing on the JVM.
In terms of the Google App Engine, you don't have access to a relational database, thing I found out when I first tried it. Instead you get a Big Table.
Martin put out a good analogy and you can just think of it as a nested hash map. It's certainly a shift on how we think these days, but layers of abstraction like google's DataStore and the Java Persistence API will help in the transition.
Another interesting bit about the presentation was on how concurrency works on GAE.
Essentially, in an standard Java application you have a single memory space where you have at least one running thread. You can create threads on the fly, which will share the same memory space, thus making it easy to share data.
On the app engine, things work differently. What you have are separate memory spaces with a single thread on each one. Any attempt to create a new thread will result in an exception. The solution for sharing information in this case? Use the nested hash map (big table).
Now, whereas you might not be worried about this since your application doesn't span any threads, as well pointed by Martin Fowler, it's the code you don't see that you need to be careful with. Any Java application uses a number of 3rd party libraries that might span out threads of their own, which will result in your application blowing up.
That rang a bell. Again, back when I was trying the app engine, one of the configuration bits shared by Ola Bini looked like this:
config.webxml.jruby.min.runtimes = 1
config.webxml.jruby.max.runtimes = 1
config.webxml.jruby.init.serial = true
I think the properties are pretty much self-explanatory but I didn't quite understand the reason for setting it back then.
If you happen to have bigger values for the number of runtimes you want, you need to set the serial property to true, otherwise JRuby will span several threads to create the runtimes.
This is a really good example of things that might fail whether you're migrating or developing a new app to deploy on the App Engine. Luckily for us, JRuby has a smart and neat way to handle this - the configuration I've just shown, but most of the libraries out there that might rely on threads are not prepared.
Martin and Rebecca's opinion on this is that new releases of these same libraries will start to take it into account, since a bigger adoption of the Cloud seem to be on the way.
Make sure you watch the video. I certainly left a lot of interesting stuff out.
helping the jruby effort debugging the source
Wanna help improve JRuby? Make sure you read this post by Charles Nutter first. There he explains how to run Ruby specs with JRuby.
Start with fixing Ruby specs is a great way to get acquainted with the code. And it’s also a important task in order to make sure JRuby is the most complete and compatible ruby implementation out there.
But before you get your hands dirty, it will be a lot easier if you can actually debug JRuby’s source while fixing any specs - or bugs/features for that matter.
railswaycon jruby internals by ola bini
As always I expected a good talk from Ola and once more he delivered it. But this one was different. It might have been even boring to some ruby developers since we saw a fair amount of java code in this presentation. Ola gave us a tour through the main classes that make JRuby possible with a single purpose: so we can check out the code and hack ourselves. You can download his slides here.
If you've been following both JRuby and Ola Bini for the past year or so, you've noticed the trend and evolution of this alternative - and so far the most complete one - implementation of the ruby language. Specially at conferences.
Last year at QCon London, Ola was also talking about JRuby. At Euruko '08, in Prague, Charles Nutter also talked about it. RailsConf in Berlin also had its share. What all these talks had in common is that they talked about JRuby from a user/developer point of view. They were selling the solution. Convincing people to use it and presenting successful use cases.
And as the trend goes on, JRuby is now faced as a true alternative - one that we, btw, believe here at the company as we're actively using it - and it seems that now the call is for help. Help to make JRuby an even more complete and overall better ruby implementation. Charles' call for help was a great step. As he states, it's a good way to get your feet wet. I answered the call and am hacking JRuby myself, having already submitted a couple of patches. Perhaps this was the reason for which I enjoyed the talk the most. I was already familiar with some of the structure and classes in JRuby.
There were 2 more talks about JRuby: The Pleasure and Pain of Migrating to jRuby, by Steven Bristol and Integrating Enterprise Java with JRuby and Rails, Michael Johann. Unfortunately only the first one was a real case experience, where Steven walked through the problems he faced integrating JRuby with an existing java project. Interesting insights.
Michael Johann basically presented a short tutorial on how to integrate rails with EJB3 which, albeit interesting, failed to address issues faced on real life projects, like dependency management. Issues which we have already addressed in a very cool way here and I plan to share it soon. Still deciding how though...
jruby on rails and google app engine
As many of you know the new language supported at GAE now is Java, as officially announced on their blog. As a Ruby/Rails developer you might not be interested on it but here is a reason you should be: JRuby.
It was only a matter of time until we saw some people deploying JRuby on Rails apps on GAE, like Ola Bini's mini blog app. Guess that was the first one really, as he was beta testing the service in secret. Google App Engine imposes a few catches to any java application deployed there and any JRuby app wouldn't be different. For instance, your Java API access is limited to these classes - called JRE Class whitelist.
As you can see on his blog, you don't need active record and in fact shouldn't even be loading that on your app.
I felt compelled to try it and the timing was perfect. I am currently developing a JRuby on Rails app at the company I work for and it was a perfect fit, since we are not using ActiveRecord. The reason is that we get the data we need from other sources, such as web services and even text files.
Ola Bini's tips were crucial here. He provides a small script you can use to prepare the jars you're sending to your app. Another important piece was the Google App Engine SDK for Java. It ships with a server that emulates GAE's behaviour locally so you're less likely to have problems once you deploy it.
I did have a problem though with the number of files uploaded to my appspot. It's currently limited to 1000 - a thousand - and a Rails app can easily exceed this limit. So before deploying, remove anything that is not crucial: activerecord - you should've done it already - , all tests directories - including the ones inside gems your app needs in order to work, fixtures and etc.
After that it was rewarding seeing a custom JRuby On Rails application working perfectly on GAE. And as much as I'd like to, I can't really share the URL since it's a private app but I encourage people to try it. I believe GAE will ultimately help the community improve JRuby even more.
And as a last tip, this time thanks to Fabio Akita, is this snippet. You should redirect your log so you can debug your app form GAE's dashboard.
Have fun!
final classes are evil
Update: Go ahead and read this post in its entirety - including the comments. Then, read my other post where I expand the subject a little more.
--
Every now and then I still do some Java coding. And I actually like it. I spent several years of my career developing primarily in Java and am very keen about the language.
I've been a fierce defender of it these days, specially with the wave of popularity of other languages such as Ruby and Groovy. But I must say that for the 1st time - actually the 2nd - I got pissed off at Java.
The reason? Final classes!
How arrogant of someone to say: "And from now on you shall not subclass my classes!"
Er.... Why?!?! I'm yet to find a good reason in favor of it. But I can share 2 that made me be completely against it. - I never actually liked it but it just didn't bother me that much in the past.
The first one happened while I was adding PostgreSQL XML support to Hibernate. The basic idea is that the XML data type should behave mostly as a string, with the exception of the saving and loading operations.
The thing is, the String data type in Hibernate is declared final. So you cannot share behavior unless you copy and paste it. How smart.
And the second is in the testing area. We all love testing. And we all love mocking external dependencies so we can test our code in isolation and fast. Well, I hope your code doesn't depend on the URL class then.
It is declared final so you just can't mock it. Mocking frameworks like easyMock use subclassing to create your dependencies mock objects and obviously it doesn't work here.
Yeah yeah, of course you can refactor your code so it depends on an interface/class that wraps your URL class and then you can switch implementations. But just how stupid is that? Programming to interfaces makes sense, but not everywhere. Specially not when you're using a low level class like this one.
So please, software developers, architects and the like, design your systems for extensibility and stop being presumptuous.
P.S.: There is a testing framework called jMockit which uses instrumentation (Java 5+) to redefine methods in runtime so you can mock final classes. It works, but should we really be playing that much with the java class loader just so we can "easily" test our code?
eclipse tip debugging non wtp projects
This is a very useful tip I shared a while ago at the office and turned out to be extremely useful.
If you work with java and use eclipse as an IDE you know that eclipse has something called WTP, which stands for Web Tools Platform. It's a set of tools and API's to aid in the development of web and JEE projects.
That means that if you have a WTP project in your workspace, you can deploy, run and debug it straight from the IDE. But what happens if your project is not of a WTP nature?
Back at the office we have a coupe of really old Java project. WTP didn't exist back then but we do use Eclipse as our IDE of choice.
So, how do we debug a deployed project that we don't actually deploy from the IDE? As long as you have the source, it is quite simple:
mock objects
When testing it's pretty common to see the need for mocking a certain object, say, a Data Access Ojbect. This way you don't need to depend on a database and you can focus on the actual logic implemented by the method being tested.
For that you have several alternatives like creating the Mock class by hand or - and this is the more common - use one of the various mocking libraries out there.
They all look the same but the past couple of days I've come accross to a new - at least for me - mocking library for Java. It's called Mockito. As the creators state, technically, Mockito is a fork of EasyMock.
I have used EasyMock already but I do think Mockito has its advantages. I find it clear and a bit less verbose to write.
From one of the stubbing examples on their website:
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
//stubbing - before execution
stub(mockedList.get(0)).toReturn("first");
//following prints "first"
System.out.println(mockedList.get(0));
//following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
Looking forward to using it in production! ;)
why i like ruby or ruby the language of the lazy programmer
This is quite funny. A friend, Perl addicted, is now learning Ruby. He really enjoys the language but made a interesting observation: Ruby is a language for lazy programmers!
Well, I have to agree... You know, I love saving keystrokes and achieving more by writing less. And this is so true with Ruby.
Let me give a really simple example, comparing with java - don't get me wrong... I love java, specially the platform, but it fits well here since I've always been a Java guy.
Imagine you have a Phone class with the attributes number and type, which can indicate whether the phone is a land line or a mobile phone. Then you got an array filled with phone classes and you want to narrow it by creating a new array only with mobile phones.
In Java, such a class could look very much like this:
public class Phone {
private String number;
private String type;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Quite simple, isn't it? But we are telling the compiler many things we actually shouldn't need to. This class is a java bean and as such, among other things, it needs a pair of getters and setters for each of its attributes.
Now, on with our example, the same class, in ruby, looks like this:
class Phone
attr_accessor :number, :type
end
Yeah, I know the feeling. This class has exactly what we need: the two attributes with its own pairs of getters and setters each. But we didn't need to inform it in the verbose way Java has teached us. Cleaner, period.
Now to the code that actually returns the new array containing only mobile numbers. In java, we can do it in two different ways.
Using an ArrayList:
//Create two phone objects, one land line and one mobile
...
// Add them to an array
ArrayListphones = new ArrayList ();
phones.add(land);
phones.add(mobile);
//Return an array only with mobile numbers:
private static ArrayListselectMobilePhones(ArrayList phones) {
ArrayList<Phone> mobiles = new ArrayList<Phone>();
for (Phone phone : phones) {
if (phone.getType().equals("mobile")) {
mobiles.add(phone);
}
}
return mobiles;
}
Or using ordinary arrays:
// Assume the same phone objects here
...
//Add them to the array
Phone[] phones = new Phone[]{land, mobile};
//Return an array only with mobile numbers:
Phone[] mobiles = new Phone[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i].getType().equals("mobile")) {
mobiles[i] = a[i];
}
}
And you're good to go. Actually this code with an ArrayList here only looks good thanks to generics. But this is another matter. Let's take a look at the ruby code that accomplishes de same task:
//Create two phone objects, one land line and one mobile
...
//Add them to an array
phones = [land, mobile]
//Return an array only with mobile numbers:
mobiles = phones.select { |phone|
phone.type == "mobile"
}
See the difference? Java is a great language but too verbose at times. This is a really simple example but if you take the same principle to a bigger app... yeah, you see where I'm going.
The bottom line... Ruby may be the language of the lazy programmer, as my friend pointed out. But I don't mind being called lazy as long as I can type less and be more productive. Do you? :)
qcon 2008 domain specific languages
Today was the first day of the conference and it started with a tutorial about DSL's with Martin Fowler, Neal Ford and Rebecca Parsons. We also had as attendants Ola Bini, core developer of JRuby, and others. My expectations were pretty high and the presentation didn't let me down. I'll try to put here toghether my impressions and some notes I took while I was there.
Marting Fowler started discussing what DSL's are and giving some examples that many of us use in our day to day Job. Like the XML configuration files in the Java world. It is a kind of DSL, it has it's own keywords and syntax in order to express some information that will be used , for instance, to configure an underlying framework.
The problem with XML is that it becomes hard to see the overall behavior behind it. It's not very fluent to understand the purpose of an XML file just by looking at it for the first time. There is too much "noise". Things that get into the way of the readability. - YAML files are an much more readable alternatives to XML.
The same happens with a standard framework api code. Let's take for instance a sample API configuration code written in Java to tackle the domain of hotel reservations. A framework like this could have the following implementation:
HotelService hotelService = new HotelService();
PersonService personService = new HotelService();
Hotel hotel = hotelService.findById(1);
Person guest = personService.findById(10) ;
Reservation reservation = new Reservation() ;
reservation.setFrom("2008-03-10") ;
reservation.setTo("2008-03-14");
reservation.setGuests(new Person[]{guest});
hotelService.book(hotel, reservation);
Of course implementations of this simple example may vary but we can see here some of the readability problems. One approach we could use for that is to develop a Fluent Interface to wrap this API. This was one of the techniques explored during the tutorial and the actual fluent interface could now look somewhat similar with this:
new Hotel(1)
.book()
.forGuests({
person.find(10)
})
.rooms(1)
.from("2008-03-10")
.to("2008-03-10");
Much more readable, huh? One of the main benefits of using DSL's they highlighted in the tutorial is the simplicity of code you can achieve. You can actually show this code to a business person and he can understand it. This is a kind of internal DSL.
But there is still a bit of noise in this code. The the parenthesis which are not always desirable, and the use of double quotes for dates. But, this is Java code, and Java doesn't give too much room for you on the DSL subject. Here was when the speakers changed their focus a bit to Ruby. It's dynamic nature and metaprogramming techniques provides a powerful flexibility that allows for a looser syntax.
So in ruby the previous interface could look like this now:
Hotel.find(1) .book(1.room).forGuests {
Person.find(10)
}.from(march.10.2008).to(march.10.2008)
We got rid of the double quotes and the code looks more fluent, like a normal english sentence. I doubt a business guy woudn't understand what this code is doing. With this, we can get closer to the business guys, with a common vocabulary, and fill the gap between us.
This is just one of the ways we could have written this code and is not the actual example used in the tutorial. The syntax also really depends on how readable you wanna make your code. I'll provide those later when they release the digital format of the presentation.
So one of the flows that the development of an internal DSL can get is to build a framework and define the DSL on top of it. But we should also keep in mind that DSL's shouldn't be general purpose programming languages. They should be created to tackle a specific kind of domain problem, so we would have a whole system made of small DSL's.
Another interesting subject that was touched is testing. How do you test DSL's?
The suggested approach, and that I think is quite reasonable, is to have separate tests for the underlying framework and another to test the DSL and its parser you can assure you have the expected behaviour of both parts.
This is really just a summary of my thoughts and of what happened there. I'm not going into too much details right now but if you found something too abstract - and it is! ;) - feel free to ask details. I'll be more than happy to help.
This is definetly an interesting subject and now I'll head to play more with all that. :)
PS; This is not the whole presentation, just the best of it from my stand point. Other subjects include External DSL's which can actually involve you coding Lexers, Parsers and Compilers. It's usually not worth the hassle. And it's too complicated anyway, that's why I left it out from this post.
dbunit and hibernate
I never paid too much attention on testing database stuff. While working with java, the closest I got to something workable was using the test case abstractions provided by the Spring framework. It ensures that each test method runs in its own transaction that is rolled back after the test's execution.
Fair enough. I used the setUp() method on my TestCase to configure some records so I could work with them, removing all of them in the tearDown() method. It was quite simple and worked.
But I always felt something strange with this solution. First of all, I had to add another framework just for that. - Actually I was using spring for dependency injection, but if I wasn't, it wouldn't be a nice option. And another thing that bothered me, is that you cannot guarantee that your database is in a known state.
After I started to work with Ruby - and Rails - I discovered the testing fixtures. It is a really nice way to set up your testing data without having to worry about your database state. - If you don't know what I'm talking about, follow the above link first.
Then I received a message from a co-worker saying he was having some trouble in using DBUnit with Hibernate, and asked for some help. I've heard of DBUnit before but never tried it myself. It was a very good opportunity to take a better look into it.
The basic idea after all is very similar to that of the Rails Fixtures: You have some sort of external file - XML in this case - where you set up the testing data. So the framework takes care of erasing the database, inserting your test data and returning it to its original state.
So far so good, DBUnit's default Classes works with JDBC, DataSources and JNDIDatasources, but not with Hibernate. The effort to put them working together is minimal and is documented in their web site.
I decided to share how this can be done with hibernate and in the end, you would have a test case similar to this one:
spring 25 dependency injection that doesnt hurt
Dependency injection - DIÂ - Â is a great thing. Really. The hability to tweak implementations without touching your code is awesome and the DI frameworks, like spring, saves you a lot of coding. No more service locators stuff.
But, and there is always a but, you're left with a bunch of XML configuration. And I hate it. Not that XML files are bad... the thing is that everything nowadays has its own set of XML configurarion files. And Spring is not different.
eu odeio xml
Isso é um fato. Cada linha de XML que eu escrevo me faz pensar em formas de evita-las. E isso não é simples.
Ultimamente, desde o Java 5, tem se trocado o XML pelas annotations. Tá bom, fica bonitinho né? Até que fica. Em alguns casos, até mais organizado. O Hibernate desde a versão 3 faz uso das annotaions da JPA como alernativa ao seu XML de configuração. E esse sim é um belo caso de sucesso!
São apenas algumas anotações na classe para mapea-la e pronto, adeus xml! Mas como sempre, as anotações já estão sendo exageradas por aÃ. Basta decidir configurar uns 3 frameworks - e provavelmente dois deles são descenessários no seu projeto - usando anotações e as suas classes ficarão uma zona! E muito mais ilegÃveis que um arquivo XML!
As anotações são recursos muito poderosos e devem ser usadas de forma consciente. Use as que realmente valem a pena, como as que vou falar agora, que fazem parte da nova release do Spring framework, a 2.5 RC1.
scea 5 beta
Hoje fiz a versão beta da nova prova de arquiteto da Sun e eis algumas impressões:
- É longa e cansativa... fato justificável se levar-mos em consideração o fato de ser uma prova em estado beta. Ela possui mais questões que a versão final. São 153 questões no total, em 4h e 30min.
como o spring me ajudou a manter o active record
Nesse primeiro post vou falar um pouco sobre meu novo trabalho. Na verdade, sobre um problema que encontramos lá.
Dentre diversas coisas que estamos fazendo, como migrações por exemplo, estou ajudando na elaboração da arquitetura que irá abrigar as novas aplicações desenvolvidas na empresa.