Four features from Java which are really cool.

There are, in my opinion, four basic language features in Java which make the language extremely cool–in that they allow IDE developers and software developers to quickly and easily deploy tools which make working with Java very easy.

I wanted to point out these features in the hope that future languages (or future extensions to other existing languages such as C++ or Objective C) could incorporate these features, in order to make those language ecosystems better overall.

Now there are a lot of things that are cool about Java. The standard RTL, so there is a standard way to create multiple threads, do file I/O, networking or other similar things is quite cool. (I’m used to the days of early versions of Pascal or C where it was anybody’s guess how to do these things.) But in my estimation the following four features have made the overall Java ecosystem quite friendly compared to other languages.

1. Reflection.

Java’s reflection system is quite complete, allowing full introspection for any given object of the class of that object, the interfaces it implements, the base class it extends, the methods it implements and the fields that are contained in that class. With methods you can introspect the parameters and the return values. You can even dynamically, using the reflection system, construct objects on the fly and invoke methods on the fly.

Java’s reflection system is far more powerful than similar systems in Objective C (which, by design, cannot really allow introspection of the methods implemented by a class, since methods are just messages and there is no strong association of implemented messages), or in C++ (which really only allows you to discover the class of an object, and that’s it.)

Later versions of Java even provide an annotation mechanism by which classes can be annotated or marked with special flags, so during introspection different classes can be handled in different ways.

This level of reflection allows one to construct a complete dynamic serialization library, serializing and deserializing objects without ever needing the object to know what is being done to it.

And because the reflection information is contained (as a first class, well documented data structures) inside a compiled .class file, it is not all that difficult to compile a Java file, then introspect the .class file and provide information about that class. By using this it is possible for an IDE to automatically determine, for example, which methods in an abstract class need to be implemented by a child class, and automatically write the missing method calls for you. I suspect in fact this is how the Eclipse functions to create a new class, populating the methods that need to be implemented, is performed.

I use that all the time.

2. Proxying.

Java also has the ability to, given an interface class declaration, create a proxy class which provides an implementation of that interface, redirecting the method calls to another object.

Proxying is a very powerful mechanism which allows remote procedure calls to be implemented with just a few lines of code. Proxying also allows other very powerful techniques to be implemented, such as using interface methods to define the constant values in a property file, and automatically associate variables in a dynamically loaded configuration file.

While proxying is a bit of a one-trick horse, it provides a tremendous amount of power that, combined with reflection, allows you to do RPC without having to create a RMI language specification and compiler to build the client and server components. You can infer the parameters with reflection and redirect with proxying.

3. Exception Stack Introspection.

Of course most languages have exceptions. What makes Java really cool is the ability to dump the function call stack when an exception is thrown. This is an extremely powerful mechanism because it allows you to know precisely what was thrown and where it was thrown from. And most of the time, knowing what happened and where gives you a huge clue as to why something went wrong.

In fact, I’d say the biggest mistake I’ve ever seen a Java programmer make is to re-throw an exception without setting the cause parameter of the re-thrown exception. For example, I’ve seen the following:

try {
    // A whole bunch of complicated crap with calls
    // into thousands of lines of error-prone methods.
    ...
}
catch (Exception someException) {
    throw new StandardException("All hell broke loose.");
}

Then I see the following:

com.chaosinmotion.mything.StandardException: All hell broke loose.
	at com.chaosinmotion.mything.Test.doSomething(Test.java:19)
	at com.chaosinmotion.mything.Test.main(Test.java:32)

And I want to murder the developer who couldn’t be bothered to add an ‘initCause’ call to the rethrown exception.

4. Inner classes and anonymous classes

To me, these both have the same net effect: they give the developer the ability to define a class inside another class, which has access to the parameters of the outer class, which can then be used as a form of closure. And closures are cool because they allow a callback function or method invocation to have access to the immediate lexical environment where the functioning requiring the closure to be invoked.

For example, suppose we have a method call that takes an interface, where the method in that interface is called for each list of objects in a system:

    private interface Callback
    {
        void object(Collection l);
    }

    private void getAllObjects(Callback callback)
    {
        ....
    }

