Posterous
Brandon is using Posterous to post everything online. Shouldn't you?
Brandon_july_2009_-_hires_headshot_thumb
 

mechanicalSPIRIT

Brandon Franklin's blog

Online Public Life vs. Online Private Life

Generally speaking, I try to be as open and public about as much of my life as possible. I don't suffer from what I consider to be the "privacy paranoia" of many of my peers, and I'm not especially concerned about identity theft. I keep important pieces of information (such as my bank account information) private, of course, and I make sure to use HTTPS when doing online transactions that involve that kind of information. But that's not privacy; that's security. The two are related, but different.

I try to be open and public about information online as often as I comfortably can because I think it offers a great number of benefits. It fosters discussion, lets my online friends get to know me better, and generally contributes to the Big Conversation that defines living in a connected society.

However, recently I've found myself doing a fair bit of self-censorship with regard to topics such as religion (I'm an atheist) and politics (I lean heavily to the Left). I don't keep these specific pieces of information secret, but I find that I often hesitate to discuss them, and offer arguments related to my points of view, even though I feel very strongly about them and spend a lot of brain cycles on them.

My reasons for this are varied. To some extent, I'm attempting to avoid alienating people who, in other contexts, contribute positively to my life. I also am protecting myself professionally, since we all know that employers these days may look at our online conversations at any time with some simple searching. Again, I make no secret of my basic positions on these topics, but the process of offering detailed arguments or rants with regard to them feels different. It feels risky. And not in an exciting and fun way, but rather in a "Wow I Hope My Boss Doesn't Read That" way.

This frustrates me. I hate that I feel the need to remain silent on speaking about issues that am passionate about, and have a lot to say about. But isn't personal restraint and "picking one's battles" also valuable?

There are other things I choose to keep private, as well, such as very personal situations related to my family situation. It makes me feel like a bit of a fake or hypocrite to say I'm open and public about myself, but then to keep these particular things totally "off the radar."  They play a huge part in my life, and yet I feel that exposing them might be more trouble than it's worth. But isn't this kind of silence about uncomfortable issues exactly what we helps things like child and spousal abuse flourish, like fungi that grow best in the dark?

What do you think of this? Do you also find it challenging to balance your public and private selves online? Please comment below and let me know.

Loading mentions Retweet
Filed under  //   digital culture   online life   openness   privacy   secrets   security  
Posted February 3, 2010
// 1 Comment

Java Programming Tip: Building Your Own Event Bus

Most of us have worked with various types of event handling in Java. There's of course the basic Observer/Observable pair, but beyond that there are all sorts of MouseEvents, ComponentEvents, PropertyChangeEvents, and many others. These are great, and are a well-established pattern for keeping code loosely coupled. However, they all share the similar attribute of requiring that a listener be attached directly to the source of the events. This has two major downsides.

First of all, it forces the code to remove listeners in order to prevent many types of memory leaks, which is particularly annoying in cases where it's not trivial to institute a "cleanup" pass, essentially mirroring the behavior that would, in C++, be recognized as a "destructor". This sort of cleanup code tends to pollute the code in general, and is difficult to maintain over time. It seems somebody always forgets to null out that one critical field...

Secondly, and perhaps more importantly, this approach can make for some very ugly designs when building a large, interconnected application such as a complex GUI system. In such systems, components more often care about what kind of event is being fired somewhere--anywhere!--than they do about who is firing it. The components don't really want to attach as listeners to a source. They want to attach as listeners to an event type.

This is when it's time to think about using an event bus!

The exact design of your particular event bus can vary depending on your needs. I've written a few over the years and they've been quite different beasts. However, there's one that I have written that I generally use as a template when starting a new event bus. I call it the SmartEventBus. It consists of just 2 classes! Here's the code, with most comments and some minor sections removed for brevity: (NOTE: Uses Java 5 language syntax)

public abstract class SmartEvent<S> {

    private S source;

    private long timestamp;

    public SmartEvent(final S source) {
        this.source = source;

        timestamp = System.nanoTime();
    }

    public S getSource() {
        return source;
    }

    public long getTimestamp() {
        return timestamp;
    }

}


