Skip to content


Thinking in DSLs

In preparation for Ludum Dare, I’m writing a little side-scrolling shooter. I took some time to think of what sort of format I should use for storing a level. I thought of Tiled, which would work…but I found that I wanted to assign a function or path for each enemy ship, which would be cumbersome. Specifically, I’d have to write a parser for infix-notation math, including sine and friends most likely. And this wasn’t going to allow for any code reuse, annoyingly.

My next thought was to create a DSL in Boo. I sketched out what I wanted it to look like. Two minutes gave me something I was vaguely happy with. Only problem, I don’t know how to implement a DSL in Boo. I could learn, but I suspect it would take me more time than Ludum Dare gives me to implement one and integrate it with my project.

But why use Boo? I immediately thought: what prevents me from doing the same things in C#?

Well, nothing.

I rewrote my DSL example in plain C#. It would take maybe fifty lines of code to support that, whereas a DSL would take more like five times that, and a custom math parser on top of tiled would take even longer. Plus, this gives me fast access to all my code, so I can easily break out of the standard stuff if I need to.

But thinking in terms of a DSL gave me an API that is much nicer than anything I would otherwise have come up with.

Posted in Uncategorized.


Surgery!

I recently underwent some minor surgery — exposing some impacted teeth — and here’s a partial account of how my surgery went.

To start with, the orderly / nurse applied nitrous oxide via a nasal mask. The pressure was a tad low, and initially I was troubled by this. However, I very quickly became lethargic, and didn’t bother talking to anyone about it. It wasn’t a big deal, as I could breathe deeply to get enough air.

I had about two waves of mild euphoria. I began laughing over nothing. I noticed this, however, and managed to drive back the feeling and stop laughing very quickly.

I began to feel a tingling sensation spreading out from my face. It affected my right arm well before my left, and eventually spread to my feet. It disappeared in roughly the same order.

The nurse / doctor introduced an IV needle into my left arm. I was awake for this, and noticed the full effects as if I had not received nitrous oxide (assuming the needle was inserted skillfully). However, I cared less about it than I normally would, due, I believe, to the nitrous oxide.

My sense of time was severely distorted once the intravenous drip started, as was my short-term memory. I believe I was unconscious for most of the time, but this was not necessarily the case. I did not remember waking up during the procedure, though I remember several times feeling pain and indicating that I needed more anesthetic. I think this happened between three and five times. When this happened, I recall reacting strongly — it felt like I convulsed due to pain. I do not recall feeling pain significant enough for me to convulse, however.

For most of the procedure, I saw nothing. I had to make an effort to keep my eyes open, and with the lethargy supplied by the nitrous oxide (and probably the intravenous anesthetic as well), I wasn’t about to expend any effort. Except for communication.

During the initial phase, I made an effort to be alert and pay attention to my surroundings and what effects the drugs were having. I didn’t have anything in particular to concentrate on, so I couldn’t test to any reasonable degree how well I was thinking, except during conversation. I found myself at, I think, no more than half speed there. I had my sense of humor, but it took about four times as long to put together a statement as it should have. (Specifically, I was rate-limited by my brain, and that reduced my conversation speed. Normally I am not noticeably rate-limited by my brain.)

I found myself wondering whether anesthetics perhaps do not dull pain but instead cause you to forget about it afterward, and in the meantime prevent you from moving. There are ways to tell, I’m certain — EEG studies and all — and I assume these have been done. I didn’t manage to think nearly that far.

I’m kind of scared that this impaired my thinking to such a degree. No more than going 48 hours without sleep would have done, I’m guessing, but still.

Posted in Uncategorized.


Spring is the devil

Spring is evil.

Older versions of Spring required you to write gobs of XML to do anything.

Newer versions of Spring merely make you wish for those days.

I had a relatively simple setup:

@Component
public class Processor {
    @Autowired
    public Processor(@Qualifier("foo") List<SubProcessor> subprocessors) {}
}

I added a configuration class:

@Configuration
public class Config {
    @Bean("foo")
    public List<SubProcessor> subprocessors() { ... }
}

Somehow, Spring managed to suss out the generic parameters for Processor’s constructor arguments, then went off looking for the implementations directly. If it had managed to find all the implementations, I’d have been impressed and relatively happy. (I wanted the subprocessors in a particular order, but that’s a minor thing.)