We can gather up all of the objects in a single list using an anonymous inner class in a function call:

    private List gatherAll()
    {
        final ArrayList n = new ArrayList();

        getAllObjects(new Callback() {
            public void object(Collection l)
            {
                n.addAll(l);
            }
        });

        return n;
    }

While Java’s implementation of anonymous functions may not meet the strict criteria of closures, in that you do not get full read/write access to all the stack variables within the function where the anonymous class is declared (thanks to the Funarg Problem), read-only access to mutable objects gets us close enough that it doesn’t really make much difference.

Closure-like functionality is such a cool language feature that Apple added it to the latest version of Objective C. Something like the above could be done by declaring a method -getAllObjects: which takes a block–a reference to a function with closure:

	- (void)getAllObjects:(void (^)(NSArray *))callback;

Then calling it with a block that accumulates the results:

    - (NSMutableArray *)gatherAll
    {
        NSMutableArray *n = [[[NSMutableArray alloc] init] autorelease];

        [self gatherAllObjects: ^(NSArray *param) {
            [n addObjectsFromArray:param];
        }];

        return n;
    }

The reason for me picking these four features is simple: I believe if other languages were extended to provide these features, then it would not only make the languages themselves more useful, but if they were provided, they would also allow the ecosystem of IDEs and compilers to become more useful as well. Reflection is extremely important to the ecosystem of IDEs: by being able to parse some sort of data structure during development that gives full inspection of the various components of a class or collection of function calls, it would make automatic code generation far easier to create. Better yet, if compilers for a given language could standardize on an intermediate “story of your compile” like structure that also gives line numbers for compiled objects (as is provided in Java class files with debugging turned on), it would make it extremely easy to automatically generate code on the fly during development.

And every language has an undue amount of bookkeeping stuff that needs to be written which make those languages cumbersome to use. C++, for example, requires all methods to be described in two separate places: once in the header file, and again with the method code. Imagine an IDE which could automatically generate the code declarations based on the header declarations, leaving you to only fill in the blanks. Or an IDE which could automatically add the required methods from the abstract class method declarations in an abstract C++ class.

Filed under: Java | Posted on September 2nd, 2010 by William Woody | No Comments »

Scroll FlowCover to a specified panel.

I thought for some reason this code was in FlowCover. It’s not, so here it is.

The following routine, if added below -startAnimation: will cause the tiles to scroll to the specified tile, with pos specified from 0 to the max-1 tile.


- (void)runToPos:(int)pos
{
	int max = [self numTiles]-1;
	if (pos < 0) pos = 0;
	if (pos > max) pos = max;

	startOff = offset;
	startSpeed = sqrt(fabs(pos - startOff) * FRICTION * 2);
	if (pos < startOff) startSpeed = -startSpeed;

	runDelta = fabs(startSpeed / FRICTION);
	startTime = CACurrentMediaTime();

	NSLog(@"startSpeed: %lf",startSpeed);
	NSLog(@"runDelta: %lf",runDelta);
	timer = [NSTimer scheduledTimerWithTimeInterval:0.03
					target:self
					selector:@selector(driveAnimation)
					userInfo:nil
					repeats:YES];
}

The way this works is to calculate the flick speed necessary to run the animation to the specified position, and runs the animation.

Filed under: Uncategorized | Posted on September 2nd, 2010 by William Woody | No Comments »

Time Zones are a pain in the ass.

Some interesting links I found that discuss time zones:

Complete timezone information for all countries. – Just as the label says

The official US time (NIST & USNO) – Displays the current time in the 10 major time zones in the United States.

Time Zone Converter – Allows a search of the various time zones in the world.

What makes time zone conversions a pain in the ass is that each jurisdiction has control over its own timezone. In some places (like California) we’re on Pacific Standard Time/Pacific Daylight Time, period, thankyouverymuch, haveaniceday.

