Just because it’s not an error doesn’t mean it’s right

*** This post belongs to https://bigendian.wordpress.com, all rights reserved ***

I was working on a PHP script the other day, and the damn bastard just wouldn’t work. I mean, the code was fine, no errors, no problems in compilation or anything like that. It ran perfectly, except that it didn’t do what I wanted. Worse than that: it was inconsistent about it, sometimes it was fine, and sometimes the results just didn’t make sense. It all depended on the input it got.

After much head scratching and dark thoughts about throwing my computer out the window and becoming a Shepperd, I found the problem: in one of the functions that was suppose to cleanse the input had a call to strripos when it really needed a call to strrpos, happens.

The thing is that this really shouldn’t happen, and if it does it shouldn’t take so long to diagnose. What a function does should be immediately and unambiguously clear by looking at its name. when you have strripos and strrpos, strtr and strstr, and stripslashes and stripcslashes, that makes it very hard to understand the code. I consider this readability problem to be one of the most fundamental flaws of PHP as a language. Luckily, this was a fairly simple and easily tested script. But consider having to read through 10,000 lines of code just to figure this out. (Yes, I know, you wouldn’t actually read all the code, you’d debug and trace the problem. But the point still stands that the code is harder to read)

Java, thankfully, does not do this. The naming conventions in Java describe ways to avoid this kind of scenario by outlining method names like “toString” “getVariable” and “isValid” which are self-explanatory. But this does not mean that Java is innocent of sin. Consider this scenario: You have a class MyClass and you need to write two constructors for it. Each constructor gets a JFrame and a String, and based on which ones it gets, it will show different information in the frame.

Now, since these are constructors, you can’t give them different names. And since they both have the same number and types of variables, you can’t distinguish them that way. So what you end up doing is distinguishing between them based on the variable order: One constructor is going to be MyClass (String, JFrame) and the other will be MyClass(JFrame, String). All perfectly legal in Java and aren’t you smart.

But now you face the same problem that I faced earlier in PHP: your method calls are non-descriptive and you can’t, based on the method name and signature, tell which constructor your actually using. Sure, you remember which is which now, but what about in six months when you have to get back to it and you’ve forgotten it all, or worse, someone has to maintain your code?

There are several solutions to avoid this kind of problem. My personal favorite is the one suggested by Joshua Bloch in his book “Effective Java” where he recommends using static factory methods instead of constructors.  Consider the two constructors above: If you made them private and instead added static methods with distinct names static getNewMyClassA and static getNewMyClassB you would eliminate the confusion and make it unambiguously clear as to which method does what. Furthermore, you’d gain much greater control over your Object creation, allowing your class to offer objects out of a pool, for example, rather than creating a new object every time. You also have a polymorphic advantage: a static method can return an object of any subclass of its return type, which can be handy.

Debugging and maintaining code are some of the most challenging tasks that a programmer can face. Sometimes, making the code more readable can be the only thing between you and a life as a walking sheepdog. 🙂



A rose by any other name… Object serilization and the Java JVM

***This post belongs to https://bigendian.wordpress.com. All rights reserved ***

Consider the two classes here. They’re identical in every meaningful way. The one on top belongs to a server application of some sort, whereas the one on the bottom belongs to the client to the same server. Both classes have the exact same members, methods, and constructors. Both have the same name. And both implement the serializable interface, which designates them as being able to be written out and read as complete objects. If you are not familiar with the wonderful world of Java serialization, look here

Now lets say that I have a server program that looks something like this:

ServerSocket sSocket = new ServerSocket(12345);
Socket iSocket = sSocket.accept();
ObjetOutputStream OOS = new ObjectOutputStream(iSocket.getOutputStream());
OOS.writeObject(new MyClass(10));
ObjectInputStream OIS = new ObjectInputStream(iSocket.getInputStream()):
MyClass aMyClass = (MyClass)OIS.readObject();

We also have a client class that looks like this:

Socket cSocket = new Socket(IP_CONSTANT, 12345);
ObjectInputStream cOIS = new ObjectInputStream(cSocket.getInputStream());
MyClass cMyClass = (MyClass) cOIS.readObject();
ObjectOutputStream cOOS = new ObjectOutputStream(cSocket.getOutputStream());
cOOS.writeObject(new MyClass(10+cMyClass.getT());

If you’re not sure about the flow here, it goes like this:

Server runs, and blocks on accept();

client runs, connects to server, and blocks on readObject

server unblocks at accept, transmits a MyClass object on the stream and blocks on readObject()

client unblocks on read, gets the Object object, casts it to a MyClass object (since readObject() returns an object of type Object), manipulates it, and sends it back to the server.

server unblocks on read, gets the Object object, casts it to a MyClass object, gets the value from it and prints it out

Now here’s a trick question: What the final output of the server program?

Well as it turns out the output is an exception that looks something like this:

 at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2281)
 at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2750)
 at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:780)
 at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)

Furthermore, the client program will throw it’s own exception:

java.lang.ClassNotFoundException: com.mycomp.myprod.server.common.MyClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1575)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)

What happened?  We serialized an object, sent it over a stream, deserialized it, cast it back and then did it again the other way. This is exactly what serialization is designed for. Yet it seems to fail even at this humble level.

The critical error is the ClassNotFound exception for MyClass.  The JVM can’t find an object that fits this discription, so it throws an error. This causes the receiver to not run at all; which in turn causes the sender to shutdown with an End Of File. Although both the server and the client have a copy of MyClass, and as we’ve shown in the beginning of the post, they are identical, the JVM isn’t happy. It doesn’t just want an identical class, it wants the same class. client.MyClass and server.MyClass may be identical, but they’re not the same.

