10 Warnings Javac should have


1. Warning: Use of @Deprected on a method will encourage its use and abuse by other developers. Consider throwing a RuntimeException instead.

2. Warning: Do you really want to read your entire database model into an XML document?

3. Warning: Your code is too clever for javac to translate. Consider refactoring.

4. Warning: Your ORM layer should not be used to model database tables.

5. Warning: You’ve been warned about using ORM to model tabels. Your IDE has now been uninstalled and your user license revoked.

6. Wanring: Sexual references should not be used in Exception contructors.

7. Warning: It appears you are writing a framework. Your browser is now being directed to apache.org.

8. Warning: You unit test should not “know” how to instantiate your middle tier, write to your database, draw your UI and start your vehicle. Consider refactoring.

9. Warning: The compiler has scanned over 700,000 lines of code and could not find a single interface. Your resume should be updated.

10. Warning: Too many design patterns found in the current statement.

Spring- Wire a property to a property…


Found a back door to a problem I was having this morning. First let me offer some background. I’m in the middle of an ugly hack! A hack unlike anything you’ve ever seen! I’m tying our order entry system into our reporting system in such a way that when a certain report runs we start dummy temporary orders, submit them, and delete them. I’m not going to speak much on the subject, just know that it is absolutely necessary for completing my project. The project itself is a tangle of additional code just to get a report that looks like it was created on one of those legacy dot matrix green bar printers from the seventies. (We’ll soon need to work on improving the look and feel of the reports but that’s another topic.) The hack isn’t what’s important, rather it is the code around the hack that draws our attention today. (By “our attention I’m referring to the combined attention span of both you and I, you’re with me right?) I needed a way to pass a stateful session bean around what was essentially a Springframework-wired report-framework writtent entirely in the POJO programming language. (You have heard about POJO haven’t you? No? Shame on you! I spit at the ground you walk upon!) It’s bootstrapped into EJB/JMS land using “clever” message driven bean delegation pattern which is also poorly implemented. If it’s an EJB and it’s in the same VM as the reporting code then I can use Spring JNDI convenience classes to get the thing out of the naming directory and into my object right? Well, there’s more and it’s not that simple. Our EJBs, stateful as they are, have grown glued to our authentication/authorization code which is hard-wired into every one of our data objects which, themselves, poorly attempt to implement the DTO pattern introduced in the early days of EJB that we have long forgotten. (Well most of us have forgotten while others like myself continue to be pestered by its ugliness.) In short, we have a mess of messy integration that messes everything up whenever you mess with the mess. (If I’m not mess-taken.)

The reporting framework stuff, is far from perfect, though we don’t want to mess it up with our old EJB ugliness and there’s about three or four brittle objects in-between the part where the EJB code breaks off and the POJO code picks up. I didn’t want to mess with that either. I got frustrated and tapped one of my buddyies on the other side of my fabric-like cubicle wall. While talking it out with him (…we never actually help one another with problems, instead one always ends up functioning as a listening board while the other rambles enough about the problem to find his own solution. You really gotta find yourself a buddy like this…) I realized that what I really needed was a way to pass a property from an EJB delegate (the point where the EJB crosses into POJO) into the ugly code I was writing. The property itself was not springwired. Instead it was a value sent from the client over the wire and pushed into the message driven bean delegate by a wrapping EJB/MDB superclass. (The “clever” code.) What I came up with was some Spring descriptor code that allowed me to wire a property from one bean, already instantiated in the descriptor, to another. The Springframework MethodInvokingFactoryBean provided the glue. The net result: I pulled a property from one bean into another without haveing to pass it, daisy-chain style through all the layers in between. I’m probably speaking greek to some of you but this is some really wild stuff. Y’all don’t hear me though…

Tell ’em why your mad…


I was about to change the name of my blog to “Diary of a Mad programmer” after venting to my buddy this morning about my many frustrations. Yes, I’m frustrated. I’m angry, annoyed.

“Tell ’em why you mad son…” I… I… I’ma tell you why I’m mad, dog! I got Jon-blaze programs and they just ain’t rekognizing…! I’ve been coding a long time and I know the in and out’s. That legacy system the we’re replacing, it’s aight. I mean, you got your order entry, inventory management and all. But my stuff is more Jon Blaze than that! I’ma calm down, though cuz it’s aight…

(The above is a parody from the old Notorious B.I.G. interlude with the Mad Rapper, if your confused.)