But in places like Indiana, where every blasted county has it’s own ideas as to if it is in Central Standard Time, or Eastern Standard Time, and if the cows there can tolerate the shift between daylight savings time–well, the tz database becomes a hot mess, with things like “America/Indiana/some-random-place” littered throughout. On the other hand, most of that hot mess boils down to “this week, Knox County Indiana has decided to switch time zones from central to eastern”–which, for a UI timezone picker, doesn’t really matter. The fine folks of Knox County can just pick “Central” or “Eastern” and be done with it.

Sometimes the easiest sounding thing, like “pick a time zone”, becomes a royal pain in the neck. And even easier things like “what time is it in GMT at my location” become royally hard. It’s like that, when local politics gets involved.

Filed under: C++, Java, Objective C++, Things To Remember | Posted on September 1st, 2010 by William Woody | No Comments »

There is nothing new under the sun.

Well, the rant on TechCrunch has gone global: Tech’s Dark Secret, It’s All About Age.

Excuse me while I throw in my two cents, as a 44 year old software developer.

  1. Pretty much all of the useful stuff in Computer Science was invented by the 1960′s or 1970′s. Very little is out there today that is really “new”: MacOS X, for example, is based on Unix–whose underpinnings can be traced back to 1969, with most of the core concepts in place by the early 1980′s.

    Even things like design patterns and APIs and object oriented programming stem from the 70′s and 80′s. Sure, the syntax and calling conventions may have changed over the years, but the principles have stayed the same.

    For example, take the MVC model first discussed formally 20 years ago. The ideas behind that weren’t “invented” then; the MVC papers from Talgent simply codify common practices that were evolving in the industry well before then. One can find traces of the ideas of separating business logic from presentation logic in things like Curses, or in Xerox Parc’s work from the 1970′s. I remember writing (in LISP) calendrical software for Xerox as a summer intern at Caltech, using the principles of MVC (though not quite called that back then) in 1983.

    Or even take the idea of the view model itself. The idea of a view as a rectangular region in display space represented by an object which has a draw, resize, move, mouse click handler and keyboard focus handler events can be found in InterLisp, in NextStep, in Microsoft Windows, on the Macintosh in PowerPoint; hell, I even wrote a C++ wrapper for MacOS 6 called “YAAF” which held the same concepts. The specific names of the specific method calls have changed over the years, but generally there is a draw method (doDraw, -drawRect:, paint, paintComponent, or the like), a mouse down/move/up handler, a resize handler (or message sent on resize), and the like.

    The idea never changes; only the implementation.

    Or hell, the Java JVM itself is not new: from P-machines running a virtual machine interpreter running Pascal to the D machine interpreter running InterLisp, virtual machine interpreters running a virtual machine has been around longer than I’ve been on this Earth. Hell, Zork ran on a Virtual Machine interpreter.

  2. I suspect one reason why you don’t see a lot of older folks in the computer industry is because of self-selection. Staying in an industry populated by Nihilists who have to reinvent everything every five years or so (do we really need Google Go?) means that you have to be constantly learning. For some people, the addiction to learning something new is very rewarding. For others, it’s stressful and leads to burnout.

    Especially for those who are smart enough to constantly question why we have to be reinventing everything every five years, but who don’t like the constant stress of it–I can see deciding to punt it all and getting into a job where the barbarians aren’t constantly burning the structures to the ground just because they can.

    I know for a fact that I don’t see a lot of resumes for people in their 40′s and 50′s. I’m more inclined to hire someone in their 40′s as a developer than someone in their 20′s, simply because you pay less per year of experience for someone who is older. (Where I work, there is perhaps an 80% or 90% premium for someone with 4 or 5 times the experience–a great value.)

    But I also know quite a few very smart, bright people who decided they just couldn’t take the merry-go-round another time–and went off to get their MBA so they could step off and into a more lucrative career off the mental treadmill.

    I have to wonder, as well, where I would be if I had children. Would I have been able to devote as much time reading about the latest and greatest trends in Java development or Objective C or the like, if I had a couple of rug-rats running around requiring full-time care? (I probably would have, simply because I’d rather, on the whole, read a book on some new technology than read the morning paper. I would have probably sacrificed my reading on history and politics for time with my children.)

  3. There is also this persistent myth that older people have familial obligations and are less likely to want to work the extra hours “needed to get the job done.” They’re less likely to want to pull the all-nighters needed to get something out the door.

    But in my experience, I have yet to see development death marches with constant overnighters paid off in pizza that didn’t come about because of mismanagement. I don’t know another industry in the world where mis-managing the resource sizing, and demanding your workers work overtime to compensate for this failure to do proper managerial resource sizing and advanced development planning is seen as a “virtue.”

    And I suspect the older you get, the less likely you are to put up with the bullshit.

    Having seen plenty of product make it to market–and plenty not make it to market, and having lived through several all nighters and product death marches, I can see a common theme: either a product’s sizing requirements were mismanaged, or (far more commonly) upper management is incapable of counting days backwards from a ship date and properly assessing what can be done.

    The project I’m on, for example, was given nearly a year to complete. And Product Management pissed away 7 of those months trying to figure out what needs to be done.

    The younger you are, the less likely you are to understand that three months is not forever, and if you need to have something in customer hands by December, you have to have it in QA’s hands by September or October–which means you have to have different modules done by July. It’s easy if you don’t have the experience to understand how quickly July becomes December to simply piss away the time.

    So I can’t say that it’s a matter of older people not being willing to do what it takes–if upper management also was willing to do what it takes, projects would be properly sized and properly planned. No, it’s more a matter of “younger people don’t have the experience to do proper long-term planning to hit deadlines without working overtime,” combined with “younger people don’t have the experience to call ‘bullshit’.”

  4. There is also, as an aside, a persistent myth that it takes a certain type of intelligence or a certain level of intelligence to be successful in the software industry.

    I’m inclined to believe more in the 10,000 hour rule: if you practice something for 10,000 hours, you will become successful at that thing.

    Intelligence and personality could very well help you gain that 10,000 hours: the first few hours of learning how to write software or learning a new API or a new interface can be quite annoying and stressful. But if you persist, you will get good at it.

    Which means IQ and personality, while perhaps providing a leg up, doesn’t guarantee success.

    It’s why I’m inclined also to want to favor more experienced and older developers who have persisted with their craft. If we assume a 6 hours of actual development work (with the other 2 on administrative stuff), then a work year only has 1,500 hours–meaning 10,000 hours takes about 7 years to accumulate. Assuming you start out of college at 21, this means that anyone under the age of 28 will not have sufficient experience to be good at their craft.

    And that assumes they practiced their craft rather than just going through the motions.