import java.lang.ref.*;
import java.lang.reflect.*;
import java.util.*;

public class SmartEventBus {

    private static SmartEventBus INSTANCE = null;

    private Map<Class, Set<WeakReference<Object>>> listeners = new HashMap<Class, Set<WeakReference<Object>>>();

    static public SmartEventBus getBus() {
        if( INSTANCE == null ) {
            INSTANCE = new SmartEventBus();
        }
        return INSTANCE;
    }

    private SmartEventBus() {
    }

    private Iterator<Class> superclassIterator(final Class clazz) {

        Set<Class> set = new LinkedHashSet<Class>();

        Class<?> superClass = clazz;
        while (superClass != null) {
            set.add(superClass);
            superClass = superClass.getSuperclass();
        }

        return set.iterator();
    }

    public synchronized void addListener(final Object listener) {

        // Pull out all the "hear" methods
        Set<Method> hearMethods = new HashSet<Method>();
        for (Method method : listener.getClass().getMethods()) {
            if (method.getName().equals("hear")) {
                hearMethods.add(method);
            }
        }

        // Examine every "hear" method
        for (Method method : hearMethods) {

            Class[] paramTypes = method.getParameterTypes();

            // Disqualify malformed candidates
            if ((paramTypes.length == 1)
                    && (SmartEvent.class.isAssignableFrom(paramTypes[0]))) {
                addTypeSpecificListener(listener, paramTypes[0]);
            }
        }

    }

    private void addTypeSpecificListener(final Object listener, final Class type) {

        // Get or create the Set of listeners for this type
        Set<WeakReference<Object>> typeListeners = listeners.get(type);
        if (typeListeners == null) {
            typeListeners = new HashSet<WeakReference<Object>>();
            listeners.put(type, typeListeners);
        }

        // Add the listener
        typeListeners.add(new WeakReference<Object>(listener));

    }

    public void fire(final SmartEvent event) {

        for (Iterator<Class> iter = superclassIterator(event.getClass()); iter.hasNext();) {

            Class type = iter.next();
            if (type.equals(Object.class)) {
                continue;
            }

            Set<WeakReference<Object>> typeListeners = listeners.get(type);
            if (typeListeners != null) {

                Collection<WeakReference<Object>> deadRefs = new LinkedList<WeakReference<Object>>();
                for (WeakReference<Object> listenerRef : typeListeners) {
                    Object listener = listenerRef.get();
                    if (listener != null) {

                        Method method = null;
                        try {
                            method = listener.getClass().getMethod("hear", type);

                        }
                        catch (NoSuchMethodException nsme) {
                            // This should theoretically never be true,
                            // but try to handle it gracefully anyway.
                            deadRefs.add(listenerRef);
                            continue;
                        }

                        Object result = null;
                        try {
                            result = method.invoke(listener, event);
                        }
                        catch (IllegalAccessException iae) {
                            iae.printStackTrace();
                        }
                        catch (InvocationTargetException ite) {
                            ite.printStackTrace();
                        }

                    }
                    else {
                        deadRefs.add(listenerRef);
                    }
                }
                typeListeners.removeAll(deadRefs);
            }
        }

    }

}

The SmartEvent class is, obviously, the base class that is used to represent events that get passed around the system. In your own event bus, it could contain just about anything you want, but mine contains simply a source object (parameterized) and a timestamp. This class gets extended into your entire event hierarchy.

The SmartEventBus is a singleton, because you use it like a service, getting a handle to it any time you need to use it. When an object adds itself as a listener, it is examined to find any and all methods beginning with the word "hear". The methods that have exactly one parameter will have the datatype of that parameter recorded in the bus as the type of event that the method cares about. In other words, when a class adds itself as a listener, it adds itself as a listener to everything it listens to. There's no interface to implement, and if the code changes such that the listener shouldn't care about a particular event type anymore, the developer need only delete the associated "hear" method. I'll leave more detailed analysis of the above source code up to the reader.

Since writing this original event bus, I've seen and written some other variations. One notable example is in the open source Buoy GUI framework. It uses a reflective system similar to my SmartEventBus. A more recent example is one that I wrote that uses the newly-added annotations framework in Java 5 syntax to mark the methods, rather than a naming convention. This means your listener methods look more like this:

@EventListener
public void handleSomeEvent(EventType e) {
...
}

While this is appealing in the sense that it frees one from onerous naming conventions and relies upon a more powerful reflective analysis, I find that it can sometimes be a bit frustrating in daily practice to not have a single, easily sorted "name group" of methods. For example, having all of your methods begin with "hear" causes them to be grouped in the outline view of Eclipse. It's a minor annoyance, but worth noting anyway.

In the end, there are as many ways to develop event buses as there are applications that need them, but by understanding some existing approaches and thinking about reflection rather than interface implementation, new doors can be opened to you that you may not have even realized existed.

Loading mentions Retweet
Filed under  //   events   Java   programming   tip  
Posted January 9, 2010
// 3 Comments

Short Story: Moonset

This story is a work of fiction and is Copyright 2010 Brandon Franklin. You may not copy or reprint it without my permission. However, I encourage you to share it and link to it if you like it.

I drove through the streets as quickly as reasonably possible, though my progress was severely impeded by the presence of nearly every imaginable obstacle.  There were cars everywhere, either crashed or abandoned.  As if that didn't make things difficult enough, there were various other items out there, too, like tipped over garbage cans, smashed televisions, large furniture items, and a seemingly endless ocean of tiny unidentifiables.  It was as though the lives of the thousands of people living here had simply been emptied into the streets.  I suppose in a way that's exactly what had happened once the rioting got into full swing, but I think a lot of it had been cast aside by its owners in a despairing expression of hopelessness, manifested as reckless abandon, brought on by the circumstances at hand.

My thoughts were interrupted as a figure suddenly appeared in my headlights and I slammed on the brakes.  It was a girl, probably in her mid-twenties, and she ran directly toward my car, smacking her hands down on the hood as she threw herself forward.  In an instant she ran up to the driver-side window and began frantically swatting at the glass, yelling incomprehensibly through tears.  I was stunned by her sudden appearance, and hesitated for a moment, not out of callousness, but rather out of sheer surprise, and by the time I had processed the scene, she was glancing back in the direction from which she had come.  My gaze instinctively followed hers, and I saw a group of three boys, similar in age to her, appear like a pack of hungry wolves, clearly in pursuit.

They paused for a moment in my headlights, until I suppose their eyes adjusted and they spotted the horrified girl, who immediately bolted from my window towards the back of the car and away.  The boys sprinted past, one of them passing by the passenger side, and then I saw them regroup in my rearview mirror.  They quickly overtook the girl and knocked her to the ground.  It was obvious to me that they intended to rape her.

I opened my door and quickly stood up, turning to face the scene.  The four were too far away for me to reach immediately, so I shouted something, I don't remember what, in an attempt to interrupt them.  One of them looked up at me, assessed me, I suppose, as not a threat, and hurled a large glass bottle that he must have been carrying, which smashed against the back window of my car as he yelled "Fuck off!"

I had defensively covered my face with my arms as the glass shattered, and as I lowered them and looked up, a new figure rushed by me.  It was another young man, sprinting toward the others.  I suppose he had come from the same direction as the previous four people, but I quickly realized that he was not one of their cohorts, as he raised a long metal object of some kind, with a very visible square mounting surface at the end--maybe it was a table leg?--and screamed "Get the fuck away from her you piece of shit!"  In perfect synchronization with that final syllable, he swung his makeshift weapon down into the upper back of one of the girl's assailants, producing a clearly audible thud, and driving the recipient into the ground.

What followed was a very confused and bloody melee, in which I sought no involvement.  I got back into my car and closed the door, looking straight ahead for a second.  I imagined that similar scenes, and maybe even worse, were taking place all over the city, all over the country, all over the world.  The last sounds we, as a species, would make in the Universe were guttural screams of pain, hatred, and fear.

The car was still running, so I pressed the accelerator gently and resumed my progress.  After I weaved through the wreckage of a trio of collided vehicles, and then slowly proceeded across what seemed to be several crushed cardboard boxes, the road opened up for a stretch and I was soon able to achieve a more reasonable cruising speed.