I love my job and my co-workers. I appreciate my boss too even as he is the source of my frustration. He’s done nothing wrong. He took a bum like me from the street and employed me adequately. He allows me to innovate like crazy. He even supports the majority of my failing hair brained ideas. (That’s why I respect him so much.) So how could he be the source of my frustration? The disjoint comes from two diffeerent vantage points on the same project. He’s down looking from up high while I’m staring upwards from down low. He’s got the classic management horizon scope of the ocean while I’m looking out from under water. That’s where we clash. More specifically, he sees the project as a necessary complex piece of software where I see the project as an unecessarily complex piece of software. When I come up with one of my stoopid ideas like storing Java objects in the database each of which knows how to upgrade the schema from the version prior to the one it was assigned then that sounds like innovation. It involves more code, more complexity, more of what is percieved to bring value to our project. However when I strive to reduce the number of integration points to something as complicated as our order entry EJB or pricing entity manager bean he seems to be totally against it. (That statement is slightly unfair, only slightly.)

In my unknowingness (can I get away with such an absurd term as unknowingness? It’s my site so I guess so!) I’ve contributed to a complicated mess that I now want to completely refactor. When I started I had no idea how important certain agile practices were, or how important simplifying code was. Now that I’m making the turn around the vehicle is moving too fast to change direction. I’m at the point where everything I do for simplification must either be undone to integrate with the project or require a huge refactoring of a major piece of the project. Without getting “the man” on board it feels like all of my efforts are in vain. Getting “the man” on board is akin to fighting City Hall. Years of preconceived ideas about the best development practices coupled with our no-doubt-complicated legacy cash-cow system that he initially created have hardened “the man” against any idea that the average agilist would promote. Now I’m in the thick of a report that must log into the system and actually start an order (via RMI/EJB) in order to determine the price of products. My prestine XSLT stylesheet that has served even the most complicated report in the system will cough up a hairball when it see the light of the latest layout that “the man” has dreamt up for this beast of a report. Yes I must do the unthinkable, put a report specific hack into my general purpose stylesheet which has remained thus far clean of such debris.

On top of all of that, I don’t even think I’m practicing best practices in the best way. Isn’t that funny? These are the best practices that I could find and I’m not the best at practicing them. In many areas I question if I’m practicing them at all! I mean, I’ve got a good chunk of code managed as individual Maven2 prjects, I’m using TDD and intentional programming, trying to separate data acess from business logic using th DAO pattern, organizing my business objects in a package separate from my general purpose utility objects which are separate from the silly framework code we all get bogged down in. How the Hell could I be wrong? I’ve also managed to desing an insulation tier separating the DAOs from the fact that JDBC is being used at all narrowing their job to asking questions (queries) of a data store (data source) and mapping the results to POJOs. Still I have many problems. I somehow got myself into a corner where some DAOs depend on other DAOs. I backed myself into a test and an implementation that’s littered with generics syntax sugar and looks more like a framework than a practice removing framework code from the business logic.

It’s during these times that I feel out of control, helpless. As a professional I’m supposed to have the answers but my answers only seem to turn up more questions than they solve. Regressing to the typical dated practices of yester-year appear to hold a huge advantage to the complexity that I’ve added in only the past 7-8 days. That’s why I’m mad!

Maven Proxy Details


Update: I included an extra proxy configuration in my example below that would normally be unecessary. I included it so that I would still be able to run builds and update my local repository when our instance of Maven Proxy was down. I also used it to access the Mojo sandbox on codehau.org so that I could finally figure out how to compile Groovy under Maven. In most cases including the extra proxy settings is akin to placing your coffee maker on a lit gas stove to keep the carafe warm. What I’m trying to say is you would most likely not need to do it unless your the type that particularly appreciates the idea of dispoable Mr. Coffee makers.

I must admit that I got lucky when I finally made Maven Proxy work for me. Ok, it might not have been luck, rather it was a stroke of persistance. I had people telling me on the mailing lists that it would not work, they couldn’t get it to work, and it it was not compatible with Maven 2. The web site had next to no documentation and at this point I don’t even rememeber how I got so lucky, ahen… persistent. Long story short, the majority of my problem (and the problem I attempted to address here) was related to our in office HTTP proxy. That dang thing has been the core of more problems than I care to think about.

So What?
Why am I wasting your time explaining how hard Maven proxy was for me to setup? I have a reader who is trying to get Maven Proxy working and that reader may not be as lucky… err persistant,,, as I was or am. My last posting about Maven Proxy left out some details and that’s no good. So, with the hope of loading my site chock full of useful information for people like myself who struggle on a daily basis, and also in an attempt to be a nice guy and go out of my way, I will present to you, my loyal reader, the rest of the details regarding Maven Proxy configuration.

