Thursday, December 25, 2008

Sea Spin: My Latest Java 4K Game

Merry Christmas, and here's my latest Java 4K. This is my 3rd year in the contest, I think. And I've gone back to focusing on trying to make a good game. (Last year was an experiment in shrinking Scala, and it didn't fare so well in judging.)

I've done professional enterprise Java development. These days I help teach Java for my pay. I've also been employed on Java applet development long ago. Been around the various sides of it. I get annoyed some by the politics and some by the lack of agreement of some folks with my own preferences of where Java should go. But every year (at least so far) the Java 4K game contest makes me feel good about Java again. For me, it's the coolest thing in Java. Not that it proves superiority. Just has a sweetness all its own.

Maybe I'd get into a similar mini-HTML game if one came along, but it's Java 4K for me for now.

Thursday, December 18, 2008

What Erlang's got that Java hain't. And vice versa.

I'm toying in Erlang now a bit. Some VM features are specific to their language needs. I won't focus on them here (though tail recursion would still be wonderful). These items seem more fundamental:
  1. Fast context switching.
  2. Update while running.
  3. GC per thread.

All these are related. And what do they all have in common? Is it any surprise that Ericsson has shown an interest in Multi-VM Java? What use cases could possibly exist for MVM? Of course, system-process level is nice for visibility to the OS, but adding the option for light-weight "green" processes for MVM would also be cool.

Side note 1: Java's GC generally is way more advanced than Erlang's, so far as I can tell. Java's also far ahead in some other categories, including raw performance.

Side note 2: Sharing simple data types in messages seems a lot more robust than trying to serialize objects generally.

Wednesday, December 17, 2008

Erlang as a Multi-language VM

Hmm. They don't seem to be fully stable projects, but the idea of compiling languages like JavaScript (see ErlyJs) and MATLAB (see Matlang in the High-performance article here) to the Erlang VM seems like an interesting strategy.

I wonder if we'll see more of this in the future.

Software that Keeps On Ticking

I like the attitude of Erlang, at least as I understand it. You should be able to update software without shutting it down. I guess many dynamic languages have a similar attitude. Software should be able to run for weeks, months, or years on end. That Firefox or Eclipse wants me to restart for updates bothers me.

If Erlang comes from telephony and server perspectives, I think the attitude still matters elsewhere.

I'm into robotics. I think that it should be possible to update robot software components without shutting the software down. I see three main directions: (1) use Erlang or some other such system that won't require restarts, (2) use separate OS processes and IPC so that individual processes can restart without the whole system coming down, or (3) since individual processes are still heavyweight in Java, I think OSGi might work instead, if done right. Erlang seems to claim the lightest weight multithreading of them all, but I don't have experience to know if it's true. I also like the idea of abstracting local vs. remote actors.

Concerning Eclipse, they should build "update while running" into the expectations. If an extension can't be correctly installed, updated, or uninstalled while Eclipse is running then it should be considered broken. However, since it gives me the warning every time, I presume people haven't done a good job, and I just tell it to restart.

Thursday, December 11, 2008

Runtime Optimization (JVM) vs. Haskell

I have been considering learning Haskell seriously. It really is sweet in many ways. And I'm getting tired of Java politics. Maybe just a phase I'm going through.

But in any case, I thought, "Wouldn't it be sweet if purely functional meant that Haskell caches useful tidbits automatically for fast performance?" The answer is that it doesn't, but you can cache (er ... memoize) results manually. The complaint being that caching everything would be expensive for memory.

Well, if someone made a cool VM for Haskell, couldn't it learn the hot spots in code from watching it run, and thereby know more easily what to cache? Maybe HotSpot can't do this particular optimization so easily (Java not being purely functional or anything), but it definitely made me think about the mentality of prior vs JIT/lazy optimization. Hmm, and there's that lazy word again.

Anyway, back to doing statistics and plots in MATLAB.

Monday, December 8, 2008

No Inline Functions for Web Workers?

I have yet to understand why Web Workers seem to support only separate JS files instead of function pointers. Any authoritative info on the subject?

Tuesday, December 2, 2008

Full Screen Goodness on Dell Mini Ubuntu

I just want to say how happy I am to discover that my Dell Mini running Ubuntu makes any window full screen by pressing the Windows button. I just LOVE FULL SCREEN. Hmm. I guess that makes my opinion clear.

Oh, and the solid state drive makes this thing fast.

And overall at this point, my Dell Mini is easily my favorite computer I've ever owned. Even more than my old Amiga 1200. Yep. Seriously.

Disclaimer: I haven't used other netbooks, so I'm not making a comparison here. I also don't know if Ubuntu normally these days makes windows full screen with the Windows key. I just happened to notice it here now.

Monday, November 24, 2008

Java's Still Great (but where is it?)

To all the Java naysayers: Java isn't dead, unless Mozilla was dead before Firefox. That is, the story's not yet written. I don't know what will happen.

Compared to C++ development, Java is a breeze (except for checked exceptions and no RAII nor operator overloading). Talk about reinventing the wheel 50 times if you want to go C++. And with Java open source, you can even simplify deployment, if you really want.

So, now I'd like to download OpenJDK 7 for my PowerPC Mac Mini running Mac OS 10.4.

Um, I meant, OpenJDK 6. Um, maybe Java 6? Or, well, I guess I'll just stick to Java 5.

Maybe I'm just a beggar and not a helper. But, I'm the sort that would like to do things with Java. I haven't planned the luxury to spend time developing Java itself. And maybe I'm just asking too much? Why ask for support for a computer that's a few years old?

Well, I can download Firefox 3, Flash 10, or Mono 2, and they all seem to work. Looking at all 4 of these players, which one of them is not like the others?

Friday, November 21, 2008

Capitalism as a Local Optimizer?

I remember learning in economics that some folks got a Nobel Prize about 50 years ago for a proof that free markets lead to optimal policies. I wonder if anyone has investigated the assumptions in the proof in the sense that I wonder if it's really just a local optimizer (finding the nearest peak) rather than finding the best global solution (the real top of the mountain).

All proofs about the real world, of necessity, rely on assumptions and approximations. Just wondering what they are here.

I also wonder, because it seems to me like capitalism works well but is short-sighted. I'd be curious if this intuitive feel could be worked out mathematically.

Note: I'm not an economics expert, so I don't know what's been researched on this subject before.

Wednesday, November 19, 2008

Wow, C++ for Flash

Looks like Adobe beats Sun to C++ support, at least in preview release form. They've got Vorbis ported already. ODE, anyone?

Seems like I was thinking about this subject just recently.

Monday, November 17, 2008

How to Supercharge Java

I think certain changes in strategic direction by Java could help it compete far better with .NET, Flash, and browsers. Here are my recommendations:
  • Drop JavaFX and Swing (though I like Swing a lot in certain ways). Move to SWT.
  • Drop NetBeans (despite the nice progress they've made). Centralize on Eclipse.
  • Provide a C/C++ to JVM compiler and perhaps so2jar and dll2jar tools.
  • Provide jar2swf and swf2jar tools, and contribute to an existing or new open-source Flash player (now that the spec is open, right?).
  • Also support GWT big time.

I know enough to understand that many folks inside and outside of Sun would scream a lot if some of these directions were taken. I also don't know what's best for Sun as a company, but gradually losing mind share for Java probably doesn't help them any. Not that I know the stats.

Just some thoughts here, and I could be wrong.

Friday, November 14, 2008

Wiki Math and Language Consequences

I was thinking how cool it would be to have a Wikipedia but with actual usable algorithms instead of human-oriented text. As I thought about it, it dawned on me that MATLAB's one-function-per-file and 'this'-passed-as-first-param notions (generalized in other languages to full multimethods) are just the kinds of things you'd want in such a system.

Also, the idea of generic mathematical concepts (via interface implementation, duck typing, or static C++ templates) leads to wanting fewer versions of the same function, so namespacing issues might matter a bit less.

Still, I think namespacing matters some. Maybe the ability to apply multiple tags to functions would be nice instead of the draconian namespacing of common programming languages. But could you never have two versions of the same function with the same tag? Maybe just multiple matches based on specified desired tags would result in an error. Hmm.

And I was also thinking about how you could imply templates just by not specifying the types of the parameters (again, the static variation on duck typing).

In the end allow translation to C/C++/Java/C#/whatever based on conventions that work well for that language.

I think the math language itself in the wiki would need to look somewhat like MATLAB (and/or Python). And of course, rendering to nice typeset equations online (image or MathML or LaTeX) would be sweet.

If only I had a ton of additional time on my hands.

C++ Templates as Duck Typing

Just remembered the relationship between duck typing and C++ compile-time templates. Writing it here as a note for future reference.

Thursday, November 13, 2008

Enough with Java Ports

Or rather, enough with requiring Java ports. Though I guess the encouragement of genetic diversity has its pros.

I also applaud Jython, JRuby, JBullet, and many more. I was once working on an ImageMagick and RMagick port for Java/JRuby. I didn't expend the time to make enough progress, though I believe it could work out well.

My concern is that the "Java apartheid" coupled with lack of direct support for running C/C++/DLLs directly on the JVM leads to too much wasted effort. And I get the point of how much easier it is to pick up and use a jar (wherever you are) vs. picking up and using native libraries.

There are some (HUGE!) gotchas, but I think it should be possible to run native code directly in Java. Two techniques:
  1. Use JPC as a base for running x86 DLLs (or Linux so files or whatever) as if they were JVM bytecode, or
  2. Compile C and C++ (and others in GCC) directly to JVM bytecode so that structs, classes, namespaces, and so on all map nicely and are directly available from other JVM languages (like Java even).

I'm don't plan to work on this myself, but I think it's a right thing to be done. And meanwhile, I'm tempted to get back into coding C++. (Been a while.)

Actually, I double-dog-dare anyone to make a C++ to JavaScript compiler.

Wednesday, November 12, 2008

Evil MATLAB Copy-On-Assign

Saying this kind of thing is really annoying:

item = items{i};
item.whatever = 'something';
items{i} = item; % <-- The evil requirement.

Maybe I just need to learn the right idioms, but this kind of thing taken to much more complicated software is just killing me right now.

Tuesday, November 11, 2008

Favorite Programming Language Qualities

Here are my favorite qualities of programming languages:
  • Consistent (orthogonal feature set)
  • Expressive
  • Convenient
  • Small (core language features and API)
  • Extensible
  • Safe (encouraging quality code)
  • Familiar (for newcomers)
  • Easy reading for people (for newcomers and experts)
  • Easy reading for computers (toolable, optimizable)

I think some of these tend to work against each other, and some support each other.

Looking at present times, small core APIs (microkernel-ish) sure aren't in vogue. Rather people tend towards "batteries included". Note that a small core should make cross-platform easier to do.

I also wonder if the current trend towards optimizing and tooling dynamic languages will eventually overcome static languages. I think it will be a while yet, but things seem to be moving that direction.

Wednesday, November 5, 2008

TeXlipse - Sweet

Finally remembered to search for "LaTeX Eclipse", and it sure found something. I just got started with TeXlipse (as in, just now), so I might not know all the down sides, but it seems really useful at first glance (autocompletion, highlighting references, BibTex support, ...).

Monday, November 3, 2008

Performance Basics

From my experience, it seems like these are the basics of achieving good performance:

  • Cache.

  • Index.

  • Parallelize.

  • Profile.

  • Simplify/Shrink (without changing external behavior).

If you move to a fuzzier world, these become additional techniques:

  • Approximate.

  • Simplify/Shrink (by changing requirements).

I don't emphasize algorithms, because picking up ready-made algorithms from a third party is so common these days. (Does that mean we actually make progress? I think so.) However, some folks still have to provide said algorithms, so it might apply to you. The same kind of issue applies to being hardware-friendly, I think.

Anything else I'm missing that doesn't fall into these categories?

More Research Bullet Points

Also wanting to track other things on my sometimes-too-subconscious radar, here are additional bullet points to follow up my research mission statement:

  • Good enough now is better than perfect later. Related to performance profiles and satisficing.

  • Multiple strategies at all levels simultaneously, including alternate algorithms. Different kinds of feature spaces in use. Parallel computation to let bests bubble up on different paths. (More on this and the next bullet discussed in my later "prioritized reduction engine" post.)

  • Metathinking. How to decide what to think about. CPU cycles are scarce resources.

  • Software built to be usable by third parties, not just for experiments. Open source where possible.

  • Multiclass assignment ("tagging" in modern netspeak) and fuzzy class membership.

  • Graph structure matching (analogies). Relationship to traditional predicate logic?

  • Ensemble of simple behaviors often better than single complex ones.

  • Allow compromise between behaviors. I might want to rest an injured leg, and I might want to walk somewhere. One doesn't have to rule out the other. I might just walk slowly, more carefully, or less often.

  • Automatic splitting of problem space into different behaviors. (Learning basis functions.)

  • Behavior activation/deactivation based on applicability and thinking resource limitations.

  • Behaviors as semi-peers rather than specific layers. The kinds of controlled actions or perhaps group activation/deactivation might imply layers still.

  • Root behaviors live independently. Some behaviors could spawn others which might be short-lived. Longer-lived behaviors might attach themselves as roots.

  • Hmm. Almost sounds like a hurd of interfaces representing depth of Unix-replacing daemons of interfaces representing depth ... I mean, like a multitasking operating system. No, I've sadly never used GNU Hurd.

  • Simulation is nice, but real world rules.

  • Most things shouldn't require huge hardware. If it doesn't go fast enough, find better algorithms.

  • Be willing to be inspired by biology, but don't get too committed to the idea.

  • Dynamic dimensionality. If sensors or actuators (or intermediate computation results) come or go, the show should go on. Algorithms shouldn't need recoded to deal with extra dimensions.

I've been warned some about watching ideas closer so other people don't steal them and publish first, but I think my chances of being seen by a potential idea thief are low. Until I get super famous (cough, cough) of course. And most people prefer to pursue their own ideas more than those of others.

And finally, I can't do everything anyway. If someone gets cool ideas from me, I guess I'll just have to hope it's something I wouldn't have gotten to.

Finally, this stuff here is still pretty high level. Not exactly a how-to manual. Need to figure out all the how-tos myself first, anyway, if I even get to focus on any of this.

So, um, steal away or something.

Saturday, November 1, 2008

Simple Research Mission Statement

Here's a stab at summarizing a research mission. Focus is hard for me, so this seemed like a good exercise. I'd like to focus on these things:

  • Everyday, general-purpose robots.

  • Real-time, multi-objective, very high (10s, 100s, 1000s?) degree-of-freedom decision making in dynamic environments.

  • Preference to automatic learning over hard-coded engineering. Also, parameter elimination.

  • Extract research from practical application rather than hoping theory will be practical. In other words, how do I know I'm asking the right questions?

Maybe I can refer back to this or post updates (like these bullets) as needed.

Tuesday, October 28, 2008

The Web Client Platform

With Firefox (and presumably others) getting fancy scene graphs with video on all three platforms out today (in beta form), and with JavaScript JIT support coming in the near future to multiple browsers, where does that leave client-side Java?

If someone makes serious (and open source) dev tools for JavaScript, I'd probably move on. JS has flaws, but so does Java.

There are nicer languages out there than either one, but I always feel drawn back to the main language for the platform. But that's also part of why I'd rather see good JS tools than use GWT. I just haven't seen them yet. Still, JS is the metal in browsers.

I'd also be curious to see a server-side JS framework get traction. Hasn't happened yet despite many attempts. Nothing is yet (and perhaps never will be) "the metal" on the server.

Monday, October 27, 2008

JBullet in jME Physics

Just noticed today that JBullet support is in svn for jME (jMonkeyEngine) Physics. I tried out the ragdoll demo, and it seems like things aren't quite ready yet. But still cool to see the development.

Anonymous Classroom Feedback

I was just imagining today the idea of people in the classroom, with notebook computers or cell phones or whatnot, being able to raise red flags anonymously when they aren't following. The number of red flags from different students could control a general classroom "temperature" visible on your own projected screen.

If the temperature gets too high, it's time to slow down. Also could allow full anonymous questions to be sent up.

The goal here being to let people give anonymous feedback if they are afraid of looking like dummies in front of the crowd.

Could be cool, or maybe old-fashioned watching faces and asking for questions is better.

Other Apps as Automated Tests

I remember hearing about how Microsoft has rooms full of automated tests of running other people's programs on Windows. I've also heard about browsers using web sites as tests. I guess beta testing in general is about this kind of thing, just involving people in the loop.

Seems like to test your own library, if licensing allows it, you could actually include 3rd-party applications using the library as part of your own automated test suite, including their own unit tests. Might not be so bad in some cases.

Wednesday, October 22, 2008

Mixins and Spreadsheets

It just occurred to me that mixins (such as seen in Scala, Fan, Ruby, or many other languages) and everyday spreadsheets have a lot in common. I tend to prefer C#-style static extension methods. Keeps things cleaner and leaner in my opinion, but it doesn't give you the chance to have tons of default-implemented-yet-still-customizable behavior.

Mixins do provide that. And it occurred to me that's a lot like spreadsheets. You can have a lot of cells that "inherit" functionality via the drag operation, but you can customize individual cells on the fly. Not each one has to be just like the other.

Not a perfect analogy, but I think there's some value in considering the relationship.

Thursday, October 16, 2008

Random Testing

So, I had a need the other day to test various permutations of some numbers (and ignoring what this is or why for the moment). Being too lazy to think about coding the permutations, I just used Collections#shuffle(List<?>). In my case, it got the job done:

import static java.lang.Math.*;
import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

public class Whatever {

private int secondGreatest(int a, int b, int c, int d) {
return min(max(a, b), max(c, d));

public void testSecondGreatest() {
List numbers = Arrays.asList(1, 2, 3, 4);
for (int i = 0; i < 20; i++) {
"for list " + numbers,


It fails, for instance, with text like "java.lang.AssertionError: for list [4, 3, 2, 1] expected:<3> but was:<2>", but it's the not the same failure every time, and there's a probability (which I haven't calculated) that it might pass even though it shouldn't.

So, what's the big picture question? Lots of test data might be a bother to produce in advance or even impossible if the domain is huge. Even an algorithm to test every possibility might take too long. Or I might just be lazy like in this case. Or, in messier contexts, it might be impossible to guarantee the results perfectly, so the results themselves (not just the test cases) might be random. So you have to deal with that in some fashion.

Summary, seems like random (or "stochastic" if I want to sound academic?) testing can be either convenient or necessary in some circumstances, but it doesn't necessarily prove that the program works as expected. Might beat no testing in many cases.

Tuesday, October 7, 2008

Unit Testing and Automatic Grading of Programming Assignments

I've found before and still that one of my least favorite things as a teaching assistant is grading. It takes time to do well, and it's hard to be consistent.

I remember once as an undergrad that I had a class with automatic grading. It ran the input and output automatically and popped out a grade.

There are pros and cons to automated grading, but I've thought of a way to make it also useful for teaching other good principles. Basically, teach unit testing by providing unit tests that their program has to pass. And use that as a way to do part of the grading automatically. There still ought to be a human involved if possible for part of assessment, but I think that giving out unit tests in advance might not be too bad of an idea in some cases.

Using Opera on Linux

The latest Firefox requires newer GTK than what I've got on the computers I have access to these days. And the latest Opera is ahead of old Firefox, for sure. So I'm experimenting with Opera these days.

Quick review: I want incremental search. Putting downloads ("transfers" in Opera) in a tab out of the way rather than an annoying downloads window is great. I've used Download Statusbar on Firefox, and that works too, but it's nice to have a non-annoying way built in.

And an update to my original post: Just be careful about random incompatibilities. Some sites I need (or want) to use Opera, others old Firefox. Sort of annoying.

Wednesday, October 1, 2008

jMonkeyEngine 2 and jME Physics 2

Turns out that jME 2 is under active development. Just no releases planned at the moment, so I pulled from svn (though I wouldn't do that with Spring for a production system). And I also pulled jME Physics 2 from svn (though it seems less active).

I had to toy around with things for a while, but I got it all happy in Eclipse and building jars with Ant (some hints, though I didn't follow instructions exactly). I also got the rag doll demo running in a separate project referencing the built jars (and native libs). Just 2 relatively readable files. Much simpler than the JBullet rag doll demo and number of classes I had to copy over there.

So, I think jME looks like a nice way to go, if I continue working on a simulated world environment. (And yes, I know about Player and Gazebo. I'll probably end up using that some, too, though perhaps for different purposes such as simulating more common robot systems.)

Some effort has gone in to supporting JBullet under jME Physics, but it's definitely not under active, public development. I haven't even looked to see if the project is from the same person as in the forum. Still, it could be a start if I care enough. The ODE wrapper seems to work for now, and LWJGL is native anyway.

OSGi for Robot Middleware

Seems like "middleware" is the term in robotics for the platform that lets the different components (usually system processes) communicate with each other. I'd previously thought about whether OSGi might be a good fit for that.

I searched a bit and found a Tobias Wegner that seems to be doing something like that, but I haven't found any papers from him at Google Scholar. Maybe I should try contacting him sometime to see about the status of his thesis.

Wednesday, September 24, 2008

Learning MATLAB

I'm out of industry and back in school these days, focusing on autonomous robots to speak generally. One of the things I knew to expect was MATLAB, and I'm learning it as I thought I'd need to. But I don't want to make it my tool of choice in the long run. I won't give a technical review here (and I don't know enough yet to give a full review), but I'm generally a pro-open kind of person. And MATLAB is definitely propriety.

But it sure pwns the competition in the research world. (Update: I mean this in terms of apparent market share, not in terms of technical merit which again I feel too ignorant to comment on.)

The main alternative is SciPy. JScience and many other options for Java seem either unmaintained or too complicated. Hmm.

Confirm Quit and Logging Off

It just occurred to me that the "Are you sure you want to quit/close/etc.?" features should be promoted to an OS (or desktop/platform) level concept. These things prevent log out, shut down, and so on. They can also cause other confusion when the system tries to guess if the software is behaving well.

Probably can't completely standardize the content of such quit confirmations, but some level of communication with the system about what's going on could make this user experience tons better.

Monday, September 8, 2008

Fan Language

By the way, I should have blogged a while back about the Fan programming language. I got relatively involved in conversation there. And I even got into the code just a bit.

My quickest summary: It's a better Java. As in, it tries to be a nice, clean, accessible language that encourages consistent style and good, readable code. But it's better than Java in that it clears out the cruft (starting with a clean slate, almost), and it's much nicer in the syntax arena. You don't have to slave away to get everyday things done like in Java. And it's still mostly statically typed.

That short review ignores a lot of the details. See the site for more. But as a summary, can you say all the same things about Groovy or Scala (alternative "better Javas")?

That said, I'm still not sure whether I'll be using it in the future. I think it's possible. For now, I think I still want Java's tool support and low-level speed. (Yes, I said "low-level speed" in reference to Java.)

Friday, September 5, 2008

3D Java Physics: JBullet

After having trouble finding much better than ODE wrappers for 3D physics in Java, someone pointed me this week to JBullet. Seems to work great from my experiments so far (just learning how to run the demos from a new Eclipse project at this point).

Pure Java is nice.

Side note, a project to convert x86 to JVM bytecode and automatically run DLL and ELF so files would be sweet. That would auto-port lots of native libraries to Java. Well, in some cases you might need semi-deep OS emulation.

Thursday, March 6, 2008

Trac and Mercurial for JVM?

Does this mean we get a chance at running Mercurial and Trac within the JVM someday soon? That would be t3h r0x0rs.

Saturday, March 1, 2008

Scala Object Literals

Groovy has great object literals. See, for example, the Customer constructor call here. Unless I've missed it, Scala can't quite do that. So far as I can tell, you can only get inside the context of a class within a class body. Sort of like Java.

That's good and bad. It's bad because you can't construct objects easily without making new classes, and we all know what classes do to jar file sizes (even with pack200, so I guess I should add another $20 JVM bounty or something on inlined nested class definitions in the bytecode, something again that more than Scala can benefit from). But on the good side, it means that there are fewer ways to get things done. Fewer choices is sometimes better. Just swallow the bytes for consistency.

But, well, there are still a few options. Here are some examples without explanations of pros and cons or what's happening:

  trait Person1 {
def name: String
def age: Int
val person1 = new Person1 {
def name = "Bob"
def age = 25

trait Person2 extends Person1 {
var name = ""
var age = 0
val person2 = new Person2 {
name = "Stanley"
age = 73

case class Person3(name: String, age: Int) extends Person1
val person3 = Person3("Harold", 7)

I only do the "extends Person1" above to show that they are compatible at the interface level. Note also that there is no need for doubling the "{{" as in Java to write arbitrary code in a class body.

Once the object is made, you can't get back inside it again. That is, no 'with' blocks. If you go pure functional, I guess that's okay, but it would be nice to have available.

Anyway, there's another concept (and something you can do in Java with varargs, too, so remember that varargs are your friends), if you need heterogeneous lists:

  abstract class Option
case class For(name: String) extends Option
case class Name(name: String) extends Option
case class Text(text: String) extends Option

abstract class Widget
case class Button(option: Option*) extends Widget
case class Label(option: Option*) extends Widget
case class TextField(option: Option*) extends Widget
case class HBox(kids: Widget*) extends Widget
case class VBox(kids: Widget*) extends Widget

val form = VBox(
HBox(Label(Text("Age"), For("age")), TextField(Name("age"), Text(person1.age.toString))),
Button(Text("Submit"), Name("submit"))

And don't forget the options for inline XML:

  val xmlForm = <vbox>
<hbox><label text="Age" for="age"/><textfield name="age" text={person1.age.toString}/></hbox>
<button text="Submit" name="submit"/>

And that will conclude my summary of rudimentary object creation for today.

Wednesday, February 27, 2008

Flex Is Not The Answer

Maybe someday, and it's definitely an option. Still, the Flash player isn't open source. And yes that matters. Also, Linux is still a second-hand citizen from Adobe's perspective, so far as I can tell. Much like Mac is still second-hand from Sun's perspective. Firefox is the only platform that stays on top of things, but their feature set and performance isn't quite there.

And there's the nice options for using Flash and Silverlight, for example, to implement HTML 5 features like the video tag.

But when it comes to apps (not sites), I still like Swing and Web Start personally, no matter what some people say. I just have to target years old versions due to that Mac issue.

In the future, things may change in who knows what ways, but that's for the future.

Tuesday, February 26, 2008

XML Is Only Complicated In Our Minds

I have a common history. I heard of XML and jumped all over it. It was king. Then I decided it was overly complicated and unneeded. Then JSON (simplifying concepts in YAML) came along promising a happier and simpler data interchange. Who needs namespaces and schemas and canonical forms and InfoSet and who knows what else?

Well, um, I'm back to liking XML, just a happier-go-luckier kind.

First, my beeves with JSON:

1. No comments. So that means not human readable.

2. The spec fits on the home page, but when people say "JSON" they often mean incompatible, nice things that don't involve quotation marks in the keys. And things like that.

3. A more extreme form of 2, along with the obvious implementation in browsers, assumes that all JavaScript is JSON. Just use "eval". Well, I know regex can validate it, but lazy code can lead to pain.

4. Heterogeneous lists are awkward. As in, first a text field, then a button, and so on. Note that some of the JSON examples simplify this issue because doing it right would look uglier. I think it applies at least to the "widget" example.

Back to XML, we really just try too hard to over-engineer things. It's the mindset. Take a sample from the JSON site. Here's the XML:
<header>Adobe SVG Viewer</header>
<item action="Open" id="Open">Open</item>
<item action="OpenNew" id="OpenNew">Open New</item>

And the "equivalent" JSON:
{"menu": {
"header": "SVG Viewer",
"items": [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},

Is that really simpler? Well, "the action and label values only need to be provided if they are not the same as the id". Um, shouldn't that apply to XML, too?
<header>Adobe SVG Viewer</header>
<item id="Open">Open</item>
<item id="OpenNew">Open New</item>

Looking better. How about name value pairs? Isn't text data better than attribute values? Because it's extensible and you can wrap it in more markup, right? Well, how about just calming down. If JSON can have plain strings, I think XML can, too. Instead of this:
<param-value>Philadelphia, PA</param-value>

say this:
value="Philadelphia, PA"/>

Wow! Almost looks like JSON with those name value pairs! I didn't know XML had JSON features! But what if I wanted an object instead of a string? Just go back to using elements.

But it seems so very ad hoc. Um, well, yep. If you can be ad hoc (somewhat) with JSON, why not XML. And while you could write a schema for JSON (surely something exists?), do you usually? And is that okay? Now, I know schemas can be nice, but do you need them in every case?

Do you always need namespaces? Do you need them in JSON? If not, why not?

Meanwhile, the official DOM (especially originally) is just a terrible API, but plenty of good alternatives exist for just about every language in common use. And we're familiar with them.

So, remember, XML has lots of fancy specs and features which have proper occasions for use, but _don't use them when you don't need them_. Think happy thoughts, and XML can still be a good friend.

Saturday, February 23, 2008

Scala More Abstract and C# More Concrete than Java

First, a bit of background. I love programming languages. I was working on my own now and then before I started getting into Scala. It was closer to Java, but still extensible. But the biggest difference from Scala was that I was targeting it to be very _concrete_.

By this, I mean that Java (while nowhere near as abstract as dynamically typed languages) is still somewhat abstract in nature. Methods are virtual by default (dynamically dispatched). You have to make an extra decision to define things as final. But Josh Bloch says to design for inheritance or forbid it.

While C# doesn't try to avoid inheritance, methods are _not_ virtual by default (something Java doesn't really support for instance methods). This makes it less abstract in its default style than Java. And extension methods are really static, too.

My idea was to make classes and methods default to 'final'. I find from coworkers and myself that it's easier to know what things do if there's only one definition. And I can usually add abstraction just when needed. At least, I think I can.

Scala goes the opposite direction, encouraging generic types, abstract types, everything dynamic dispatch where possible, full object orientation and instance methods, structural typing, mixin traits that allow overriding, and so on. This is doable also, but I'd like to see better support than what Eclipse has for control-clicking on definitions. If it is overridden in the project (or workspace), please show me the options especially if the top level definition isn't fully abstract/undefined.

And it's not too hard to image the abstract meanings of types and methods. And it's not as abstract as dynamic types. But it's an issue that shouldn't be ignored when going into Scala. Scala isn't a language that prefers the concrete.

Wednesday, February 20, 2008

LINQ For Java ...

LINQ for Java should look a lot more like db4o than Quaere. An independent project to do something like db4o's native queries would be nice. Maybe sit on top of JPA for ORM, or something like that.

Tuesday, February 19, 2008

$20 Bounty For JVM Mixins

I've mentioned that Scala jars are huge, and that's mostly due to mixins. Pack200 doesn't solve the whole problem, either. So, I'll donate $20 to whomever gets mixins into the JVM such that there's no need to forward every single method individually. I'm sure other languages could take advantage of that, too. (An extra $10 points for good handling of prototypes/delegation to arbitrary objects.)

Once upon a time, I offered a $20 for immediate objects (such as representing Integer objects directly in pointers by taking advantage of unused least-significant bits) in the JVM. I'll stand by that still, too.

That's up to $50 for the entreprising individual. Just think of all the pizza you could buy. Oh, and here's the Da Vinci Machine link for getting started. Though, to clarify, I do need the final result in an official Java release before paying.

Thanks much in advance.

Thursday, February 7, 2008

IDE For Scala instead of Closures For Java

The more I think about it, the more I think that people who want closures in Java would be happy enough with Scala if they got used to it. _If_ it had competitive IDE support. And IDEs for Scala aren't nearly so controversial as closures for Java. (I can just hear the cries of "IDE support would ruin Scala!")

And _if_ Scala had really good IDE support, I wouldn't use Java if I could avoid it. Because no one is serious enough about getting rid of checked exceptions.

So I'm in the no closures for Java camp. Keep people happy.


And no ARM either, even if they get CICE. The whole overloading of 'do', 'try', and 'protected' seems scary to me. Much like the old-timey "we only have N operators in C++ so better overload them all we can" situation.

Wednesday, February 6, 2008

Methods That Look Like Vars

A couple of years ago, Tim Sweeney of Epic Games (makers of Unreal) gave a presentation on "The Next Mainstream Programming Language". See here for Cedric Beust's take.

One of the points brought out by Cedric is that evaluation should be "lenient by default". Here's a simple example in Java:

public class Numbers {
public static final int FIRST = 1;
public static final int SECOND = FIRST + 1;

The order of definitions matters a lot. You can't put the SECOND before the first. (And try circular dependencies across classes for some fun.) Well, if we used methods rather than constants, the order of appearance doesn't matter:

public class Numbers {
public static int second() {
return first() + 1;
public static int first() {
return 1;

Mr. Unreal Tournament says that the lack of dependency on definition order is better than than supposed performance gains.

Well, both examples are bulky due to Java syntax, but the methods version is obviously more work than the constants. Well, say we had a language where defining methods is as easy as defining constants. There are several such languages, and Scala happens to be one of them. This corresponds roughly to the second Java example:

object Numbers {
def second = first + 1
def first = 1

So remember, according to Mr. Sweeney, Scala's 'def' is your friend. (Unlike in Groovy where 'def' makes vars or methods, 'def' only makes methods in Scala.)

That said, I'm not super hip on all out functional programming. Immutable and semi-functional have their uses, but I'm not on the big time functional side of the Scala crowd. At least not for now.

Scala Bean Properties

First of all, Scala isn't Java even if it's interoperable. That's a pro or a con depending on your perspective. But that's how it is.

For example, take this class:

class Whatever {
var name = "Tom"

As I've mentioned before, that generates accessor methods, not a public field. Scala is way more object oriented than Java.

But the accessor methods are named "name()" and "name_$eq()". Way more sane than Java in some ways, but not compatible with say, Hibernate. So until/unless such tools add Scala support, you need to be compatible on your own.

Well, Scala makes this one not too bad. Just add an annotation to generate standard Java "getName()" and "setName()" (in addition to the Scala-conforming accessors):

class Whatever {
var name = "Tom"

Et voila. Or 'import scala.reflect._' to cut that down to simply '@BeanProperty'. Could be worse. Could use an IDE to generate source code. *Shudder*

Saturday, January 26, 2008

Scala Hopes And Fears

Main things I want out of Scala:

1. Closures.
2. No checked exceptions.

Main things that scare about Scala:

1. Bloat. One safe-looking line can generate a 30K class file. Helps explain how their own jars are so big.
2. Slow compiler. That they need an 'fsc' ('Fast Scala Compiler') sort of scares me.
3. Creative operator overloading (':::', '/:', '|-', binary '!', and so on since the possibilities are mostly endless).

Monday, January 21, 2008

Scala Pong 4K - Source Code Now

I was afraid to post my source code for Scala Pong 4K because I'm afraid it's not a good example of Scala programming, nor of 4K game programming, nor of programming in general. Learning a new language while staying under 4K with limited time for working on it provides less than ideal results. And I purposely avoided many Scala features because I was afraid of the weight it would add. (4K is really small.) For instance, I avoided arrays. Part of why I chose something as simple as pong (and Pong is really trademarked, so I guess that was a bad name choice). But it makes sense why people might want to see the source anyway. Also, finally, here is the Scala license which says I'm supposed to show their terms and copyright (though it would be nice if ProGuard could have stripped it all out, just to make it smaller).

All that out of the way, here's the source code which I kept all in one file "Game.scala". And it looks like it get visually chopped off on the right, so you might need to copy and paste it into an editor to see everything:

package sp4k

import java.awt._
import java.awt.event._
import javax.swing._

object Game {

// Don't extend a big class with an 'object'. That makes tons of static methods.

def main(args: Array[String]) {
SwingUtilities.invokeAndWait(new GamePanel)


class GamePanel extends JPanel with Runnable with ActionListener {

// Closure vars are smaller than member vars because no accessor methods are generated.
// Except that then it uses Scala's IntRef class, so a new dependency.
// So back to member vars.

var y1 = 200
var v1 = 0
var y2 = 200
var v2 = 0

var xb = 0
var yb = 0
var vx = 0
var vy = 0

def actionPerformed(e: ActionEvent) {
xb += vx
yb += vy
if (xb < -5 || xb > 605) {
} else if (xb > 573) {
if (yb > y2 - 40 && yb < y2 + 40) {
xb = 573
vx = -vx - 1
} else if (xb < 27) {
if (yb > y1 - 40 && yb < y1 + 40) {
xb = 27
vx = -vx + 1
if (yb > 375) {
yb = 375
vy = -vy
} else if (yb < 25) {
yb = 25
vy = -vy
y1 += v1
if (y1 < 60) {
y1 = 60
} else if (y1 > 340) {
y1 = 340
y2 += v2
if (y2 < 60) {
y2 = 60
} else if (y2 > 340) {
y2 = 340

def bar(g: Graphics2D, x1: Int, y: Int, x2: Int) {
g.setPaint(new GradientPaint(x1, 0, new Color(40, 40, 0), x2, 0, new Color(160, 160, 0)))
g.fillRect(java.lang.Math min(x1, x2), y - 40, java.lang.Math abs(x2 - x1), 80)

def initBall() {
xb = 300
yb = 200
vx = (if (java.lang.Math.random() < 0.5) -1 else 1) * ((10 * java.lang.Math.random()).asInstanceOf[Int] + 5)
vy = (if (java.lang.Math.random() < 0.5) -1 else 1) * 10

override def paint(graphics: Graphics) {
val g = graphics.asInstanceOf[Graphics2D]
g.setPaint(new Color(0, 0, 0))
g.fillRect(0, 0, 600, 400)
g.setPaint(new GradientPaint(0, 0, new Color(40, 40, 40), 0, 20, new Color(80, 80, 80)))
g.fillRect(0, 0, 600, 20)
g.setPaint(new GradientPaint(0, 380, new Color(80, 80, 80), 0, 400, new Color(40, 40, 40)))
g.fillRect(0, 380, 600, 20)
bar(g, 2, y1, 22)
bar(g, 598, y2, 578)
g.setPaint(new Color(255, 255, 255))
g.fillOval(xb - 5, yb - 5, 10, 10)

def run() {
setPreferredSize(new Dimension(600, 400))
addKeyListener(new KeyAdapter() {
override def keyPressed(e: KeyEvent) {
val code = e.getKeyCode()
if (code == KeyEvent.VK_UP) {
v2 = -5
} else if (code == KeyEvent.VK_DOWN) {
v2 = 5
} else if (code == KeyEvent.VK_W) {
v1 = -5
} else if (code == KeyEvent.VK_S) {
v1 = 5
override def keyReleased(e: KeyEvent) {
val code = e getKeyCode()
if (code == KeyEvent.VK_UP) {
if (v2 == -5) v2 = 0
} else if (code == KeyEvent.VK_DOWN) {
if (v2 == 5) v2 = 0
} else if (code == KeyEvent.VK_W) {
if (v1 == -5) v1 = 0
} else if (code == KeyEvent.VK_S) {
if (v1 == 5) v1 = 0
val frame = new JFrame("Scala Pong 4K - Use W/S and Up/Down")
frame.setLayout(new BorderLayout())
frame.add(this, BorderLayout.CENTER)
new Timer(50, this).start()


And I just used ProGuard from the GUI (remember I was just hacking this), but somewhere along the way, I asked it to spit out the configuration:

-injars bin
-injars lib/scala-library.jar
-outjars output

-libraryjars /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/classes.jar

-optimizationpasses 3

# Keep - Applications. Keep all application classes, along with their 'main'
# methods.
-keepclasseswithmembers public class sp4k.* {
public static void main(java.lang.String[]);

# Keep names - Native method names. Keep all native class/method names.
-keepclasseswithmembers,allowshrinking class * {
native ;

# Remove - System method calls. Remove all invocations of System
# methods without side effects whose return values are not used.
-assumenosideeffects public class java.lang.System {
public static long currentTimeMillis();

And it actually keeps on going with lots of method lists of that "assumenosideeffects" stuff. Hmm. So I'll stop listing it here.

Thursday, January 17, 2008

Extension Methods vs. Traits & Implicit Conversions (a Scala question)

I personally prefer the idea of extension methods (most obviously in C#) vs. Scala's use of both traits/mixins and implicit conversions to achieve the same result. Simplifying the argument for each side, I find this:
  • Extension methods: Simpler, less bloat, more predictable, extensible by third parties.
  • Mixins: More flexible (since classes can override). Designer control for uniformity, but less extensible. Bloats compiled code. More complicated than static extension methods.
  • Implicit conversions: Extensible but results in more complicated semantics. (I understand that C# also has implicit conversion, but it's not meant for this use case to my understanding.)
So, Scala folks, why should I prefer mixins/implicits (the Scala way), and how do you decide how much to mix in and how much to extend by implicits?

My own idea is something I call a "role" which is a combination of a runtime-erased type alias with optional extension methods. But I won't go in depth right now.

Wednesday, January 16, 2008

Scala Pong 4K

Well, I've decided to enter the Java 4K Game contest again, but I didn't use Java. Launch my simple 2-player pong game from here:
Scala Pong 4K
Player 1 uses W and S. Player 2 uses Up and Down. Not too exciting. It doesn't even keep score. But it's under 4K.

I've watched Scala off and on for years. Most recently, I've been toying with making a Scala-look-alike of my own, but far closer to Java. My two biggest problems with Scala have been these:
  1. Scala is very different from Java, even though you can code in Java style. I'm sometimes willing to learn new, but I've been afraid others wouldn't, and I wanted something with popular support. Also, it would be nice to be able to write Java libraries in "JavaNG".
  2. It has a 2.5 (plus or minus) MB runtime library. Some people couldn't care less, but I love small. To me, 2.5 MB isn't anywhere close to small. Oh, and then the compiler is 4 MB or so, if you want that.
Well, Scala can be made usable from Java (just as people sometimes write C libraries in C++ or other languages), people are picking it up despite my fears, and I made a 4K game in it. So, maybe it's time to start learning it better.

Side notes, don't say "object Game extends JPanel" since the singleton objects create classes that make a static method for every method in the class or super class. Or at least all visible methods.

Also, even private vars create accessor methods. Closure vars don't, but they bring in the class IntRef (for ints). And simple closures like "(a) => a + 1" create a class with a half dozen methods defined in them. Maybe pack200 and gzip would take care of that, but pack200/gzip doesn't count for the Java 4K Game contest. In real life, it could be useful, though.

Oh, and I definitely used ProGuard.