If you think about it, this makes a lot of sense. The JVM has no way of knowing that client.MyClass and server.MyClass are the same. As far as it knows there are also a foo.MyClass, a bar.MyClass, and an iphonesarebad.MyClass, each with different purposes and construction. But when the JVM reads the object head from the stream, it is told to look for a server.MyClass, and that’s exactly what it does. No class, no dice.

Note that this is not a ClasssCastFailed exception. The JVM never gets that far, and never gets to try and cast the object into the local form of MyClass. It simply looks for a class on the output side of the stream that matches the class that was present on the input side of the stream which means looking in the the directory specified by the class name (/com/mycomp/myprod/server/common) for the file specifed by the class name (MyClass.java).

How do you get around this? Simple: Make sure that in both client and server the class you are serializing resides in the same relative path. This way, when the JVM looks in the path to find the class definition, it actually finds it, and everyone is happy. If you are really slick, you can put all of the code that’s common between the client and the server in its own JAR, but’s that’s a discussion for a different day.


De-Coupling MVC with Facade classes

Please note: The original url for this post is: https://bigendian.wordpress.com/
If you are reading this on any other web site, this content is stolen.

One of the best and worse things about Java is the easy way it allows you to create GUI elements and their associated commands together, which makes for very simple way to develop user interfaces.  This is one of the best features because it allows developers to concentrate on developing program logic, and simplifies interacting with the user to a level attainable even by beginners. It is one of the worse because this integration can lead to a very tightly coupled View and Control. Two of the three major part of the Model View Control (MVC) design pattern. MVC calls for each part to be separate and independent, so as to allow better code re-usability, easier maintenance, and better task grouping. This is certainly possible in Java, but requires more work then just building the control logic right into the GUI classes, and so developers don’t always bother to make the separation.

My current project, for instance, uses exactly this kind of tight coupling, which I’m trying to undo. I am looking to separate the view and the controller into independent code, and actually into different programs. The controller and model code requires administrative privileges to run and need to run all the time, while the GUI code requires just regular user privileges and only when the user wants it. So I’m separating them into two separate programs which will communicate over a shared channel.

The problem, as I mention, is that my GUI and the actions that it creates are coupled very tightly with the controller code itself. There is no point were controller threads are registered on GUI components and get notify()ed of state changes (yes, a Java method as a verb. Live with it). Rather ActionListeners directly invoke methods in the controller classes to make things happen in the program. It works, but it’s a bit messy, and can be a real problem considering that in the new paradigm, all commands and feedback are going to travel over one point of contact (the Channel). There are twenty-some methods being invoked from three classes that are part of the program cotroller. All of thoes need to be brought under one roof.  I could rewrite every one of them to call my ChannelCommunicator class instead, and ask it to transmit the command to the controller, but this is both tedious and potentially dangarous since I don’t know what else in the code is dependet on those methods being invoked in this certain way.

Facade classes to the recue! A facade class is a class which presents a simplified view of a subsystem and makes it easier to use. In my particular case, this means that I can create a facade for each of the three classes mentioned above. The facade function as an abstraction layer which implements the methods that my GUI classes expect to finds on on side, and passes calls to the ChannelCommunicator in a unified way on the other side. The GUI is happy because nothing has changes (except for the class name), the ChannelCommunicator is happy because it gets one type of call and doesn’t need to deal with special cases, and I’m happy because I don’t have to re-write every method that’s involved! Fantastic!

The thing to remember about this paradigm is that your facades come in pairs, and thus there is a certain amount of duplication involved. Why pairs? bacause I have to put a facade for the controller between the GUI and the ChannelCommunicator and, on the other side, I have to put a facade for the GUI between the ChannelCommunicator and the controller. The nice part about it is that these classes are really nothing more than parsers which translate the specific format of each command into a standard format the communicator can understand, and parse it back on the other side, so the logic involved is not very complicated. Still, this is a stopgap solution to allow MVC decoupling without having to redesign major parts of the code. In a perfect world you’d be better off re-writing the methods. But then, in a perfect world you wouldn’t have this problem to begin with. 🙂


P.S. To learn more about design patterned I would highly recommand Bruce Eckel‘s book Thinking in Patterns, which is available to download for free.

Do you understand the words that are coming our of my keyboard?

I happened across an interesting article about OpenXava today. OpenXava is a platform for Java Enterprise applications that promises to simplify code development, which is a great idea. But what struck me about the article was actually the opening paragraph:

OpenXava 3.1.3 is a framework to develop Java Enterprise applications in a different way: OpenXava avoids MVC. It’s a JPA Application Engine in that you provide only your POJOs annotated with JPA and you obtain an application ready for production.

With OpenXava, you only need to write your model, POJOs with annotations. You do not need to write the view, and the controller (for CRUD, printing, etc) is reused.

If you are scratching your head at this and reaching typing in Google for translation, you are not alone. Sure, it makes it sound all hi-techie and complicated when there are a ton of acronyms and abbreviations, but that also makes it harder to understand. What the guy meant was that you can use plain Java to create enterprise applications without having to go through a lot of the grunt work. As far as  introductions go, I think that would have been sufficient. There really is no need to make things sound more complicated then they are, and don’t always assume your readers know what you’re talking about. For any one who is still interested, the full article is HERE.

On the same topic, I’ve been meaning to write a post about the wonders of commenting your code, and why it’s so important to do it, and do it right. But then I discovered 13 tips to comment your code – a wonderful piece originally written in Spanish by José M. Aguilar in his blog, and translated into English by Tidarat Chamnasri Timm Martin (Thanlks, Tidarat, For the correction). It’s something that anyone who write code should read at least once a week. Or possibly (in the case of certine people) have ingraved into their forearm.  🙂

And finally, for anyone who hasn’t seen it, I’d recommand going to http://www.tengrandisburiedthere.com. If you don’t get it, look here.

Good Weekend,