I felt my body finally relax a bit, and I leaned back in my seat, allowing myself a deep breath and a glance upward into the sky, where the Moon, the cause of all this misfortune, hovered massively, ominously, bearing down upon us with every passing moment.  She was surrounded by a glowing halo of particles and fragments of varying sizes, like drowned Ophelia surrounded by petals; the remnants from the cataclysmic impact that had, mere days earlier, drastically altered our beloved satellite's trajectory, and sent her plummeting toward us, toward inescapable obliteration for us both.

I thought back to the memorable moments leading up to the impact.  There had been the initial announcement that the extremely massive Potentially Hazardous Object designated 877 Kira was headed for a near-miss of the Earth.  Then, later, the projections were revised to confirm that there would not be a near-miss, but rather a certain impact upon Luna, and that the event would be globally catastrophic for us, as it would cause her to fall out of orbit almost immediately.  People were tense, but for the most part life had carried on normally despite the news, perhaps due to a collective need for denial.

Everything changed on the night of the Object's impact, though.  People from every nation on the Western Hemisphere, myself included, watched in awestruck horror as a glowing form darted across the sky, followed soon after by that ghostly cloud of debris, spilling outward like pebbles scattering from a bucket kicked over by a careless child.

That was the moment when mankind's hope died, taking with it all sense of civility and restraint.

After about an hour, I had reached the outskirts of town and begun heading up into the hillside.  The road began to twist and incline, and the burning homes and vehicles were gradually replaced by trees and blessed, empty darkness.  No place on Earth could be called "safe," but my destination could, at least, be called "familiar," and I was determined to finish what I had started on my own terms, before being destroyed on Nature's.

The remainder of the drive was quiet and uneventful. The illumination afforded by the increased intensity of the moonlight lent the landscape a surreal clarity, as though previously invisible details were crying out to be noticed by my passing eyes before they were wiped from existence altogether.  I slowed down as the crunching under the tires alerted me that the road had become gravel, and as I rounded the final bend, my headlights glinted off of the windows of my cabin.

The woods were absolutely silent.  I found this strange at first, as I had expected that the bright moonlight would have the wildlife in an uproar. However, upon a moment's reflection, I determined that the exact opposite must be true, and the unprecedented luminosity had convinced the denizens of the forest that it was, in fact, still daytime.  Hence, not a cricket was heard.  Not an owl.  But there was something...

I climbed the three steps leading up to the wooden deck that surrounded the cabin, and followed it around to the back.  From here, the hillside fell away and one could see the city, from which I had just made egress, below.  Ordinarily, this would have provided a relatively tranquil view, with the grid of streetlights twinkling as the residual heat radiated into the night sky, but things were different now.  The city had been without power since shortly after the riots began, so rather than twinkling streetlights, the flickering flames from hundreds of burning buildings dominated the scene.  Plumes of smoke rose from every corner, framed by the light of our Destroyer above.  The unnatural silence of the forest allowed me to hear the sounds rising from that hellish cityscape, which had blended together into a sort of mid-pitched roar, like the cheering of a crowd at a distant ballgame, mixed with the chaotic popping of small firearms being discharged.  This sound was further punctuated with periodic explosions, which were sometimes preceded by bright flashes of light that I could see at various points around the city.

I found it ironic how humanity's reaction to despair was noise, while the other animals reacted, instead, with silence.

I turned away from the dismal apocalyptic scene and entered the cabin through the back door.

The bright moonlight streaming through the windows made it easy enough to see without artificial aid.  I retrieved my stored bottle of Jack Daniel's from the cupboard, along with the glass kept inverted atop it, and sat down at the circular wooden table in the middle of the room.

My drink accompanied my thoughts, poisonous and distracting as they both were.  What would the moment of the end be like?  Would the impact be oceanic, resulting in some impossibly massive tsunami?  Or would we be blotted out in a direct crushing blow, our sky filled with flames and stone before a single piece of the Moon even touched the ground?  I was sure that many scientists and astronomers knew the answer, but mass media had failed too soon after the riots began for any such information to be made available, at least to me, and surely the overwhelming majority of other people, who probably didn't really care anyway.

