Entries Tagged 'Java' ↓

Getting rid of getters and setters

Today I read an interesting post about mistakes Java programmers make when they start writing Python code. The one that really caught my eye was “Don’t create getters and setters!”. Apparently a lot of other Python newbies are doing that.

I started out creating getters and setters in python a while ago and in the last month or so (while refactoring) it occurred to me that it was a waste of time since you can’t make member variables in python private like you can in Java. The more I thought about it, the more I started to wonder why I was doing straight getters and setters in Java. I mean, if all I’m doing is assigning a variable (no format checking, etc.), the having that extra code doesn’t really make much sense does it?

So, I’m on a fact finding mission to discover the what happens when getters and setters are left out in Java code and the class field is accessed directly. Yes, I know, its not OO. But if the object is just a bean and its only reason for existence is to be an member of an abstract data type (like a struct in C), then why not just let it run free? Aside from situations where you are manipulating the field in some way (like formatting, or whatnot), all the getters and setter get you is more code on the screen.

Business Rules and the Visitor Pattern

One thing I really love about Python is that you can really knock things out quickly with it. I’ve been thinking about business rules lately, and specifically about how to make them cleaner with respect to your code.

When it comes to rules, there are several places and ways you can encode them in your application, each with its own pro’s and con’s. Lately I’ve been reading a lot about Lisp based languages and every now and then I’ll read a reference to using Lisp code not only as a configuration file, but as a “executable” that carries its own data.

The more I thought about this, the more I wondered if this type of separation was possible in Java. Sure, I could just code the rules in Java, but where’s the fun in that? Via its reflect package, Java can do some pretty neat tricks, so I decided to try and code up some ideas in Python first since its so concise (and can also do reflection, etc.). Basically a case of “anything you can do, I can do better”.

A while ago I read a really interesting article about the visitor pattern. Most of the time this pattern is explained in terms of something like a driver: You have some kind of hardware that needs to call a driver to setup its connection to the system. Using the accept() and visit() methods you can make a class that can register itself with the caller and allow it to configure itself, the end result being that the caller doesn’t need to know (i.e. be linked with) the details of the visitor.

It occurred to me that this is the same situation with externalized business logic: The rule engine is reading in an external file and then based on the contents of that file, executing code. If a “rule” implemented the visitor pattern, and the “rule engine” implemented the accept(visitor) method, then this would allow the external file to dictate what the program would be doing without the program needing massive changes to alter the rules.

It boils down to this: defining the core actions separately from the rules allows a better separation between  the two. The visitor pattern allows the two to be bound together. The end result is cleaner (smaller) code, that should be more “testable”. At least that’s my theory.

I’ve put the python code implementing this up on my project page (here is the code). Its a very simple example, there is one rule per line, and the first token (space delimited) is the function to call followed by its arguments. Internally the RuleEngine class is calling Python’s eval() function and that is what actually executes the function from the data.txt file.

For the function to execute successfully it needs to exist (i.e. it needs to be defined in the file, or be a built-in Python function). Note that this is not the safest approach, it will allow malicious code to execute. A more secure way to do this would be to set up a dict (or, if this is done in Java a HashMap) that contains a mapping between the rule tokens and the function to be executed. That way the execution of the RuleEngine can be controlled somewhat, in that it will only allow certain functions to be executed.

Refactoring observations

Its almost spring time and I’ve been doing some spring cleaning both at work and at home. Yes, its refactoring time.

For the most part I like refactoring. It’s a chance to go back and tighten up the code, correct earlier guesses, and just make things nicer looking. One thing that has really been hammered home to me is the type of refactoring you are trying to do depends greatly on the underlying design and what you are trying to change about it.

Example: One of my home projects is an RPG game written in python. I started out with one code base, and began changing it to meet my ideas/needs. Over time it has change two more times. Yesterday I noticed that a major class (the display that draws the tiles to the screen) had not really been migrated and could use some attention. As I began trying to work in the new changes I saw why I put the project down a few months ago: there’s got to be some major changes because the class is so different than the new architecture. As a result, most of the refactoring tools/techniques I’m used to using (at work)
just can’t be used right now.