Setting Up the Maven Proxy Config File
For the most part you can use the default settings in the Maven Proxy config file. I use something similar to the following (names changed to protect the guilty!):


################ GLOBAL SETTINGS
# This is where maven-proxy stores files it has downloaded
repo.local.store=./maven/repo-cache

#The port to listen on - not used if loaded as a webapp
port=8080

#This is the base area that all files are loaded from. While it is possible to leave this blank, this behaviour
#is deprecated and will be disabled in version 2.0.  There are too many namespace conflicts caused by not using
#a prefix.
#The repository will be shown at http://localhost:9999/repository/
#for the .war loaded into a webapp server, the default prefix is "repository" (edit the web.xml to change)
# As maven doesn't like a trailing slash, this address shouldn't have one either.
prefix=mvnrepo

#This is the simple date format used to display the last modified date while browsing the repository.
lastModifiedDateFormat=yyyy/MM/dd HH:mm:ss

################ SNAPSHOT HANDLING
#If you want the proxy to look for newer snapshots, set to true
snapshot.update=true

################ M2 METADATA HANDLING
#If you want the proxy to prevent looking for newer metadata, set to false (default is true)
#metadata.update=false

################ M2 POM HANDLING
#If you want the proxy to look for newer POMs, set to true (default is false)
pom.update=true

################ PROMOTION HANDLING
# ***** NOT CURRENTLY IMPLEMENTED *****
#Promotion describes the process by which new artifacts are loaded to global maven-proxy repository.  It
# is designed to be used by "higher security installations" that do not want to acquire artifacts from
# remote repositories without approval.
#
#If promotion handling is enabled, then the proxy will not download remote artifacts without permission
# (local repositories with copy=false are considered to be local)
#
#Permission to download is granted via the Promotion menu which will be enabled
#  when promotion handling is enabled.
#
#If promotion is false, artifacts are sourced from any repository as per normal.
#
#Promotion and snapshots:  If promotion is enabled, snapshots are not downloadable.  The concept of using
# a snapshot in a production build (which is primarily what promotion is for) is counterintuitive.
##
promotion=false

################ WEB INTERFACE
# This defines the absolute URL the server should use to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
# The prefix will be added to this for the actual repository
# i.e. proxy available at http://localhost:9999/, repository at http://localhost:9999/repository
serverName=http://localhost:8080

#If true, the repository can be browsed
browsable=true

#If true, the repository can be searched
searchable=true

#Not currently implemented. Will allow webdav access to the repository at some point.
webdav=true

#Stylesheet - if configured, will override the default stylesheet shipped with maven-proxy - absolute URLs only
#eg.  /maven-proxy/style.css, http://www.example.com/style.css
stylesheet=/maven-proxy/style.css

#bgColor / bgColorHighlight are replaced in the built in stylesheet to produce a simple color scheme.
#If a stylesheet is set, these are not used.
bgColor=#14B
bgColorHighlight=#94B

#rowColor / rowColorHighlight are replaced in the built in stylesheet to produce a simple color scheme.
#If a stylesheet is set, these are not used.
rowColor=#CCF
rowColorHighlight=#DDF


################ PROXIES
#This is just a hack, it should auto discover them
proxy.list=instagate

#Authenticated proxy
proxy.instagate.host=instagate.mycompany.com
proxy.instagate.port=8080
proxy.instagate.username=ccc
proxy.instagate.password=mypassword

################# REPOSITORIES
#This is not just a hack, it specifies the order repositories should be checked
#Note that the proxy adds a "/" which is why the urls aren't suffixed with a "/"
repo.list=local-repo,www-ibiblio-org,dist-codehaus-org

#local-store
# The local store represents a location that local jars you host can be located.
# This could also be achieved by having a local http repository, but this is less cumbersome
repo.local-repo.url=file:///./maven/repo-local
repo.local-repo.description=In-office Maven Repository
#If copy is true, jars are copied from the store to the proxy-repo. Only configurable for file:/// repos
repo.local-repo.copy=false
#If hardfail is true, any unexpected errors from the repository will cause
#the client download to fail (typically with a 500 error)
repo.local-repo.hardfail=true
#Don't cache a file repository
repo.local-repo.cache.period=0