It was irrelevant in the end, wasn't it?  The result would be the same.

My glass empty, I slid my chair back and stood up.  I would finish what I had started.

The other door of the cabin was directly opposite the one through which I had entered.  On the wall beside it hung a chainsaw, which I retrieved and placed on the floor.   A large jug of gasoline sat nearby, and after I ensured that the chainsaw was properly fueled, I emptied the remainder of the jug's contents to form a shallow pool throughout the center of the cabin.  Then I took the cigarette lighter, brought along for precisely this purpose, out of my pocket and set the pool ablaze, tossing the lighter in after.  Hefting the saw into my hands, I pulled the door open and stepped into the night, letting the door slam upon the flames in the room behind me.

Again I could hear the screams and cacophony from the distant city.  A couple of pulls on the saw's cord soon drowned them out with a much louder rumble.  I allowed the saw to idle as I walked over to the covered woodcutting area a few yards to my left, where three young women were tied to the supporting columns.  One of them appeared to be either unconscious or dead.  The other two cowered and attempted fruitlessly to move away.

I spoke loudly to be heard over the growling saw. 

"I'm sorry.  I really hadn't planned on doing this yet, but as you can see, we've run short on time."

I pulled the throttle trigger of the saw and was pleased that it was effective at covering nearby screams as well as it did distant ones.

Loading mentions Retweet
Filed under  //   apocalypse   creative writing   lunar impact   short story  
Posted January 5, 2010
// 0 Comments

Short Story: Filth and Wine

This story is a work of fiction and is Copyright 2010 Brandon Franklin. You may not copy or reprint it without my permission. However, I encourage you to share it and link to it if you like it.

"So what do you think about how everybody's on the Little Purple Pill nowadays?" she slurred from across the table, limply waving her cigarette around before taking another drag.

"I don't know.  I guess I hadn't really thought much about it," I replied, completely disinterested in this latest in a long stream of inane utterances from my dinner companion.

"I just can't help but ask myself if anybody's even thinking for themselves anymore, you know?  Or are they just letting their psychiatrists make all the decisions for them."  I was barely paying attention to her at this point, but I feigned interest by producing a muted grunt of implied agreement.  At this moment, our waiter appeared and placed our plates on the table in front of us.  My companion had ordered a large steak.

"It's obvious to me that most people are just not taking stock," she said condescendingly as she put her cigarette in the ashtray, then unfolded her napkin into her lap and picked up her utensils.  I sighed to myself and picked up my glass, wondering how many drinks it would take before I was no longer irritated by this woman.

I watched as she cut a piece of meat and shoved it into her maw.  A cow eating a cow.  Disgusting.

I looked at my plate. My food was attractively presented.  By this time I should have been starving, but the presence of this cretin had caused me to lose my appetite.  I wondered if I should force it down?  I supposed there was no getting around it...

Suddenly, everything went blindingly white.  I squinted against the sudden brightness, then watched the smiling face of a young man appear as my eyes adjusted.

"Alright sir, your time is up.  Please exit the simulation capsule."

"Already?" I said, pleadingly.  "It feels like it's only been a few minutes."

"No sir, it has been a full two hours, as agreed," he cheerfully replied. "I'm glad you've had an enjoyable experience, but if you'll please exit the capsule..."

"Can I book some additional time today?"

"I'm sure that'll be no problem, sir.  Just talk to one of the representatives at the front desk where you came in."

"Okay, great!"  I stood up, stepped out of the padded capsule, and eagerly made my way back to the booking desk, mentally calculating my finances along the way.  If I postponed grocery shopping for a couple more days, and skipped the skiing trip in November, I reckoned that I had enough credit available to buy another hour and a half of simulation time!

Loading mentions Retweet
Filed under  //   beef   creative writing   dystopia   short story  
Posted January 2, 2010
// 1 Comment

Free Song Download: "Inverse Science"

  
(download)