At work, I’ve got a pretty well laid out architecture (coded in Java) and most of my refactoring work revolves around streamlining and consolidating methods and classes. The refactoring tools in Eclipse make this a breeze because everything is pretty straightforward. (Also, the strong typing of Java is really helpful in this area, its much easier for Eclipse to figure out what a member variable is in Java than it is in Python.)

The moral of the story? I think it’s best to make sure you build in some flexibility to your designs. This will allow you more choices down the road, especially as you discover new techniques for your particular language. As always, the tools are helpful, but they can only do so much to help you.

The joy of Java

I’m taking a class in programming languages and recently we had a home work assignment that involved writing a C++ program (to deal with multi-dimensional arrays, pointers, etc.). It has been a while since I’ve written any C++ code, so this was quite an experience.

I managed to more-or-less get the program done, and at the end of it all, I had an overwhelming thought: I’m glad I work in Java.

C++ is fun in its own way, but the whole time I was coding I kept feeling like I was doing something wrong with all of the jumping around in memory locations, and playing with pointers. In Java, you just don’t do those types of things. Also, every time I ran into an error, it seemed to be pointer related. I haven’t had to use the debugger to look at memory locations in a loooooong time.

I really like the secure feeling that Java gives me when I’m working in it. I also feel like I’m more productive, but that could be a result of being more “current” with Java’s libraries, vs. C++’s libraries.

Also, as an odd note: I never understood why all the Mac developers talk up TextMate so much and how it works great with Xcode. After spending this last homework working with the default editor in Xcode, I totally see why. Any editor that asks me “Are you sure you want to undo?” when I press Ctrl-Z (or Cmd-Z in the case of Macs) instantly looses about 50 points in my book. Add on to that there seemed to be no auto-completion for classes built in (or at least turned on) and it makes the IDE pretty poor in my view. The rest of Xcode seems pretty good, but that editor sucks and has got to go. It looks like I will need to search for a decent editor that can work with Xcode. (I tried TextMate, and its missing some feature I feel I need.)

An ordered HashMap in Java

HashMaps are pretty cool, they allow you to access you information using a “named” index. They aren’t as good/useful as Python’s dictionaries, but they are still really useful. (In Java, the key and the value have to Objects, so using primitives like int are out. Which is a bummer because while you can create an Integer out of an int, it leads to more code which looks less streamlined. Python doesn’t have this problem because everything is an Object.)

It seems like I’m always using HashMaps to organize my data. The other day I ran into a situation where I needed to pull the keys from the HashMap in the same order that I put them in. I’d never run into this particular scenario before, so I didn’t really give it much thought until I kept noticing that my keys were coming out in a crazy order (i.e. not in the insert order, and not in alphabetical order either).

My first thought when I need something in an ordered collection in Java is to run to the TreeMap (or TreeSet depending on the data situation). TreeMap will keep the keys sorted, so I thought all was well. When I tried it out I found out that because I was using Strings as the key, it alphabetized them, which is not what I was looking for.

The data structure I was looking for is the LinkedHashMap. It keeps track of the keys based on insertion order, so that when you do a call to getKeySet(), you will get the keys back in the order you put them in. Once I started using LinkedHashMap, everything started working perfectly.

Sometimes it pays to look around the API a little bit and see what all is out there. I’ve been running around the java.util package for a while now, but until this requirement came up, I’d never even given LinkedHashMap a second look.

And since LinkedHashMap derives from HashMap, you can use it in the same places as you would a regular HashMap (i.e. use the Map interface in your method calls) and no one would notice the difference, other than the sorting of the keys.

Now I remember why I like Java and Python

I just had to whip up a quick little program in C++ for a class I’m taking. I used to do a lot of C/C++ coding, but that was a while ago and it shows. My first pass at writing the program compiled great, but once I started running it I began to notice that under certain conditions it would crash.