#www.ibiblio.org
repo.www-ibiblio-org.url=http://www.ibiblio.org/maven2
repo.www-ibiblio-org.description=www.ibiblio.org
repo.www-ibiblio-org.proxy=instagate
repo.www-ibiblio-org.hardfail=false
#Cache this repository for 1 hour
repo.www-ibiblio-org.cache.period=3600
repo.www-ibiblio-org.cache.failures=true

#dist.codehaus.org
repo.dist-codehaus-org.url=http://dist.codehaus.org
repo.dist-codehaus-org.proxy=instagate
repo.dist-codehaus-org.hardfail=false
repo.dist-codehaus-org.cache.period=3600
repo.dist-codehaus-org.cache.failures=true


The important part is the local cache setting along with the prefix. The prefix controlls the URL that the proxy will respond to while the local cache setting controls where the proxy will write it’s cached artifacts that it gets from the internet. You’ll want to point the local cache property to a folder that has adequate space for a potentially large repository. You’ll note that I use relative paths for the cache setting. My paths are relative to the working folder of my servlet container’s process. If you get confused where your paths are relative from then use absolute paths. The other important setting you need to consider is the properties file location setting in the web.xml for Maven Proxy. I expanded my copy of Maven Proxy and edited the web.xml adding the following before repackaging everything up for deployment.

    <context-param>
        <param-name>maven-proxy.properties</param-name>
        <param-value>/home/newaredev/webservers/jetty-5.1.5rc1/maven/conf/repo-proxy.properties</param-value>
        <description>Controls where maven-proxy grabs its properties from</description>
    </context-param>

Lastly you ned to edit your settings.xml file that lives under the $HOME/.m2/ folder. My copy looks similar to this:


<settings>
	<proxies>
		<proxy>
			<active>true</active>
			<protocol>http</protocol>
			<host>instagate.mycompany.com</host>
			<port>8080</port>
			<username>ccc</username>
			<password>mypassword</password>
		</proxy>
	</proxies>
	<mirrors>
		<mirror>
			<mirrorOf>central</mirrorOf>
			<id>myproject-repository-repohost</id>
			<name>repohost Repo</name>
			<url>http://repohost.mycompany.com:8080/mvnrepo/repository/</url>
		</mirror>
	</mirrors>
	<profiles>
		<profile>
			<id>default-profile</id>
			<activation>
				<activeByDefault>TRUE</activeByDefault>
			</activation>
			<repositories>
				<repository>
					<id>myproject-repository-repohost</id>
					<name>repohost Repo</name>
					<url>http://repohost.mycompany.com:8080/mvnrepo/repository/</url>
					<snapshots>
						<enabled>TRUE</enabled>
					</snapshots>
					<releases>
						<enabled>TRUE</enabled>
					</releases>
				</repository>
			</repositories>
			<pluginRepositories>
				<pluginRepository>
					<id>myproject-repository-repohost</id>
					<name>repohost Repo</name>
					<url>http://repohost.mycompany.com:8080/mvnrepo/repository/</url>
					<snapshots>
						<enabled>TRUE</enabled>
					</snapshots>
					<releases>
						<enabled>TRUE</enabled>
					</releases>
				</pluginRepository>
			</pluginRepositories>
		</profile>
		<profile>
			<id>Snapshots</id>
			<repositories>
				<repository>
					<id>Maven Snapshots</id>
					<url>http://snapshots.maven.codehaus.org/maven2/</url>
					<snapshots>
						<enabled>true</enabled>
					</snapshots>
					<releases>
						<enabled>false</enabled>
					</releases>
				</repository>
			</repositories>
			<pluginRepositories>
				<pluginRepository>
					<id>Maven Snapshots</id>
					<url>http://snapshots.maven.codehaus.org/maven2/</url>
					<snapshots>
						<enabled>true</enabled>
					</snapshots>
					<releases>
						<enabled>false</enabled>
					</releases>
				</pluginRepository>
			</pluginRepositories>
		</profile>
	</profiles>
</settings>


One more word of advice would be to watch out under windows. When my buddy installed Maven 2 on XP somehow one of the default or example settings.xml files got considered before the one in his home folder. I cost us hours to figure out but afterwards we renamed all other occurences of the settings.xml file in the distribution and got around the problem. I would be a little more descriptive but it’s getting late in the day and honestly many of the details escape me. I believe everything I listed here should be sufficient enough for most people to get started. I have heard word of some alrenative solutions but I cannot remember the names. When I get time I’ll do the research and possibly set them up instead of our current proxy. Until then, hit me up…

Hallway usability testing


I’m seeing how important step 12 from the joel test is in software design. The most important part of any software product is usability. Usability is defined as:

The effectiveness, efficiency, and satisfaction
with which users can achieve tasks in a particular environment
of a product. High usability means a system is: easy to learn
and remember; efficient, visually pleasing and fun to use; and
quick to recover from errors.

If your product is not easy to use then it offers no real value to the user. Why? Because the user is trying to achieve a task with your software. The user chose your software as an effective, efficient, statisying means of accomplishing that task. That is where the value of the software lies. Forcing the user to learn your software or learn your way of thinking when they interact with your software is taking the main reason your software was choosen and tossing it aside. In other words you’re removing the only real valueable reason they sat in front of the interface to your product and replacing it selfishly with an introduction to how you think and work. Analogy: Suppose you asked me for a ride home from a party. Let’s say I agree to help but then I stopped by the ATM and ask you to pull out some money for gas. (Nothing wrong with that, right?) Imagine that I then forced you to take out an excessive amount (much more than $20) and used that money during our trip. Our trip includes several toll booths and turnpike fees. (Getting crazy but only if those tolls were along the way home right?) It involves a stop by a Burger King because I’m hungry and a pit stop by the club where I use your money for admission. We go around many different places and have an adventure. (Think Harold and Kumar.) Our trip finally ends in the parking spot in front of your home. Have I done you a service?

Unfortunately many software products behave in just the same way, they take the user for a ride to places they never intended to go. The big problem being the software forces the user to sacrifice his/her main mission soley because the developer had inadequately understood or cared for that mission. That’s the problem that results when you don’t prioritize testing. More accurately stated, that is the problem when you don’t prioritize the use requirements of the software. Starting on an implementation without a test harness is like starting down the road when I haven’t even asked where you live. “Yeah, we’ll get you home!”, goes the thought process but along the way lets have fun. It’s really fun to develop and really easy to get distracted even when you have solid clear requirements. It is possible to fill requirements accurately in absence of a test harness but you are far less likely to do so and far more likely to develop extra extraneous code. This article is not about the merits of Test Driven Development, though I had to sneak the idea in.

Why am I saying all of this? Bear with me, I’ll explain shortly. Right now lets talk about usable software. We should agree that it’s the most important thing. If your programming artifacts are not usable then you have a real challenge creating a usable product. Let’s think about that more closely. If you need to write code to use your product then your product offers no value. Zero value is realized. Nothing. It doesn’t matter how fancy the product is there’s nothing practical about writing software to use software. I exaggerate somewhat on that point but it is important to think that way when developing. The fact is that is is possible, always possible to create a product that requires no programming to use. (By the way, for the purpose of my argument let’s consider configuring through config files or command line options/switches programming because it is a means of encoding, or coding, your wishes in a dialect that is not english grammar.) More important is the fact that it is not any more difficult to create a product that requires no programming than it is to develop one that does require programming. In most cases I dare say it is easier to create a product that requires no programming to use. So why does there always seem to be a programming dialect, config file, or command line argument for most software? Going back to what I said earlier about prioritizing the requirements you will understand that the primary requirement for every piece of software is that it be easy to use. Better stated, the primary requirement is that the software be focused on getting the user’s task accomplished. That primary requirement is the first one to get dropped in favor of covering all of the potential situations it will be used. So a developer will typically prioritize the re-use of his/her soon-to-be-developed product over the initial use. Surely the product will be used in more than one way, even by the same users, right? So why not make sure a vast majority of the product does not need to be re-implemented?

The problem here is that when a developer does not focus on each requirement individually neither does the resulting product. Then you have some developers on the more extreme end that focus on all the possible end results of using their product before the thing even gets started. (They pose questions like, “What about performance and data volume? Will it clog the network? Can it talk through firewalls?”) That’s another topic for another discussion. Every developer loses focus from the primary requirement as soon as they begin development. So then the result is a bunch of code that either requires configuration, additional programming, or command line switches to operate, hard to use code.

Grab the next person in the hallway (or in the next cubicle) and ask them to use the product you’re currently working on. That highlights the primary requirement of your product. The first thing that person wants to do is use it. They want to accomplish the task that your product is supposed to assist them with. If they can perform that task without you telling them about your product then you’ve done a perfect job. If not then you have some polishing up to do on not only the interface but your approach to development. The day when we can have Hallway-usability-test-driven-development will be the day when all of the programming for programs starts to disappear. My point is the ignorant user (the person from the hallway) should be the primary driver of your development process. (At least have the guy in mind when you write the first lines of test or production code.)

