I can haz ceiling friend?

Posted on 28th January 2011

See Ceiling Cat.

What I’m reading

Posted on 28th January 2011


PubSub fun fun

Posted on 27th January 2011

Here’s a concept: Your developing a piece of code that needs to let objects subscribe to the actions of another object but you need to keep it all nice and tidy and decoupled as possible.


To the left is a simple class diagram demonstrating a one possible design for such a problem. We have a Subscriber object which must be extended by objects who want to subscribe to a Publisher object. The Publisher object must be extended by objects who want to publish information to a series of subscribers. We use a feed object to monitor and control the interaction between the two. Although I’ve put association lines in the diagram between the Feed and the two other objects there is actually no concrete relationship and the two objects Subscriber and Publisher are completely decoupled.

Ler’s hop to it. Here’s our Publisher class.

Publisher.java:

public abstract class Publisher {
    public final void send(String message) {
        Feed.getInstance().send(message);
    }
}

Pretty simple stuff right. We have to declare it abstract because we want to control the declaration of the send() function. We also don’t want anybody to ever change how the send() function is declared so we declare it final.

Next we have the Subscriber class.

Subscriber.java:

public abstract class Subscriber {
    public final void subscribe(Subscriber s) {
        Feed.getInstance().subscribe(s);
    }
 
    public abstract void message(String msg);
}

Also very simple, we declare it abstract because we need to defer the implementation of the message() function and we want to control the implementation of the subscribe() function. We declare subscribe() final to stop future implementation from reimplementing how our subscribe() function.

The following is the code for the Feed class.

Feed.java:

public final class Feed {
    private static Feed self;
    private static java.util.ArrayList subs;
 
    private Feed() {
        subs = new java.util.ArrayList();
    }
 
    public static Feed getInstance() {
        if(self == null) {
            self = new Feed();
        }
 
        return self;
    }
 
    protected final void subscribe(Subscriber s) {
        subs.add(s);
    }
 
    protected final void send(String msg) {
        for(Subscriber s: subs) {
            s.message(msg);
        }
    }
}

This is an immutable class meaning it is as it is nobody can ever touch it this implementation. We declare it as a Singleton because we want it to behave as such by allowing our program to only ever have one instance of the Feed class. The class has three methods and a private constructor: getInstance() which is part of the Feed being a Singleton it provides a way to get an instance of the Feed by returning a reference to itself, subscribe() is called by Subscriber objects and puts the parameter Subscriber object into a list of subscribers, and finally the send() function which loops through all the Subscribers registered with the Feed object and calls their message() functions.


Please keep in mind this is a very very basic implementation. This implementation is literally only to send a String message to it’s subscribers. These classes could be designed to allow any type of object to be sent as in Event driven programming where the message in this example would instead be an event object of some type. We could also change the Feed to allow different type of Subscribers to subscribe to different types of Publishers all through the singleton feed. This concept is also very similar to the Observer design pattern which I might explain in a later post. I just wanted to post this for some interesting reading. Hope you enjoyed it!

Objects and Pointers: Pointer confusion

Posted on 27th January 2011

Here’s another little tutorial that most amateur developers need to take the time to read through. When it comes to objects and pointers in Java people seem to get confused without the explicit *’s and &’s that most C-based languages offer. New developers seem to often lose track of whats a pointer and whats a value when programming in Java and therefore end up with lot’s of unexplained behavior/bugs or exceptions in their code.

Below is a series of tests which demonstrates most (if not all) the scenarios where pointer confusion takes place. The following should at least solidify this basic concept for Java programmers to a degree of comfort that pointer confusion is no longer an issue. Enjoy:


Here is a class, Something, that is composed of another class, SomethingElse.

Something.java:

public class Something {
    private SomethingElse somethingelse;
 
    public SomethingElse getSomethingelse() {
        return somethingelse;
    }
 
    public void setSomethingelse(SomethingElse somethingelse) {
        this.somethingelse = somethingelse;
    }
 
    public void print() {
        somethingelse.print();
    }
}

Here is the SomethingElse class that Something is composed of:

SomethingElse.java:

class SomethingElse {
    public int n = 0;
 
    public void print() {
        System.out.println(n);
    }
}

Finally, here is the Main class which contains out main() method with all our tests. The tests purposes are identified in the comments:

Main.java:

public class Main {
    public static void main(String[] args) {
        SomethingElse a = new SomethingElse();
        SomethingElse b = new SomethingElse();
        SomethingElse c = new SomethingElse();
        a.n = 1;
        b.n = 2;
        c.n = 3;
 
        Something something = new Something();
        something.setSomethingelse(a);
 
        System.out.print("Value of something before any modifications to a: ");
        something.print();
 
        /*
         * Let's try assigning a new value to a in the Main class to see if it
         * affects the value held within the something object.
         */
        System.out.println("==Test 1==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a.n = 100;
 
        System.out.print("Value of a after modification: ");
        a.print();
 
        System.out.print("Value of something after first modification of a: ");
        something.print();
 
        /*
         * Let's try assigning the pointer in b to the pointer in a then changing b and printing out a.
         */
        System.out.println("==Test 2==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        b = a;
        b.n = 25;
 
        System.out.print("Value of a after modification of b: ");
        a.print();
 
        System.out.print("Value of something after first modification of b: ");
        something.print();
 
        /*
         * Let's try assigning the pointer in a to the pointer in c.
         */
        System.out.println("==Test 3==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a = c;
 
        System.out.print("Value of a after modification: ");
        a.print();
 
        System.out.print("Value of something after second modification of a: ");
        something.print();
 
        /*
         * Let's try setting the pointer in a to null.
         */
        System.out.println("==Test 4==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a = null;
 
        System.out.println("Attempting to print a after nullifying it's pointer will throw a NullPointerException so let's move on.");
 
        System.out.print("Value of something after third modification of a: ");
        something.print();
    }
}

Output:

Value of something before any modifications to a: 1
==Test 1==
Value of a before modification: 1
Value of a after modification: 100
Value of something after first modification of a: 100
==Test 2==
Value of a before modification: 100
Value of a after modification of b: 25
Value of something after first modification of b: 25
==Test 3==
Value of a before modification: 25
Value of a after modification: 3
Value of something after second modification of a: 25
==Test 4==
Value of a before modification: 3
Attempting to print a after nullifying it's pointer will throw a NullPointerException so let's move on.
Value of something after third modification of a: 25

So to explain what’s happening here.

In the first test we’re testing to see whether changing the value of a in the Main class will affect the value within something’s somethingelse class because it holds a pointer to the same memory space that a does. The test does change the value of a both within the Main class and the value of n within something’s somethingelse class.

In the second test were attempting to show how you can assign object pointers and alter the same memory space through different object pointers. We’re doing this by assigning b the same pointer held by a and then changing b and printing out the value of a which prints out the new value that we just assigned b. This happens because when we assign b the pointer held by a we have assigned both a and b to point to the same memory space. When we alter b we are altering the data in that memory space and when we go to look at it through a we are still looking at the same memory space we just altered with b. Get it? Got it? Good.

The third test is to show the opposite of test two where something’s somethingelse class holds a reference to the memory space held by Mains a object pointer but then we assign a the same pointer held by c thereby losing our pointer from a to the same memory location as something’s somethingelse class. This test is to show that assignment of objects with the ‘=’ operator only works on pointers so after we do this something’s somethingelse class doesn’t take on the value of c we just effectively eliminate our pointer through a to the same memory space held by something’s somethingelse class.

The last test is just to reinforce the same concept the previous three were trying to demonstrate. We eliminate the pointer held in a so if we try to access it the code would throw a NullPointerException in the Main class but something’s somethingelse class still holds the reference to the original memory space and the value printed remains the same.

I hope this demonstrates enough examples of object pointers to clear up some of the confusion. There are a number of other things I could have shown in this code but they would have been just as redundant as the fourth test in the code already provided.

Keep coding!

tags: ,

Pass by what?

Posted on 27th January 2011

Here is a problem I hear over and over again from developer entering the Java realm. Many new developers have either never been introduced to the concept of pass-by-value/pass-by-reference or they just never understood what it meant. So I threw together some simple source code to demonstrate this basic concept that every developer of ANY language should know.


Here’s a simple object class that has only a string.

Something.java:

public class Something {
    String name;
}

Here are two objects, one to change the name attribute in the Something class, and one to change a primitive type, by simply changing an int to 1.

ObjectChanger.java:

public class ObjectChanger {
    public void changeSomething(Something s) {
        s.name = "changed";
    }
}

PrimitiveChanger.java:

public class PrimitiveChanger {
    public void change(int n) {
        n = 1;
    }
}

Now let’s look at the Main class which contains this projects main() function.

Main.java:

public class Main {
    public static void main(String[] args) {
        // Let's try changing an object type
        Something s = new Something();
        s.name = "unchanged";
 
        System.out.println("String before pass: " + s.name);
 
        ObjectChanger oc = new ObjectChanger();
        oc.changeSomething(s);
 
        System.out.println("String after pass: " + s.name);
 
        if(s.name.equals("unchanged")) {
            System.out.println("Objects are passed-by-value.");
        } else
            System.out.println("Objects are passed-by-reference.");
 
        // Now let's try changing a primitive type
        int n = 0;
 
        System.out.println(n);
 
        PrimitiveChanger pc = new PrimitiveChanger();
        pc.change(n);
 
        System.out.println(n);
 
        if(n == 0) {
            System.out.println("Primitives are passed-by-value.");
        } else
            System.out.println("Objects are passed-by-reference.");
    }
}

And finally the output:

String before pass: unchanged
String after pass: changed
Objects are passed-by-reference.
0
0
Primitives are passed-by-value.

As you can gather by reading through the code and output when an object is passed into a function it gets passed-by-reference meaning if that function changed that object within it’s logic then the original object will reflect those changes. A primitive type on the other hand is passed-by-value which means it basically gets a copy of the value to take away and do as it will with it. The called function can manipulate the passed in primitive value as much as it wants and the original value outside of the called function will remain the same as it was before it was passed to the function.

I hope this helps to clarify some of the misunderstanding surrounding this topic. This example does not take into account the overloading of the clone() function in your objects and then passing a reference to an objects clone rather than the original objects itself by using the obj.clone() syntax. Getting into the clone() function however deserves a whole other post.

Some things to look forward to

Posted on 9th January 2011

A long long time ago in a sub domain not so far away a couple friends and I ran a blog called WAFN. On this blog we explored a very big range of topics. The mistake we made however was trying to provide news even though we were not really plugged into that universe. After a recent conversation with a couple of other friends about starting a podcast we took a look at our old blog. After trying every credential set I could remember I was able to log into the admin page and we found that we still get an enormous amount of hits on that website. So there is talk about reviving WAFN perhaps under a different name but getting a similar group of people together to revive it.

The second project in talk is about the podcast our friends want to start which we might be involved with. As more news comes I’ll make sure to share but as it stands for now it is still in the planning stages. So stay tuned!