Since its been a while since I’ve written any C++, it means its been a while since I’ve debugged any C++. So I spent about a half hour trying to figure out what EXC_BAD_ACCESS meant. It meant that I had forgotten about the joy of pointers. Then once I realized that, I spent another half hour trying to find out how do a dynamic multi-dimensional array in C++. The kinds of things that are second nature to do in Java and Python (which is where I spend most of my days).

The major lesson learned? A friend at work likes this quote from Martin Fowler: “Experience and knowledge are expiring assets.” In other words: Use it or loose it.

I got a MacBook

A few weeks ago I went and got a MacBook. I’m really digging it, it feels so much faster than the MacMini. Plus I’m loving the widescreen on the MacBook, I’ve been wanting a widescreen monitor for a while, but have never had the opportunity to get one.

In case anyone out there is wondering about the pro’s and con’s of getting an ICBM (Intel Chip Based Mac), I thought I would toss out my thoughts on the topic:

  • Speed- It is sooooo much faster than the old PPC machines. Don’t get me wrong, the PPC machines are fast, but the duo core aspect of the MacBook makes everything that much faster.
  • Ease of Upgrade- I bought 2GB of RAM and dropped it in the machine after I got it all set up. That has made all the difference in the world. The Mini only had 512MB, and I think that really holds it back. Being able to get 2GB for less than $200 was a no brainer, and the performance is phenomenal.
  • Heat - The MacBook gets hot. Real hot in some spots. The Mini is one of the best combinations of speed and coolness that I have ever seen. Most of the time I don’t have the MacBook on my lap, but I’m still concerned about heat.
  • Compatibility - The Intel based machines are supposed to support the old PPC binaries, and for the most part I have found this to be good. However, I did find two glaring problems right off the bat: Eclipse and NeoOffice. Both of these programs would not start up. It turns out that Universal Binaries are right around the corner for both. I thought it was odd though that both apps (which are Java based) wouldn’t run. It turns out there is some JNI in the background and that’s where the problems were. Once the Universal builds are released (I think Eclipse is already out with its 3.2 release) that should solve those problems. Also, I’ve found that PyGame isn’t 100% functional on the MacBook, but I’m thinking I might have done something to cause that. (More on that later)
  • Form Factor - Both the Mini and the MacBook are just slick looking machines. Thin, compact, yet packed with power. Its great! I recently took the MacBook on a trip and it was a breeze to bust it out and knock out some code. The built in Wi-Fi is great, though sometimes I wish I could get a little more detail out of it (Windows machines have a really good interface for its WiFi stuff, its great for users who want more advanced information).

Overall I’ve got to say the MacBook just rocks. :)

java.lang.StringBuffer Blues

Although we live in the future, and in the future everyone uses XML, there are still times when you need to interface with something that uses fixed position strings to relay information. This happened to me the other day at work and I thought I would share somethings I learned.

My first thought was to find something that would allow me to insert characters into a String at a specified point. Strings are immutable, so they aren’t ideal. The StringBuffer class is designed to be manipluated, so it seemed like the perfect fit. Looking through the API docs I saw that it had useful sounding methods like “insert()”.

Boy was I in for a shock.

When you build a StringBuffer, you can specify the length of it. Since I’m going to be building a String of a specific length it seemed like a snap, just build a StringBuffer of that length. But when I tried to use that StringBuffer, I kept getting index exceptions.

It turns out that when you pass in a number to the constructor it allocates the space (plus 16), but doesn’t put anything in it. For some reason when I started putting strings into the StringBuffer (via the insert() method) I would eventually get the error. Stepping through the debugger showed that the buffer was allocated, but something just didn’t seem right. When ever I would try to print out the StringBuffer it never seemed right, like it was stopping in the middle for some reason.

So, as a quick test I used the constructor that allows you to pass in a String, and I passed in a String of spaces that was the right length. Lo-and-behold everything started working correctly. That was slightly annoying to me because from everything I read it seemed like I shouldn’t have to pass in a string of spaces in order for this to work.