Ever heard of a "chiptune"? Well kids, Back In The Day, musical computing hardware was very constrained memory-wise so any music compositions you did had to be kept quite small.  Most of the sounds were generated in real-time by very simple audio processors. Also, since you usually only had maybe 3 audio channels to work with, you had to use arpeggio to produce things that sounded like chords. Even after hardware advanced, many trackers (that's what digital musicians were called back then...and I was one of them) loved the challenge of writing a song that used tiny samples that you could fit into a few kilobytes of memory. 

So, years ago, I wrote one called "Inverse Science". It was only 16k in size in its MOD file form (originally a ScreamTracker 3 file, for those who care), though of course as a modern audio file it's much bigger. Musically, I am actually pretty pleased with it, but I was always a sucker for that old 8-bit music anyway. At any rate, it'll instantly bring back memories of the old 8-bit gaming platforms, etc. which were often bound by these constraints.

I hope you enjoy it.

If you would like the original 16k MOD file (which you can play with VLC), let me know.

Loading mentions Retweet
Filed under  //   chiptune   music   screamtracker   tracking  
Posted December 28, 2009
// 0 Comments

Java Programming Tip: Using Reflection to Call Any Method (Even a Private One!)

Many of us have encountered the following situation: You are coding a tricky algorithm and discover that a very useful method for doing what you're doing already exists. Alas, it's private, or perhaps "package" visible (in a package that you're not in!) and you have no way of accessing it. You end up duplicating the code yourself, perhaps grumbling under your breath about how the other developer should have made the useful method public. I have some good news for you. By using Java's built-in reflection API, you can actually call any method you want under most circumstances!

How? It's easy. It all comes down to the setAccessible(boolean) method of the AccessibleObject class, of which Method is a subclass. Let's take a look at some example code. First, a class that contains our "target method", the one we want to call but can't access:

public class Foo {

   private boolean same(int x, int y) {
       return ( x == y );
   }

}

Here's a class that uses reflection and "setAccessible" to call the method (NOTE: uses Java 5 language features):

public class Bar implements Runnable {

    static public void main(String... args) {
         new Bar().run();
    }

    public void run() {
        try {
            Foo foo = new Foo();
            Method targetMethod = foo.getClass().getDeclaredMethod( "same", int.class, int.class );

            // This is the magic line
            targetMethod.setAccessible(true);

            Boolean result = (Boolean)targetMethod.invoke( foo, 4, 4 );
            System.out.println( result );
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Pretty easy, isn't it? You can also call static methods using this approach. Let's imagine that the method in our Foo class had been static. In that case, here's what we would have done instead:

public class Bar implements Runnable {

    static public void main(String... args) {
        new Bar().run();
    }

    public void run() {
        try {
            Method targetMethod = Foo.class.getDeclaredMethod( "same", int.class, int.class );

            // This is the magic line
            targetMethod.setAccessible(true);

            Boolean result = (Boolean)targetMethod.invoke( Foo.class, 4, 4 );
            System.out.println( result );
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Notice that the difference is simply that we cannot use an instance of Foo to get the class object, and that during the invocation of the method we use the class itself as the first parameter, rather than an instance.

This technique isn't foolproof. Every time you call "setAccessible", the installed security manager (if there is one) is given an opportunity to block the call. However, I've not yet encountered a situation in which this was actually blocked. That said, just because you can do something doesn't mean you should, so be sure to use this approach with caution, and certainly only when you absolutely must! After all, it is fundamentally "breaking the rules" that are being expressed in the code itself.

Loading mentions Retweet
Filed under  //   Java   programming   reflection   tip  
Posted December 27, 2009
// 0 Comments

Java Programming Tip: Why Not to Obfuscate

Obfuscation is a seductive mistress! At several places where I've worked, the management's perception was that obfuscation was absolutely necessary to protect the company's intellectual property. After all, with so many clever algorithms and so much custom code in there, it must be very important to ensure that all those sneaky hackers out there don't figure out our secrets! Right?

Well...Maybe. But not really.

Okay, perhaps I'm not being fair. Yes, without obfuscation involved, it truly is extremely easy to decompile Java bytecode into completely readable sourcecode. Yes, it really would be a trivial issue to essentially build the entire source tree of a product up from just a single copy of the runtime code. And yes, programs that will do this for you are incredibly easy to find on the Internet with a quick Google search. I'll give them that much. I concede those points.

Where we differ, however, is on that "very important" part. Is it "very important" to do this? Is it even worth it at all? I assert that it is not, and I'm happy to back that up with some explanations.

First of all, obfuscating your code may give you a sense of security, but it is an illusion. Any interested party who truly has something to gain from understanding your algorithms (such as a corporate competitor) is not going to be thwarted by methods being renamed to "a3()". If they care that much, they will spend the time (and money) to carefully pore through your obfuscated code, looking at "what it's doing" rather than "what it says", and they'll eventually figure it out. Don't believe me? Hackers have been doing this with compiled assembly language for years. How do you think they write all those crazy "cracker" programs that route the code around checking that there's a CD in the drive, etc.? And those are just some kids with a little free time! When you bring a team of experienced coders and a corporate payroll into the picture, your obfuscated Java source doesn't stand a chance.

So that argument deserves to leave skidmarks on the bowl. The only "hackers" you're going to deter with obfuscation are hobbyists who don't pose any actual threat to you anyway.

Beyond the basic ineffectiveness of obfuscation, it actually makes some things worse. I can tell you from experience, nothing is quite as frustrating as running a production build of your product and getting a stack trace that looks like this:

Exception in thread "main" java.lang.NullPointerException
    at a.q.a.b.m3(unknown:unknown)
    at a.x.e.a.a1(unknown:unknown)
    at t.a.h.b.b2(unknown:unknown)
    at t.b.a.a.c2(unknown:unknown)
    at b.c.a.a.a2(unknown:unknown)

Yeah. Great.

Better yet, wait until you get a stack trace like that emailed to you from a customer who just got that in a logfile. Or even better, wait until your Support Department guy calls you up asking what it means! That's the reality of it, folks. That's the bit that they don't mention on the back of the Obfuscation Software 2010 box. Oh, I know, some of the obfuscators generate little "lookup tables" so you can try to make sense of that gibberish, but let's get real: The end result is, it wastes a huge amount of developer time that would be better spent actually fixing the bug that a real stack trace would have made obvious.

As if this wasn't already bad enough, it gets worse! By employing obfuscation, you completely destroy your ability to use reflection in your product. Reflection encodes everything as hardcoded strings, like "com.company.MyClassName". That stuff doesn't get converted by the obfuscator, at least not by any obfuscator that I've ever seen. So what you get is code that looks fine, compiles fine, even runs fine during your tests, but as soon as it goes to production and gets run through the obfuscator, BOOM! It's broken. You've essentially destroyed your ability to use a very powerful feature of the Java language. I ask you again, was it worth it?

Finally, the very act of employing an obfuscator introduces more complexity to your build process. It's yet another step, another thing you need to automate in your build script, or have some poor human being execute by hand. It's yet another piece of software to manage. It's yet another moving part! If you're like most software shops I've worked at, the last thing you need is more moving parts!

So please stop the madness. When your boss says "We need to start obfuscating!" or when you start a new job and see that they're employing obfuscation already, pipe up. Explain these issues. Ask them to think about the pros and cons. Maybe, just maybe, you won't be seduced by this femme fatale like so many others have been.

Loading mentions Retweet
Filed under  //   Java   obfuscation   programming   tip  
Posted December 21, 2009
// 0 Comments

Java Programming Tip: Keyed Singletons

Most Java programmers are familiar with the "singleton" pattern, shown in this snippet:

public class MyService {

    static private MyService INSTANCE = null;

    static public MyService getInstance() {
        if( INSTANCE == null ) {
            INSTANCE = new MyService();
        }

        return INSTANCE;
    }

    private MyService() {
    }

}

However, I've found that sometimes in a complex application, it can be useful to have instances of particular classes that act like singletons, but only in terms of a specific context. For example, perhaps you are working on an application that allows you to edit "projects" of some sort, and within the scope of each project you only want exactly one instance of a particular service, such as an "Undo Manager" or a "History Manager". You want it to work like a utility class, but it needs to maintain state that is specific to the context in which it's being used.

My solution to this problem has been to use what I call a "keyed singleton" pattern. It's easy to implement, as shown here (NOTE: uses Java 5 language syntax):

public class MyService {

    static private final Map<Object,MyService> INSTANCES = new HashMap<Object,MyService>();

    static public MyService getInstance(Object key) {
        MyService service = null;

        if( INSTANCES.get(key) == null ) {
            service = new MyService();
            INSTANCES.put(key, service);
        }

        return service;
    }

    private MyService() {
    }

}

In the above example, instances are lazily initialized just like you'd expect from a singleton implementation, but then they're added to a Map which tracks every instance based on the key it was created with. One will quickly notice that there's a problem with using this approach in some cases, though, which is that there's no obvious removal semantic. In other words, you'll quickly end up with a lot of instances in your Map and no way to get rid of them. Also, if you are using large objects (such as some kind of Project class) as your keys, then you could be creating a rather severe memory leak. You could add a removal method, but I have a better way!

Just substitute in this line:

    static private final Map<Object,MyService> INSTANCES = new WeakHashMap<Object,MyService>();

Instantly you have now made all of the references to your keys into "weak references," meaning the Map itself cannot prevent garbage collection of the key instances. Better yet, when one of the keys is garbage collected, its associated value entry is removed from the Map as well. In this way, careful use of a keyed singleton pattern can provide a scoped, self-cleaning service management framework.

Loading mentions Retweet
Filed under  //   Java   programming   tip  
Posted December 18, 2009
// 0 Comments

Always Check for Open Source First!

This is a lesson I've learned the hard way. Typically, when we engineers approach a problem, we are excited about the prospect of solving it. That is, we almost immediately begin imagining how the code might work, or what sort of algorithm we might use. This is a hard habit to break, but if we don't force ourselves to gain a bit of discipline, we will often end up wasting a lot of time solving problems that have already been solved (sometimes many times over!) by other people. It is a very disappointing feeling to spend days or weeks implementing a partial solution to a complex problem, only to discover too late that somebody already wrote a solution years ago that does far more than yours ever will. I've often had to ask myself "Why did I bother with this?"

The simple fact of the matter is that before you start laying down code, or even writing up a design, you should take 15 to 30 minutes and search the Internet for open source implementations of the functionality you need. You should try to get in the habit of doing this consistently, so that it becomes a normal part of your thought process. Some sites that you should always include in your search:

SourceForge
Google Code Search
Java.net (if it's a Java project)
freshmeat

In addition to those sites, you should do some basic Google searches for the functionality you need. You will probably end up being surprised at just how much useful stuff you find. Many projects, had they taken this approach from Day One, could probably have built themselves almost entirely out of existing open source components, shaving development time to a tiny sliver of what it had been, and therefore saving money and making time available for the addition of truly new features.

Loading mentions Retweet
Filed under  //   developers   FOSS   Java   open source  
Posted December 15, 2009
// 1 Comment

Crazy Idea: Convert an Old Motel into an Office Park

I just saw a story about how an abandoned motel caught fire here in Mesa.  It made me start thinking about what pathetic eyesores those become.  They almost always end up burning down, probably most often due to arson.  There was a small motel almost just like this one back in my hometown that also burned after sitting vacant for ages.  Even after burning, they typically just sit there because nobody bothers to spend the money to properly demolish them.

It seems like an enterprising investor could purchase one of these small motels and do very minor renovations needed to convert them into startup-friendly "office parks" of a sort.  Many startups are just a few people, and could benefit from things like:

  • Dedicated, small, private space, complete with pre-wired phone and internet access
  • A private full-featured bathroom
  • A private kitchenette
  • Easy, right-by-the-door parking
  • Common "office area" similar to in an incubator, where there could be a shared copier, fax machine, vending, etc.
I have no idea how much money it would take to do such a thing, or if it's even economically feasible.  It just seems like it would be a good way to re-use existing building space and would be a hell of a lot better than leaving a boarded-up fire hazard sitting around for years.

Just an idea.

 

Loading mentions Retweet
Filed under  //   economy   idea   motels   startups  
Posted November 30, 2009
// 2 Comments