Sidebar
Am I being overly critical of command line options? Perhaps but not by much. I believe that the simpler an interface is the more valueable it is, even and especially at the requction of features. It would be better to offer several commands for different tasks than it would be to offer a single command with switches.

Groovy Invaders V


Let’s add movement!
In our game we have a screen that shows all of the aliens and the ship on a black background. Now let’s make everybody dance. In the last part I had you define a bunch of empty subclasses. Why did I do that? Because I wanted to get off topic and show you how cool Groovy can be when it comes to mundane tasks like writing a bunch of redundant code. Well that’s not the only reason. We created subclasses because all of our Entity objects will behave diffeently. We want different behaviour right? You wouldn’t want the Ship to fly up the screen attempting to explode an alien would you? (Well that might make a cool game to but that behaviour doesn’t fit for classic space invaders!) So how does each game piece move?

ShipEntity
The ship is reeeal cool! It can move left all the way to the end of the screen and then when it gets there it can move right all the way to the other end! That’s it. No other movement. Ignoring how “way cool” our ship is, we dive into the code. (The TEST! We should dive into the TEST FIRST right? Well in practice I would dive into the unit test to describe my objects but since I’m copying somebody else’s tutorial and since that other person is smarter than I am I’m going to do as the other person did and dive into the code.) The only thing we put in the ShipEntity class is limits to prevent it from moving off of the screen.


package com.craig.groovyinvaders

public class ShipEntity extends Entity
{
    public ShipEntity(Game g, String spriteRef, def locX, def locY) 
    { super (g, spriteRef, locX, locY) }

    //These are closures or executable "method-like" things that return theresult of the enclosed expression
    def imAtTheLeftEdgeOfScreen = {(x < 10)} //an x coordinate less than 10 means we're at the edge
    def imMovingLeft = {(dx < 0)} //a negative x direction means we're moving left
    def imAtTheRightEdgeOfScreen = {(x > 750)} //an x coordinate greater than 750 means we're at the edge
    def imMovingRight = {(dx > 0)}//a positive x direction means we're moving right... Yaay!

    public void move(long delta) {
        if( (imMovingLeft() && imAtTheLeftEdgeOfScreen()) || (imMovingRight() && imAtTheRightEdgeOfScreen()) )
            return;

        super.move(delta);
    }

}


ShotEntity
If you think the ShipEntity is cool wait till you see the shot class. It moves in one direction mindlessly until it falls off the screen at which point it removes itself from the picture. How does it do that? On creation it sets its vertical movement speed to 300 pixels per second and in the move method it contiues until it falls off the screen.


package com.craig.groovyinvaders

public class ShotEntity extends Entity
{
    def moveSpeed = -300 //Speed of shot in pixels per second
    
    public ShotEntity(Game g, String spriteRef, def locX, def locY) 
    { super (g, spriteRef, locX, locY); dy = moveSpeed; }

    public void move(def delta) {
        // proceed with normal move
        super.move(delta);

        // if we shot off the screen, remove ourselfs
        if (y < -100) game.removeEntity(this);
    }
}


AlienEntity
Alright, how many of you have actually played SpaceInvaders in your youth? Don’t be shy, raise your hand. (Of course I can see you or else I wouldn’t have asked the stoopid question!) I ask because aliens are a little more involved and I wouldn’t want to lose any of you. If you’ve never seen or played SpaceInvaders then you wouldn’t be familiar with how the Aliens work their way left and right and down the screen trying to land on our ship.


package com.craig.groovyinvaders

public class AlienEntity extends Entity
{
    public AlienEntity(Game g, String spriteRef, def locX, def locY) 
    { super (g, spriteRef, locX, locY) }

    //These are closures or executable "method-like" things that return theresult of the enclosed expression
    def imAtTheLeftEdgeOfScreen = {(x < 10)} //an x coordinate less than 10 means we're at the edge
    def imMovingLeft = {(dx < 0)} //a negative x direction means we're moving left
    def imAtTheRightEdgeOfScreen = {(x > 750)} //an x coordinate greater than 750 means we're at the edge
    def imMovingRight = {(dx > 0)}//a positive x direction means we're moving right... Yaay!

    public void move(long delta) {
        if( (imMovingLeft() && imAtTheLeftEdgeOfScreen()) || (imMovingRight() && imAtTheRightEdgeOfScreen()) )
            game.updateLogic();

        super.move(delta);
    }

}