As as side note, I really really really don’t like variables that are just strings of spaces that have to be a certain length. It is almost impossible to count out the spaces, plus if someone ever accidentally removes/adds a space it is a pain to debug. It is much better to specify a length and then build the string of spaces at runtime (if it simply must be done).

So, once I had that figured out I thought it was going to be clear sailing. Ugly, but clear. Wrong again. It turns out the insert() isn’t the best choice for inserting things. Insert doesn’t overwrite anything in the buffer (which is cool, but now that I have my crazy String of spaces I would prefer it to overwrite, but hey this ain’t Burger King so I’m not gonna get it my way). Instead it simply inserts. Which eventually causes the index exception. D’oh!!!!

It turns out that replace() is a much better choice. However it requires a lot of parameter to be passed in, and soon the code I was writing looked like a war zone. So at this point I had to create a new Class to wrap up all of the ugliness and still keep it useful.

It turns out this was a pretty good move to make, because a little while later I discovered that there were times were I would want to insert something, but have it justified one way or the other. Simply adding a method to my new class allowed me to keep the code nice a clean, and debuggable (because all of that logic was contained in once place). Score one for Object-Orientation.

Anyways, the moral of this story is that the Java API is pretty good, but is lacking in some areas (don’t get me started on the nightmare that is the StringTokenizer class). A well crafted wrapper class can help create the functionality that might be missing and also allow you the chance to keep your main business logic code looking clean. Plus the benefit of having that kind of code (the kind that is subject to changing requirements) in one place for debugging and maintenance can not be understated.

More thoughts on being a better programmer

Ned Batchelder’s site is always a good read, he’s very insightful about the art of programming. When I saw his posting that Joel Spolsky is a crotchety old man, I couldn’t wait to see what his thoughts where.

When I wrote about Joel’s article I was feeling a little bit down, Joel pointed out something that I knew deep down, namely that programmers today (i.e. me) aren’t quite the same as programmers from yesteryear. Java and other “layers of abstraction” have taken us away to a weird place. Its almost like you don’t have to think as hard to be a programmer today.

Ned pointed out that this isn’t 100% true, its more like you don’t have to think the way you used to. He points out that assembly language and a good knowledge of the inner workings of the computer were necessary to perform the job role of a programmer. These days, a lot of schools aren’t really teaching assembly, and using it in a day-to-day job is becoming rarer and rarer.

Is this “loss of knowledge” really a sign of how bad things have become? Not necessarily. A lot of systems and languages these days go to great lengths to hide the implementation details of the underlying hardware from the developer. Java springs to mind as an example of this. A Java developer doesn’t need to understand what the value in the IP register is.

BUT… if the Java developer does understand how a computer works at a low level, then they probably would have a better insight into performance issues, threading, and other dark corners of computer science.

After thinking about both articles I’m starting to think that while they both have a good point, Ned is really onto something. Perhaps what the computer scientists/developers/programmers of today are missing is the understanding of the computing machinery. I know when I recently took a computer architecture class, I found it very enlightening and I haven’t really looked at any programming language the same since.

Being a better prorgammer

Every now and then when I’m feeling nice and confident about whatever it is I’m doing, something will come along and knock me down a peg or two.

Lately I’ve been feeling really good about my development skills. I’ve been thinking a lot about things like refactoring, architecture, reusability, maintainability. I feel that while I’m not a master yet, I think I am well on my way to honing my Jedi skills in the area of software development.

That is until today. Today Joel published an essay about how the schools these days are focusing in on the wrong things (pushing Java and not other languages that require more thinking) and basically not pushing the students hard enough. The article is here:The Perils of JavaSchools

After reading the article I was pretty depressed. I thought I was doing ok, but now I think I need to make sure I master the art of thinking, not just the art of implementing whatever Sun (or whoever) is spouting about this week.

Like Bea, if I am to survive the cruel tutelage of Pai Mei, I will simply have to buckle down and do it. Nothing worth having comes easy, and having the knowledge (and the power that comes with it) that Joel speaks of is something worth having.

It looks like it is time to break out the Little Lisper and begin the training…