Archive for the 'java' Category

The Matrix (Multiplication)

Monday, October 23rd, 2006

How come Java does not have a matrix datatype? It has everything under the sun, and a bag of chips but no matrix datatype or object in the API? Sure, I can easily simulate it using a 2D array, but that’s not the most convenient thing in the world. So I started writing my own matrix class which would allow me to do something like this:

dp = a.traspose().multiply(b.add(c)).dotproduct(d)

That thing above is totally meaningless, and I made it up on the spot, but these are the kind of calculations I’m currently working at. If I could just call methods instead of writing nexted loops all ver the place both writability and readability of my code would improve greately.

But then I remembered that I will have to pay in blood for every single method call inside my monstrous loops. First thing I needed to do with my old code was to remove every method call that was not necessary from the part of the code that iterates for a long friken time.

So instead I decided to just leave it alone, and keep decorating my code with things like:

for(int i=0; i<A_ROWS; i++)
for(int j=0; j<B_COLS; j++)
for(int k=0; k<A_COLS; k++)
result[i][j] += a[i][k] * b[k][j];

The sizes of the matrices are known from the start and do not change, so I make them into constants. This way the values are inlined at compile time, and I shave off few millisecods of a memory lookup. Then I try to squeeze more than one, unrelated matrix multiplication into the same loop. P

So once again, you can either modularize or optimize but you can rarely have both at the same time…

Multiple Inheritance in Java

Thursday, September 14th, 2006

Java has no support for multiple inheritance, right? At least that’s what you have been told. You can’t explicitly declare a class to be a child of two different unrelated classes. That is true. But you also need to remember that you can always walk up the inheritance tree which may give you a way to circumvent this rule.

Let me give you an example. I’m currently working on a multi-threaded matrix factorization algorithm. So I have a class called Factorizer which extends Thread and implements the logic of the algorithm. I needed to slightly modify this algorithm and change the logic in 2 or 3 methods. I really don’t like copying and pasting large volumes of code so I decided to simply inherit everything from Factorizer and then overload the methods where appropriate.

When I extend Factorizer, I implicitly inherit all the functionality of it’s parent which is Thread. This was essentially a no-brainer, but if you think about this in the end I ended up with a class that inherits from two wildly different parents.

But how to apply this logic to real life situations? Let’s try to come up with a good scenario when a multiple inheritance would be desirable. If you will, imagine that we have two classes called Camera and Phone:

public class Camera
{
public void snapPicture() { // lots of code }
}
public class Phone
{
public void makeACall(){ // lots of code }
}

You want to create a new class CameraPhone. Ideally you would want to inherit all the code from both classes so that you don’t have re-implement anything. Unfortunately in Java this is impossible. You could rewrite Phone as a child of Camera, or Camera as a child of Phone but neither one nor the other makes much sense with respect to the conceptual design. This is the type of conundrum that you may possibly encounter in Java world, albeit very rarely if ever. What do you do?

You go back to the drawing board and rethink your design. When dealing with single inheritance we usually want to design from the most general, to the most specific entity. We could argue that CameraPhone is a more general design element because both Phone and Camera can be defined as it’s sub elements. So if we flip the inheritance tree on its head, we get a classic, Java kosher, single inheritance. So lets put all the functional code in the parent:

public class CameraPhone
{
public void snapPictute() { // code }
public void makeACall() { // code }
}

Next we simply do what many manufacturers out there do when they decide to sell low end, cheep versions of their products - disable features:

public class Camera extends CameraPhone
{
public void makeACall() {}
}
public class Phone extends CameraPhone
{
public void snapPicture() {}
}

I’m simply overloading unnecessary methods with empty definitions, but you can probably do something more clever. For example you may return some default value, throw an exception, etc.. The best part is that both Phone and Camera will continue working in the same exact way they did before. Any code that depended on these classes being there will still work. But now we do have a class that combines characteristics of the two. Is this multiple inheritance? No, but it works. Would it be more logical to do it the other way around? Maybe, but who cares. This solution makes sense both conceptually, and code wise.

Any time you run into a multiple inheritance problem, try to think about it in terms of design. You can’t circumvent Java’s inheritance rules, but you can you can probably restructure your code to rout around this issue.

Update Fri, September 15 2006, 08:59 PM

Here is another solution suggested by ZeWrestler. Create a wrapper class that would include both Phone and Camera:

public class CameraPhone
{
private Camera c;
private Phone p;
public CameraPhone(Camera c, Phone p)
{
this.p=p; this.c=c;
}
public void makeACall() { p.makeACall(); }
public void snapPicture() { c.snapPicture(); }
}

This is probably the best thing to do if you just can’t modify the existing classes (for example, you have no access to their proprietary code). What is the downside here? You get a performance hit because instead of one method call you have two. If you can live with that, you should be fine. Also, you can’t down-cast CameraPhone back to Phone if you need to.

I think I can one-up that. The most elegant solution would be to create interfaces for both Phone and Camera:

public interface CameraInterface
{
public void makeACall();
}
public interface PhoneInterface
{
public void snapPicture();
}

You can now create Phone and Camera classes that implement appropriate interface. Finally when making your CameraPhone you implement both, and use wrapping as above:

public class CameraPhone implements PhoneInterface, CameraInterface
{
private Camera c;
private Phone p;
public CameraPhone(Camera c, Phone p)
{
this.p=p; this.c=c;
}
public void makeACall() { p.makeACall(); }
public void snapPicture() { c.snapPicture(); }
}

There you have it - an elegant solution to the problem with total code reuse, and only a small performance hit.

Arcane Java Operators

Friday, April 21st, 2006

I previously posted about the nifty ?: Java operator that I personally love, but that I never see in the code. And then I realized that there are quite a few instances of Java specific stuff that no one really knows or cares about. It seems that most Java instructors these days are C++ people who read a Java book - and thus they rely heavily on their C++ experience.

And that’s fine, you can really survive in Java world with a C++ like mindset (as long as you don’t try to pass integers by reference). But you miss out on all nifty little language nuggets and syntactic sugar that Java has to offer.

For example, Let’s say you have an ArrayList, a Vector or another Collection class. At some point you want to extract something out of it. Since you populate your collection class you know what should be in it. But what happens if someone sticks in an Integer into a Vector that should contain only Strings?

You can always do this:

try
{
    Sting foo = (String) vector.get(i);
}
catch(ClassCastException e)
{
    // error handling
}

This is IMHO a PITA. Of course Java has a much more elegant solution to a problem like that. It is the instanceof operator:

if(vector.get(i) instanceof String)
    // do something
else
    // error handling

Java will gladly let you know, what type of object you are dealing with, as long as you ask it the right way. Granted that this example is trivial, but in the long run, instanceof can save you allot of catching and handling runtime exceptions.

Operators such as instanceof or ?: do not exist in C like languages. So most C oriented Java instructors ignore them completely.

Allot of programmers do not understand the this keyword. For example most people do this:

public class Foobar
{
    private int foo, bar;
    public Foobar(int a, int b) { foo = a; bar = b; }
    public Foobar(int a) { foo = a; bar = 0; }
    public Foobar() { foo = 0; bar = 0; }
}

This is an ok code, but imagine having 5 or 8 fields to handle. It becomes real messy, really quick. What if you have 12 constructors need to change the name of bar to something else? What if you decide to initialize values to 1 instead of 0?

What you shour really do is this:

public class Foobar
{
    private final DEFAULT =0;
    private int foo, bar;
    public Foobar(int a, int b) { foo = a; bar = b; }
    public Foobar(int a) { this(a, DEFAULT); }
    public Foobar() { this(DEFAULT); }
}

This is a good coding practice from the get-go. If you ever rename your fields, or change the default initialization value, all you need to do is to edit the top constructor. If your code is written well, you rarely need ractoring tools for minor stuff like this.

I think there is simply a fundamental issue with teaching the students to use the correct tools for the right job.

I cannot tell you how many times I have seen people implementing XOR like so:

if(foo)
    foobar();
else if(bar)
    foobar();
else
    barfoo();

But Java has a perfectly good boolean exclusive or operator:

if(foo ^ bar)
    foobar();
else
    barfoo();

There is a xor operator in C, so I just see no reason why most college level programmers only use && and ||.

This is kinda like using the break on the default case of the switch statement. Code that is not wrong, but obviously redundant, or unnecessarily convoluted annoys me.

Tags: , , ,

Java ?: operator

Friday, April 21st, 2006

One of the least understood, and most underestimated Java language constructs is the ?: operator. Most people never even seen it in action. And those who did, never actually used it to do anything meaningful. Imagine something like this:

public generateFoo(int threshold)
{
    if(threshold > MIN_THRESHOLD)
       return new Foo();
    else
       return null;
}

In this snippet of code we have a function which generates a new Foo object if the passed argument is greater than some minimal threshold. If it is below threshold we return null. This is not an uncommon scenario… But with the ?: operator we could accomplish all of this on a single line.

public generateFoo(in threshold)
{
    return (threshold > MIN_THRESHOLD) ? new Foo() : null;
}

If you didn’t catch that let me show you something simpler:

int foo = bar ? a : b;

Java expects to a boolean or an expression evaluating to a boolean before the question mark. If that expression is true, then the whole statement evaluates to a. Else it evaluates to b.

It is elegant, produces a lean code and saves you one return statement. It is a good coding practice to have one return statement per method when possible. I think more Java programmers should embrace this little syntactic sugar. It saves you allot of typing when used appropriately.

Tags: , ,

The case of the switch

Wednesday, April 19th, 2006

Please look at the following code snippet and tell me what is wrong with it. No it contains no errors, just something really dumb that shows that the programmer does not understand the switch construct:

switch(foo)
{
     case 1:
     // do something
     break;
 
     case 2:
     // do something
     break;
 
     default:
     // do something
     break;
}

Do you see what I’m talking about? Come on, look at it!

If you couldn’t spot it, shame on you. Look at the default block. Why do we have a break there? The break statement is only there to prevent rolling down the the next case. If you are in the default case, which also happens to be the last case of the switch you are done. There is nothing below default it that can be executed. There is no need to put that break there!

And yet every book, online tutorial, and example I see put it there. Who the hell stated it? Why is everyone blindly copying this pattern? Is it for consistency?

Putting a break on a default statement is not wrong. It is syntactically correct. But that does not mean it does not look dumb as hell when you do it P

Tags: , , ,