The whole “it’s all about ageism” in the tech industry is an interesting meme–simply because it’s far more complicated than that.

Filed under: Commentary, Politics | Posted on August 30th, 2010 by William Woody | No Comments »

GWT Weirdness Of The Day.

On the project I’m working on, I noticed that, for whatever reason, it was now taking up to 3 minutes to start a web site running under GWT. That is, from hitting the “Debug” button and opening the web site in the browser, to seeing the web site actually up and running, was taking just shy of three minutes, with most of that time with the Spinning Beach Ball Of Death™.

I finally figured out what was happening. The first clue came from hitting ‘pause’ on the Daemon Thread labeled “Code server for myProject from Safari DMP…”, and noticing a lot of time being spent walking around inside the source kit for resources.

And noticing a lot of that time was spent in a bunch of .svn folders.

I think what was going on is that, for some reason or another, a lot of crud had accumulated in a number of random hidden folders associated with subversion. I don’t know if this is normal or abnormal behavior for Subversion; I just know there was a bunch of crap floating around there–and GWT was spending several minutes walking around the directory structure.

Blowing away the entire source kit and checking it all out fresh from Subversion reduced the startup time to less than 5 seconds. And it greatly improved the performance of the browser in the debugger as well: rollovers which were taking a while to get detected now are fast and responsive.

I suspect all the crud in my source directory was creating a lot of crap for the debugger to deal with, creating a substantial slowdown that got cleared right up.

Filed under: GWT, Java | Posted on August 25th, 2010 by William Woody | No Comments »

Tools in Eclipse I wish were in Xcode for Objective-C and C++.

1. Override and implement methods.