But no. Spring died at that point. It couldn’t find any implementations, it said. I had five.

I ended up getting around its stupidity eventually, though: I changed the types everywhere to Object and Spring shut up.

Seriously, I didn’t have anywhere near this much trouble with .NET. What’s going wrong with Java? I can’t even use Spring as a service locator. I’d get better utility out of a hash table.

Posted in Uncategorized.


Implementing a JUnit Test Runner

Today, we’re going to look into implementing a custom test runner for junit 4. The features we’re targeting are:

  • Feature parity with the standard runner (expected exceptions, @Before/@After, @BeforeClass/@AfterClass)
  • Per-test parameterization (with appropriate output formatting)
  • Expected exceptions (like in the standard runner)
  • Performance enforcement (stop and fail tests after N milliseconds)

So let’s open up our favorite editor and start hacking.

Basic structure

Our test runner must inherit from the abstract class org.junit.runner.Runner, which provides some restrictions, and requires a constructor that takes one argument of type Class<?>. So let’s add that:

public class BeefyRunner extends Runner {
    private final Class<?> clazz;
    public BeefyRunner(Class<?> clazz) {
        this.clazz = clazz;
    }
   
    @Override
    public Description getDescription() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void run(RunNotifier rn) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

Okay, so now we have two interesting points of contact with the outside world: getDescription() and run().

JUnit’s internals and our model

getDescription() returns an instance of Description, which is a tree-like structure holding test and test suite information. This is used for a few purposes, among them counting the number of tests in this test fixture. If you botch this, you’ll end up with the HTML output at some point saying that your user has 15 failed tests out of 4, or something like that. Not exactly desirable, but if you’re just doing this for internal use, it might be acceptable.

The main problem with getDescription() is that it uses this Description class. Description has exactly one constructor, and that is private. So you can’t modify its behavior, without doing some low-level and ugly JVM contortions à la JMock. But maybe its behavior by default is good enough?

…yes, as long as we play fast and loose with the API. There are a few issues, so it’d be nicer to have our own properties on Description, like maxElapsedMilliseconds and expectedException and so forth. This would, however, constrain our external API — we’d have to make all our annotations method-level, disallow overloading test names, and so forth. So while we can get our results using just the standard Description class, we’ll have a lot fewer headaches if we have our own internal model and only serialize to Description at the last second.

So here’s a quick hack of our internal model, probably good enough to support all the features we’re after:

public class Test {
    public Class<?> classUnderTest;
    public Method method;
    public Class<?> expectedException;
    public long maxElapsedMilliseconds;
    public Object[] parameters;
    private Description description;
   
    public Description getDescription() { ... }
}

We don’t know for certain whether there will be any object identity issues in the rest of junit with instances of Description, but it’s safer to cache our instance just in case. As for the rest, we just record what we need in order to run this one test instance.

Note what we’re saying when we say ‘test instance’. We’ll end up with a separate instance of Test for every combination of parameters. So if you have a test with a few hundred combinations of parameters, we’ll create a few hundred instances of this. What will this do to our output? It’ll be pretty unreadable, I should think. Let’s split this out so that the final output will aggregate by test method, and you can drill down into a test method to get the individual parameters.

public class TestMethod {
    public Class<?> classUnderTest;
    public Method method;
    public Class<?> expectedException;
    public long maxElapsedMilliseconds;
    public List<Test> tests = new ArrayList<Test>();
   
    public Description getDescription() { ... }
}

public class Test {
    public Object[] parameters;
    public TestMethod parent;
    private Description description;
   