At this time it would be a good idea to move some code into our Base Entity class. Why? Well because both the ship and the alien need to ask the very same stoopid question.
Entity.groovy


    //These are closures or executable "method-like" things that return theresult of the enclosed expression
    def imAtTheLeftEdgeOfScreen = {(x < 10)} //an x coordinate less than 10 means we're at the edge
    def imMovingLeft = {(dx < 0)} //a negative x direction means we're moving left
    def imAtTheRightEdgeOfScreen = {(x > 750)} //an x coordinate greater than 750 means we're at the edge
    def imMovingRight = {(dx > 0)}//a positive x direction means we're moving right... Yaay!
    def iveMovedOffTheLeftOrRightSideOfScreen = {
        (imMovingLeft() && imAtTheLeftEdgeOfScreen()) || (imMovingRight() && imAtTheRightEdgeOfScreen())
    }

    public Entity(Game g, String spriteRef, def locX, def locY)
    {


While the ship asks if( iveMovedOffTheLeftOrRightSideOfScreen() ) return; the alien asks the same but answers differently. While we’re in the base class now would be a good time to point out a problem I’ve had with sub-classing in Groovy. We’ll need to change our move() method signatures from move(long) to move(def). (In Groovy the def keyword indicates an undefined type.) We are leaving the parameter passed into the move method undefined because calling super class methods with a primitive like long appears to generate runtime errors for some unknown reason. Hopefully the issue will be resolved in the next release of Groovy but for now we work around it by using def whenever we see such issues. That also means we must make sure it matches the move method as it’s defined in Entity.groovy, Ship.groovy, Alien.groovy and Shot.groovy. We need additional setter/getter methods for our movement variables in our Entity class. Our Game will later access these values to add control to our entites. Add these methods to Entity.groovy:


	/**
	 * Set the horizontal speed of this entity
	 *
	 * @param dx The horizontal speed of this entity (pixels/sec)
	 */
	public void setHorizontalMovement(double dx) { this.dx = dx }

	/**
	 * Set the vertical speed of this entity
	 *
	 * @param dx The vertical speed of this entity (pixels/sec)
	 */
	public void setVerticalMovement(double dy) { this.dy = dy; }

	/**
	 * Get the horizontal speed of this entity
	 *
	 * @return The horizontal speed of this entity (pixels/sec)
	 */
	public double getHorizontalMovement() { return dx; }

	/**
	 * Get the vertical speed of this entity
	 *
	 * @return The vertical speed of this entity (pixels/sec)
	 */
	public double getVerticalMovement() { return dy; }


Control
We want to let players control the ship so that it can line shots up with the aliens don’t we? Unless you want to give the aliens an unfair advantage your answer should be yes. Create a new class in the same package. (I know, all of our code has been in one package so far but bear with me!) Call it KeyInputHandler and make it extend java.awt.event.KeyAdapter so that it can respond to key presses. We’ll use our little KeyInputHandler to make our ship spring to life. (It’s also a cool place to put Easter Eggs! Don’t know what an Easter Egg is? How about up, up, down, down, left, right, left, right, B, A? You’ll learn in due time don’t worry!) The events we’re interested in are key presses and key types. In other words we want the ship to fly to the right when the player presses right, fly left when the player presses left and stop flying (moving) when the player releases the key. We also want a photon bean to emit from our vessel when the player hits the fire key. Ship control in our game will be controlled in the game loop by referring to a set of boolean flags. In every iteration through our game loop we will examine these booleans and tell our ship to act accordingly. The original tutorial uses an inner class for the KeyInputHandler and since Groovy doesn’t support inner classes and also since I’m too duhmb to dream up a reasonable alternative I give you the ugly hack. (Honestly, if someone can advise me better on what to do in these situations where it is common to use an inner class I would really appreciate it.)


import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent

class KeyInputHandler extends KeyAdapter {

    Game g

    public KeyInputHandler(Game game) { g = game }

	public void keyPressed(KeyEvent e) {
        g.leftPressed = (e.getKeyCode() == KeyEvent.VK_LEFT)

        g.rightPressed = (e.getKeyCode() == KeyEvent.VK_RIGHT)

        g.firePressed = (e.getKeyCode() == KeyEvent.VK_SPACE)
	}

	public void keyReleased(KeyEvent e) {
        g.leftPressed = (e.getKeyCode() == KeyEvent.VK_LEFT)

        g.rightPressed = (e.getKeyCode() == KeyEvent.VK_RIGHT)

        g.firePressed = (e.getKeyCode() == KeyEvent.VK_SPACE)
	}

	public void keyTyped(KeyEvent e) {
		// if we hit escape, then quit the game
		if (e.getKeyChar() == 27) System.exit(0);
	}
}


We need to define that set of boolean flags in our Game class

    //Control flags
    boolean leftPressed, rightPressed, firePressed


As well as registering our KeyInputHandler with out Game in the Game contructor: addKeyListener(new KeyInputHandler(this)) That code registers the Game with the KeyInputHandler then registers the KeyInputHandler with the Game and then registers the Game back to the key handler which is then registered to the Game after we register the… you get the point right? Ugly hack! So far we’ve left the little processInput method in our Game class empty. Now it’s time to fill it. With our key handler correctly (confusingly) registered we dive into the method and start telling our ship what to do there. Plop these lines in the middle of those curly braces after the processInput method:


        // resolve the movement of the ship. First assume the ship
        // isn't moving. If either cursor key is pressed then
        // update the movement appropraitely
        ship.setHorizontalMovement(0)

        if ((leftPressed) && (!rightPressed)) ship.setHorizontalMovement(-moveSpeed)
        else if ((rightPressed) && (!leftPressed)) ship.setHorizontalMovement(moveSpeed)


That’s enough to get our lazy ship moving. Oh, but wait! We referenced a moveSpeed variable so we should define that in the header section of our Game class. long moveSpeed = 300 //Speed of ship movement in pixels per second. Next thing would be to allow the player to shoot aliens. That is the sole point of the game anyhow, right? Read the following line of code and it shold read like pure English: if(firePressed) tryToFire()
That’s how you know when your design is looking good. When sections of code start to resemble grammatically correct english. Hold on! If fire pressed what? Which key do we anticipate fire will press? Well it almost makes sense if you don’t stare too hard! (Stop staring so dang hard!) Put that line after the others in processInput. Now why are we trying to fire instead of just firing? Well it takes a while for our photon beam to charge up so we need to simulate that with a call to method that dilly-dallys while aliens are marching towards us. Here’s the method that shoots the breeze between photon charges:


    public void tryToFire() {
        // check that we have waiting long enough to fire
        if (System.currentTimeMillis() - lastFire < firingInterval) return

        // if we waited long enough, create the shot entity, and record the time.
        lastFire = System.currentTimeMillis()
        ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30)
        entities.add(shot)
    }