It’d be nice if there was some way to indicate that the Objective-C and C++ class could automatically generate the proper header modifications in a C++ or Objective-C class declaration, and create an empty method call in the source file, to override a virtual method (in C++) or a message (in Objective C) in it’s parent class.

2. Implement methods.

Similarly it would be nice if there was some way to simply write the C++ or Objective-C header, then have the method or message body automatically generated from the header in the source file.

3. Implement missing abstract methods/protocol methods.

And similarly it would be nice if there was some way for an IDE to determine that you have a class which needs to extend and implement a number of abstract methods or protocols, and automatically insert them into the header or source file.

4. Generate core methods (C++)

In C++, there are a few methods that you need to implement if your class is to participate in the C++ STL as a key, as a sortable object, or as an array object. It’d be nice if there was a mechanism to automatically generate the necessary method definitions and (if possible) even attempt to divine reasonable defaults for these methods in the same way that Eclipse will automatically generate equals() and hashCode().

Java is a very verbose language. But most modern IDEs hide this verbosity by providing a number of tools to automatically generate the “bookkeeping code.” For example, in Eclipse, if you declare a class that implements an interface, Eclipse will offer to automatically fill in the missing method declarations for you. So it’s an easy matter of simply declaring the interface, and letting Eclipse to the tedious cut and paste work.

Most languages are verbose in their own ways. Objective-C and C++ are verbose in that they require you to declare your methods in two places. Synchronizing between those two places is a pain in the neck.

Of course in Java once you build a class file parser it’s trivial to build code to walk the method tree for an interface or an object, and automatically generate template code. What’s missing is a similar interface to an Objective-C or C++ parser to automatically generate the parse trees necessary for automatic code generation. In each of the cases above, it wouldn’t even require a full parse tree–just enough of the parse tree to understand the C++ or Objective-C class declaration objects. (Meaning you would only need to parse the class or @interface declarations.)

I can daydream, can’t I?

Filed under: Uncategorized | Posted on August 24th, 2010 by William Woody | No Comments »

Interesting MacOS Java Links

Java Integration Document.

The classes used to hook into Finder.

Testing to see if you’re running on MacOS X, so you can set up your LAF to resemble a Macintosh application.

It’s interesting that it doesn’t take a lot of work to get a working application that has the correct look and feel on MacOS X 10.5 or later. Too bad most Java developers don’t seem to put in the extra work–because if they did, they’d have something that looks exactly like every other application on the Macintosh platform instead of refugees from the UI wasteland that is Linux.

I like Java as a programming language. I like Java a lot. Too bad Java has been inundated with a metric-shitload of useless and over-engineered frameworks that really don’t add any value. (I’m looking at you, Spring…)

Filed under: Uncategorized | Posted on August 13th, 2010 by William Woody | No Comments »

Things to remember: table-layout

By default a table in HTML wants to do all sorts of auto-magic reflowing stuff–which is a pain in the ass if you want to explicitly set the width of the columns via GWT (or JavaScript). But if you set the CSS attribute table-layout to fixed, column widths are honored. Wrap each of the items in the content area with ‘overflow:hidden’ and ‘white-space:nowrap’, and if the text associated with a cell overflows, it gets neatly clipped.

Filed under: Things To Remember | Posted on August 10th, 2010 by William Woody | No Comments »

Why are all my moderation e-mails going to spam?

If you posted a comment to this blog, my apologies if they weren’t approved. I get so few comments–and for whatever reason, the e-mail indicating I have comments went to spam instead. (*sigh*)

Filed under: Uncategorized | Posted on August 10th, 2010 by William Woody | No Comments »

Retention Policy in Java Annotations

Something I keep forgetting, which I’m recording here so I can remember in the future.

When creating a new annotation which is to be parsed during execution with Java Reflection, you must change the retention policy with the @Retention annotation.

So, for example:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
...
}

This will keep the annotation around when checking annotations at runtime.

For whatever reason I keep forgetting this.

Filed under: Uncategorized | Posted on July 27th, 2010 by William Woody | No Comments »

Copyright © 2010 William Edward Woody. All rights reserved.

Theme modified from the original Tech Blue, designed by Hive Designs • Ported by Free WordPress Themes and Linux Web Hosting