Tag Archives: java

Sequence, Selection, and Iteration: Scala

I’ve been picking up Scala recently, and in my studies I discovered that code such as the following:

class Foo {
  def bar(strings: String*): Seq[String] = {
    strings.map((s:String) => s.bazify())
  }
}

Can be shortened to the following:

class Foo {
  def bar(strings: String*) = strings.map(_.bazify())
}

The idea here being that since the function provides a data mutation on a set of variables, it becomes unnecessary to actually declare the variable each time through in the map. For those of you with a Perl background, this ought to look familiar. It’s called the ‘default variable’ $_ in Perl:

foreach (@strings) {
    print "$_\n";
}

I wonder if this cross pollination between languages was a direct inheritance from Perl or if it was just a natural best choice?

Interesting side note: While I almost universally appreciate C# over other languages, C# provides no such automatic variable wiring:

class Foo 
{
    IEnumerable<string> Bar(IEnumerable<string> strings)
    {
        return strings.Select((s) => Bazifier.Bazify(s));
    }
}

Really I think what this all boils down to is people trying to optimize around the common theme in structure programming, of “Sequence, Selection, and Iteration”. Uncle Bob put it thusly at RailsConf 2010:

Once you strip away the syntactic sugar, argues Uncle Bob, our programming languages essentially boil down to three things: sequence, selection and iteration, and every construct within those languages is some combination of them.

Android Development – Stack Careers

I’ve been itching to get into Android development for some time now. I must confess my ultimate goal is to create games for Android, but I actually can’t do that right now for some reasons I won’t explain here (contact me privately if you’d like to know more). That’s ok though, because creating games is a more complex undertaking on a platform you’re not familiar with. I needed something to get my feet wet, so I chose to create something that is simple but still useful.

‘The Lean Startup’, a book by Eric Ries about how to create successful products and services, proposes a method for accomplishing that goal:

  • Leverage validated learning
  • Scientific experimentation
  • Iterative product releases
  • Measuring progress
  • Gaining valuable customer feedback

To accomplish this, the book defines a ‘minimum viable product’ (MVP). An MVP is “a version of a new product which allows collection of the maximum amount of validated learning about customers with the least effort.”

The general idea is that you should develop something extremely simple in quick order, put it out there, and use it to gain feedback early and begin successive iterations to improve upon it. The advantages are numerous, but most notably is this: If you spend a lot of time scheming and planning out a project and developing without releasing it for a while, you may end up developing something that isn’t quite what your customers want at best, and at worst is something completely useless and opposite of what your customer actually wants.

androidSo I decided to build an Android app that is really simple with limited scope so that I could get something out there that provides value early and is open for feedback loops.

If you’re familiar with Stackoverflow (I really hope you are if you’re a software developer) you may be familiar with Careers 2.0. It’s a job search site tied in with the Stack Overflow crowd. Unlike traditional StackExchange sites which have full APIs, this site has only a limited RSS feed for job seekers (there is no API for employer or resume/CV data, which makes sense given that it’s a source of revenue for StackExchange). I chose to make an app that leverages that simple RSS feed data.

Here’s what parameters this simple RSS ‘API’ supports:

http://careers.stackoverflow.com/jobs/feed
    ?searchTerm=ruby&location=seattle&range=20&distanceUnits=Miles

Given that this is my first Android project, I knew I needed to limit my scope as much as possible because a non-trivial amount of time and effort would actually be just in learning the Android SDK and development process. So to further limit the scope of the effort, I decided I would only implement the skill and location search abilities.

I learned all about Android concepts like activities, intents, and the lifecycle of such things. I learned best practices for network communication, xml parsing, asynchronous work off of the UI thread, and more. I kept a set of bookmarks and guides that were helpful to me along the way, with the intention of writing a blog post series on basic Android 101 development in the future (keep your eyes out for this soon).

48 hours of effort later I have a first iteration suitable for release. Behold, ‘StackCareers’:

Stack Careers Stack Careers

It’s nothing amazing I suppose, but it does one job and does it well (those Unix guys in the days of yore were on to something). If you check it out, I’d love your feedback and suggestions.

Stack Careers app on Google Play

Google Play is a trademark of Google Inc.

The Stack Exchange and Stack Overflow names and logos are trademarks of Stack Exchange Inc.

 

 

Game Development: The Engine (Game Loop)

All computer games, when you boil them down to their simplest form, consist of a notion called the ‘game loop’. When you consider what a game really is you realize that it’s just a looping construct thats continuously receiving inputs and drawing outputs. The simplest loop looks like this:

  1. Calculate time elapsed since last loop.
  2. Accept inputs from the user(s).
  3. Decide what to do based upon those inputs, including updating entity positions.
  4. Draw everything to the screen.
  5. Repeat the loop.

I’ve been working on a game in my spare time (ok, so I’m ALWAYS working on a game in my spare time, shutup, let’s get back on topic). I spent a fair amount of time simplifying my game loop so that any developer could come along and immediately understand what it’s doing. As it turns out, this process of simplification is a great way to decouple things into a better design. Here’s what I’ve ended up with so far:

private boolean running;
private long lastLoopTimestamp;
private final Renderer renderer;
private final RateLimiter rateLimiter;

public Engine(Renderer renderer, RateLimiter rateLimiter) {
	this.renderer = renderer;
	this.rateLimiter = rateLimiter;
}

public void run() {
	
	this.running = true;

	while(running) {
		
		long elapsedTimeMillis = 
                  this.calculateLoopElapsedTime();

		this.processInput();
		this.think(elapsedTimeMillis);
		this.drawWorld();

		this.rateLimiter.blockAsNeeded(
                  System.currentTimeMillis());
	}
	
}

private long calculateLoopElapsedTime() {
	
	long now = System.currentTimeMillis();
	long elapsed = now - this.lastLoopTimestamp;
	this.lastLoopTimestamp = now;
	
	return elapsed;

}

The basic idea is that the Engine class here knows nothing about processing input, thinking about the logic, or rendering the world to the screen. It does however orchestrate all of those things (omitted the contents of the orchestration methods for brevity). The only thing the Engine cares about is knowing how to run, and how fast.

I think this is a pretty clean design. I’ll post more later about how I decoupled what’s being rendered to (ultimately a Canvas).

Order Matters: Java statics

Being a C# refugee, I haven’t quite picked up all the little nuances of Java. I’ve written a fair share of Java in my day but today I uncovered something new. Many of you may already know this, but in Java the order of statics matter.

To illustrate what I mean, let’s take a look at a snippet of C# code:

private static final IDictionary<string, object> foo = new Dictionary<string, object>() {{ "foo", bar }};
private static final object bar = new object();

In this example, after the class is initialized the contents of the ‘foo’ key’s value is bar.

Ok. Let’s take a look at a similar snippet in Java:

private static final Map<String, Object> foo = new HashMap<String, Object>() {{ put("foo", bar); }};
private static final Object bar = new Object();

Unlike C#, in Java the contents of ‘foo’ here is null.

The reason is that in Java, the order of initialization of static finals is the order in which they appear.

Bizarre.

Reduce Your Nesting

A key aspect of software development is making the code base maintainable. If the code is hard to read or understand, it corresponds to an increase in the time to wrap your head around what it’s doing. And since time is money, we can conclude that if code is hard to read/understand, there is a very real increase in cost required to maintain that software.

Nesting Is Your Enemy

Nesting occurs when you open up a new code block. This comes in various forms depending on the language, but is typically your branching, looping, and function definitions. For example, here’s a LOT of nesting:

public String getNameFromDatabase(string id) {

	if(id != null) {
		if(id.trim() != "") {
			Person person = this.database.load(id);
			if(person != null) {
				if(person.Name != null) {
					return person.Name;
				} else {
					return "";
				}
			}
		}
	}

	return "";

}

That’s awful. The human brain can only keep so many things in mind at a time, and usually the more contexts that you need to keep in your head at once, the more likely it is that you’ll get lost or make mistakes. Each level of nesting is another context that you’ve got to keep in your head.

What do you do? The solution is often to use early exits.

public String getNameFromDatabase(string id) {

	if(id == null) {
		return "";
	}

	if(id.trim() == "") {
		return "";
	}

	var person = this.database.load(id);
	if(person == null) {
		return "";
	}

	if(person.Name == null) {
		return "";
	}

	return person.Name;

}

Doing this improves readability and maintainability. You only have to keep at most 1 context in your head at a time. Once you’ve moved beyond that possibility, you can safely forget it and move on to the next one.

Another common (but less severe than the above), and one that junior developers make often is a scenario like this:

public boolean getFoo() {

	if(thingX == true && thingY == true) {
		return true;
	}

	return false;
}

Here’s how we can make it a little better:

public boolean getFoo() {

	if(thingX && thingY) {
		return true;
	}

	return false;
}

But it can still be even better. Here’s how:

public boolean getFoo() {
	return thingX && thingY;
}

It’s a contrived example of course, but illustrates the point. Now there’s no nesting, no unnecessary comparisons, and it’s faster to read and understand. As with all practices and approaches this needs to be considered on a case by case basis because there are certainly cases where a single line return statements actually hurts readability, especially as the branch clause grows larger.

Happy coding.

Languages and their Operators

Did you know that in JavaScript, if you do this:

'5' + 3

You will get 53, because it coerced the 3 into a string when it needed to perform a concatenation ‘+’ operation against the string ’5′.

But if you do this:

'5' - 3

You will get 2, because it coerced the string ’5′ into a number to perform subtraction against another number.

That’s what happens when you have a weakly typed language; It attempts to do the right thing based upon the operator and operands, and you’ve got to be careful to understand whats going on.

Another oddity… In Java:

Integer foo = 1000;
Integer bar = 1000;

foo = bar; // true
foo == bar; // false

The above happens because the first two operations are numeric equality checks, while the last is a reference equality check. ‘foo’ and ‘bar’ do represent numeric values, but are not the same reference.