That means we have to add more variables to our Game header to store the time the last shot was fired and define the firing interval.


	/** The time at which last fired a shot */
	long lastFire = 0
	/** The interval between our players shot (ms) */
	long firingInterval = 500


We have some more work to do in our Game class. Earlier we decided to call a method from our ShotEntity that would remove entities from the screen. We now need to define that method along with an additional list and logic required to make that happen. Rather than allowing an Entity to snatch itself from the screen abruptly we will treat the removeEntity method as a request method where requests to remove stuff can be made. We can then go about our game logic as normal and remove entities at the appropriate time. We need a removeList which we will define Groovy stile in the Game header section.
def removeList = []
We can then add the removeEntity method along with a helper method that actually performs the remove.


	removeEntity(def entity) { removeList << entity }

	def cleanDeadEntities() {
	    entities.removeAll(removeList)
        removeList.clear()
	}


We will then change the innards of our GameLoop as follows to perform the actual removal:


	    while(gameRunning)
	    {
	        def elapsedTime = calculateElapsedTime()
	        processInput()
	        display( moveSprites(elapsedTime,draw()) )
	        cleanDeadEntities() //Remove all dead objects from the screen.
	        delay()
	    }


Recap
Whew! It’s been a while since the last installment in this series and we’ve covered a lot of ground. I want to note a few things. First off, look at how some of the above examples are colorized while others are black and white. It took me a couple of days to write everything here and during that time WordPress introduced the ability to in-line CSS attributes. I’m too lazy and don’t have the time to go back and fix all of the examples. I make no apologies here as I believe the CSS thing should have been here all along and my Blog has been handicapped for a while as a result. Secondly I want to talk about some of the difficulties I faced. I had to change my coding style half way through this post as I noted the issue regarding subclassing above. Also, a Groovy committer pointed out that classes and methods within are public by default so there’s no need for the “public” key word. A lot of things are going on here and I plan to clean it up later. For now what I have so far gives me a very glitchy display where the ship moves and flickers. I can go on forever trying to figure out each problem but it’s time for another big break. I have real work to finish. If you’ve been keeping up I thanmk you and please feel free to comment and/or contribute fixes. I’ll try to post corrections later as well as what I hope to be the sixth and final part to my series. (Open GL refactoring will be in a different series at a different time.) For now, keep it movin’ and I’ll holla…