    public Description getDescription() { ... }
}

Okay, we’ve got our model; we only have three concerns now: serializing this to Description, creating the model in the first place, and executing our tests. Let’s decide on our external API and then worry about creating our model.

External API: Parameterized Tests

Our primary concern is parameterized tests. We want to be able to specify as much as possible on the method level and on the parameter level, for maximum flexibility, ease of use, and ease of reuse. Also, we want shortcuts for the cases we can handle easily. Lastly, since we’re using Java and providing metadata, we’re using annotations to assign values.

This deserves a rehashing of the limitations of Java’s annotations. You can’t store values of type Object in an annotation. You can’t store arrays of arrays. You’re limited to compile-time constants (integer types, byte, and String) and arrays thereof.

This means we can’t use the same annotation field for strings and doubles. We can use the same annotation with different fields, or different annotations. It would be slightly prettier to use different annotations — then you could use the value() property for each. But this would require using more types and more imports to accomplish the same tasks. Let’s use the same annotation — @Values — and multiple fields. If you put this annotation on a test with one parameter, we’ll pretend that you put it on the parameter. If your test has multiple parameters, we’ll emit an error.

Now that we know what we want end users to see, and we have a good idea of what our internal model will be, let’s call it a day and come back to this in the morning.

Posted in Uncategorized.


Java sucks, that’s all

I keep getting annoyed at these Java libraries. In some cases, I can do better (and I have). In a bunch of other cases, though, Java just sucks.

My most recent complaint? Annotations are great! But they can only have values that are primitives, or String, or one-dimensional arrays of primitives or String.

So you can’t have an annotation with a property that might be a string or a primitive, because you need to store that as Object. And that’s not allowed.

Why is this so important to me? Well, junit has a concept of parameterized tests. So does nunit (a roughly similar library for C#). But junit does it horribly. In junit, you have one set of parameters that apply to your entire test suite. You annotate the data generation method, not your tests:

@RunWith(Parameterized.class)
public class MyTests {
    @Parameters
    public Collection<Object[]> makeData() {
        return Arrays.asList(new Object[][] {
            { "fish", 17 },
            { "sheep", 12 }
        });
    }

    private String animal;
    private int count;

    public MyTests(String animal, int count) {
        this.animal = animal;
        this.count = count;
    }

    @Test
    public void testCase() { ... }
}

Nunit, on the other hand, provides attributes where you put the data in directly:

public class MyTests
{
    [Test]
    [Sequential]
    public void TestCase([Values("fish", "sheep")] string animal,
                 [Values(17, 12)] int count) { ... }
}

See the difference there? One way is so complicated, I’d refactor away from it. The other is just plain readable.

And the junit version is near optimal for Java’s capabilities.

These limitations don’t seem insurmountable under the JVM. Groovy, for instance, allows you to have two-dimensional arrays as annotation members, whereas Java does not. But there seems to be very little pressure for improvement in Java.

Posted in Uncategorized.


Video Film Declaration Forms

It takes significant effort to defend freedom against security and patriotism. In the case of elected officials, you need to track individual actions and make it clear which actions you support and which you do not. This requires being in frequent contact with a senator or two, a governor, and a handful of representatives.

What happens when a bureaucratic institution goes awry?

The Department of Homeland Security has started requiring ‘Video Film Declaration’ forms for any imported film.

Security effects

Who does this move benefit? Is it a valid security measure?

No. For it to be a security measure, there needs to be a threat that it reduces. Organized terrorism isn’t a threat. Oh, sure, there have been a handful of arrests — genuinely innocent people, or victims of agents provocateurs. And a couple of idiots have tried to blow themselves up in ill-thought-out attempts that would barely succeed at suicide, let alone any appreciable level of terrorism.

(As an aside, I wonder whether it would be effective as terrorism to have agents blow themselves up, with little damage to others, making it look like the explosives had been planted in secret. But I doubt such a plot could remain secret for long enough to make that successful.)

What’s the most successful terrorist act since the World Trade Center incident? A lone man in Oslo, deciding, without outside assistance, that certain people needed to die.

What about in the United States, before the Word Trade Center incident? Well, that would be the Oklahoma City bombing, which was also a lone man deciding that others needed to die.

These things are more likely to stop by providing more access to psychiatric care than by censoring material.

Political terrorism has been a lasting threat in certain circumstances. Hamas, Hezbollah, the Tamil Tigers, and the Irish Republican Army have caused a huge amount of strife. The United States is not seeing anything similar domestically. If we were, I’d have to consider whether censorship might help in those circumstances, but I think it’s likely a bad idea to have the ostensible good guys suppressing truth that only criminals and terrorists can provide.

Why censorship?

So, we don’t seem to be getting any security from this loss of freedom. Need we consider any other benefits that censorship might give?

Well, presumably, if there were good arguments in favor of censorship, those who are censoring materials would already be providing them. So I could claim that it is simply unnecessary for me to refute arguments that have not been provided; these are clearly outside the scope of consideration for the Department of Homeland Security. And there’s some merit to that attitude: it’s unlikely that the DHS would optimize censorship for a less spurious goal if they are claiming its purpose is security.

But it’s a better form of argument, if you’re interested in finding truth, to fix your opponent’s arguments for them, and refute what you are left with.

Is there any knowledge that is uncontroversially dangerous, that we would benefit from restricting access to? Some knowledge that harms more than it helps? Or something that merely requires significant caution to handle safely?

Well, yes. Knowledge of how to create an artificial intelligence could be extremely dangerous, if it were exercised in the absence of careful and thorough work on the topic of Friendly AI. Knowledge of how to create an atomic bomb or an airborne ebola could be quite dangerous, especially since the implementation will get easier in time. Any subject about which people are strongly inclined to become severely dogmatic is dangerous, whether it be a political theory or a religion. (And I’ve heard a number of stories about people deconverting from Christianity as a result of having read the Bible. It seems safer, if you’re not stamping out the religion, to allow people to access its holy texts.)

Censorship in science and artificial intelligence would reduce a wide variety of means to attack others, and reducing religiosity would reduce one strong motivation for terrorism. Censorship in these areas is at least controversial, albeit not an obviously good idea. But the DHS is not redacting the Journal of Clinical Microbiology, or banning sales of the Bible.

Dangerous materials?

The DHS is censoring materials that suggest being violent toward anyone in the United States. I can ask whether there is a reason for US citizens to view such materials, but that implies there is by default no right for me to see anything, unless it has been proven safe already.

Are these materials actually dangerous? Well, they’ve been available for years, with very little effect. If we treat the period in which it has been readily practical to distribute videos promoting terrorism and terrorist organizations in the US as a trial period, these videos have incited violence pretty much never.

In the US, you can visit al Jazeera’s English website and see a number of announcements from terrorist groups. Al Jazeera occasionally runs video submitted by terrorist organizations. How many people have resorted to violence due to these? If it had happened, would al Jazeera still be operating?

Obscenity and Immorality

Let’s look at the other provisions in the video declaration form. Inciting treason is already a criminal offense, so there’s not much point worrying about it in this form. Obscene and immoral matter, though, is a different knob of wax.

Obscenity laws are a way of imposing the scruples of the largest or most powerful portion of a society on members of that society who would otherwise be free to do what they want in the privacy of their own home. They typically target sexual material or mannerisms of speech (which is to say, swearing).

What can be covered by immorality and not obscenity, but is not already illegal?

If some activity were universally or near-universally condemned, it would presumably already be illegal. Immorality only has room where the enforcers have a different morality than their society. It is a way to sneak in views that are not sufficiently mainstream to survive a fair vote.

Do you think something is immoral and should be banned? Fine — push a bill through Congress. I’ll happily debate you there. But if you instead put an undefined ‘immoral’ term in a video declaration form, with a strong assumption that anything that ends up being called immoral can’t be imported…well, you’re surrendering the definition of law, and the enforcement of your morality, to unknown, unchecked employees of the Department of Homeland Security.

Regardless of your specific morality, that’s just not a good idea.

Posted in Uncategorized.


Thinking from the future

If I can predict what I’ll feel in the future, I may as well think it now.

I’ve read this story before. I’ve seen the protagonist go down this road and learn a valuable life lesson. I know what that lesson is. I’ll just learn it without slogging through the Forbidden Forest with orcs on my tail.

The other lesson I’ve learned is that things will keep going like they have been going unless someone changes something, usually with deliberate effort.

I’ve been apart from the D community for about a year now. Before that, I had maybe six months on, which was preceded by another non-D spell. This has happened through about four cycles so far. It’s getting old.

I can look for something to change about this. And “just stick with it this time” isn’t an option. It’s a goal. What I would need to do is identify some motivation I have that I can feed and increase, or remove some obstacle that’s been causing me to abandon D periodically, and use that to make it easier to stay.

Of course, that takes work — maybe a lot of it. Maybe I should just say goodbye and never look back. Even though that saddens me at times.

But switching back and forth at this point is useless, unless I have some specific, bounded goal I can achieve, will make me less happy than I could otherwise be. It’s inconsistent, and inconsistencies generally produce guaranteed suboptimality.

I don’t know what I’m going to decide. But I’ll think about it.

Posted in Uncategorized.


Ubuntu’s Unity Desktop

I recently upgraded to Ubuntu 11.04, despite the hullabaloo about Unity Desktop. I initially thought I’d be quite annoyed with it.

I’m used to dealing with full-screen everything. Every window is maximized. Every panel autohides. Simple, clean. From the mockups and screenshots, I concluded that the application panel was always visible and taking up screen space. I also disliked the fact that the top panel couldn’t autohide.

My concerns disappeared pretty much immediately. I rarely see title bars for windows — instead of a five-pixel stub for a hidden panel and a 24-pixel title bar, I just have the 24-pixel omnibar. And it handles the main application menu, too! Overall savings of about 30 pixels for most applications. Chrome’s the only thing to suffer, since it usually doesn’t come with a separate titlebar or menu bar.

I use GNOME-Do, and it works just fine with it, obviating the launcher.

I do have some complaints about Unity, but that’s mainly because it’s new software. Sometimes the application bar doesn’t disappear when switching workspaces to one with a maximized window, for example. But these are pretty minor, and they’ll go away in time.

Posted in Uncategorized.


What makes a Dark Lord?

Fantasy novels usually feature a Dark Lord. But what is a Dark Lord? What do they do?

Minions

Minions are an inherently Dark Lordish thing to have. A wise ruler might have people whom he can order around, but they’re expected to think for themselves. A Minion, however, should never think for itself. It’s a faceless automaton serving its master’s will. Obedience rather than loyalty is demanded.

Sauron had his orcs and goblins, which are now beyond trite and have become a staple of the genre. Even in human-only fics, there’s bound to be a Legion of Terror, a bunch of prison guards in gimp masks, or something of the sort.

Dark Lieutenants

Nazgul, the Forsaken…these aren’t nearly as common as minions, since having a dark lieutenant

Holing up

A Hero goes out on his own (and it’s almost always his, not her) to have an adventure. A Dark Lord sits in a castle and has underlings go out to have an adventure.

This is mainly a matter of practicality for the story and for administrative purposes. It’s hard to oversee a nation of any decent size from a field outpost. Also, a Dark Lord who sallies forth will pursue his most relevant interests, which is, with high probability, the Hero. This results in a Hero that kills the Dark Lord near the end of chapter 3 or gets squished like a bug near the beginning of that same chapter.

Inscrutable motives

The only motive that Sauron seems to have is getting his ring back. Other than that, he almost seems content to sit back in Mordor. Give Sauron the Ring, and within a decade he’ll be belching Rohorrim mead in a hall with his Dark Lieutenants and Gondorian ambassadors and fondling the serving orcs. (This is lampooned in Harry Potter and the Methods of Rationality, with a drug called Bahl’s Stupefaction.)

Lairs

Maybe they just want to make mutalisks. Maybe the décor calls for craggy mountains. Maybe the in-house volcano provides a convenient source of geothermal energy.

Whatever the case, a Dark Lord has cool digs, and the motif is always black and spiky.


Most of these are trappings of a Dark Lord. What’s the bare minimum?

Followers

Maybe minions, maybe Dark Lieutenants, but there needs to be something to make this a Dark Lord rather than a Dark Just This Guy.

Disregard for popular moral judgments

A Dark Lord must be Dark. This doesn’t mean evil, necessarily. It doesn’t mean that I have a different moral code.

You and I might agree that it’s morally correct to save people’s lives. You might be unwilling to kill terminally ill people in order to harvest their organs for people who might thereby live for years. I might make the opposite choice.

Posted in Uncategorized.


The trouble with C#

If I’m bashing Spring, I should have some idea of what I want from an IoC container. And I know exactly what: Castle Windsor.

This is a common theme. I encounter a problem. I encounter a Java library to solve it. The Java library solves the problem but doesn’t allow any customization; or it solves it in a way that isn’t useful for me.

When I’m working in C#, I rarely have that problem. This is quite annoying. I have to think about the code I actually intended to write. I’m not used to this. A couple years ago, I tried writing a little game…and ended up writing a unit testing library, a dependency injection container, an event broker, a mock objects library, and eventually started on a compiler.

So now, I’m considering applying to a job that requires a C# code sample, and I haven’t managed to write anything worth sending since I left my old job. This is a bit of an issue.

Posted in Uncategorized.