Friday, October 8, 2010

Java Workshop

About three weeks ago, I floated the idea of a Java Workshop to my CS222 class, and enough liked the idea for me to pursue it. Last Tuesday, I gave a two-hour evening workshop on the fundamentals of Java. Here is a synopsis of the major points we covered. The point of this post is primarily to refresh the ideas among those who attended, but others may still be interested to see what I consider as the Java fundamentals. It may be worth noting that this was explicitly about the language and environment of Java, not best practices or even software development.


  • "Java" refers to a language, an API, and a VM. It's good to be aware of this overloading of the word so that you can see how the whole system fits together, especially with the proliferation of languages that run on the JVM.
  • Java has primitive types and reference types. Primitive types are just boxes that hold values, but reference types are for objects, the fundamental building blocks of OO systems.
  • All of the primitive types have similarly-named reference types. For example, there's int and there's Integer. The difference between these reveals an important insight into object-oriented software design. Whereas an int variable is just a box that holds a value, an Integer instance is a representation of the idea of a number. Consider the following code.
    int x = 5;
    Integer y = 5;
    
    Here, x is just a box that holds an integer, and so we can say x=7, and that means we're putting a different value in the box. On the other hand, y is five. We cannot say y.setValue(7) any more than we can assert that 5=7 in mathematics.
  • It's good to recognize that y=5 is not free: it's using autoboxing to convert an int primitive into an instance of Integer. While it's true that premature optimization is the root of all evil, you shouldn't write code that creates unnecessary objects either.
  • It is critical that a Java developer builds a functionally-correct mental model of
    classes, objects, static, methods, and fields. A blog post is not the right way to help you, dear reader, to identify the problems in your own mental model. The good news is that my services are for hire. ;)
  • There are four access control modifiers that you should know so that you can read code: public, private, protected, and package-protected (which has no keyword). However, you should really only ever use public and private, so you just saved half your allocated brainspace on this topic.
  • To understand classes, abstract classes, and interfaces, I used an example like the following.
    public interface InningListener() {
      public void strikeOut();
      public void walk();
      public void balk();
      public void beaned();
      public void hit();
    }
    
    public abstract class AbstractInningListener implements InningListener {
      public void strikeOut() {}
      public void walk() {}
      public void balk() {}
      public void beaned() {}
      public void hit() {}
    }
    
    public class Inning {
      private final List<InningListener> listeners = new ArrayList<InningListener>();
      private int strikes = 0;
      public void addInningListener(InningListener listener) {
        listeners.add(listener);
      }
      public void strike() {
        strikes++;
        if (strikes==3) {
          fireStrikeOutEvent();
          strikes=0;
        }
      }
      private void fireStrikeOutEvent() {
        for (InningListener listener : listeners) {
          listener.strikeOut();
        }
      }
    }
    
    public class Demo {
      public static void main(String[] args) {
        Inning inning = new Inning();
        inning.addInningListener(new AbstractInningListener() {
          public void strikeOut(){
            System.out.println("Strike out!");
          }
        });
        for (int i=0; i<3; i++)
          inning.strike();
      }
    }
    
    A few highlights of this example:
    • This is an example of the Observer design pattern.
    • The abstract class provides default empty implementations of the methods in the interface so that implementors—like the one in Demo—can provide implementations of only those methods that they care about. This keeps the code from getting cluttered up with no-op implementations.
    • This pattern can be found throughout java.awt.event. I tend to do something a little more idiosyncratic involving inner interfaces and inner classes, but that's for another day.

  • If you're doing I/O, it's good to know that the InputStream/OutputStream family of classes is for byte-level I/O, Reader/Writer family is for character-encoded content, and the nio libraries are for blazing fast access to hardware buffers, and so can be ignored until you need it. To me, the critical classes to know are BufferedReader and PrintWriter. BufferedReader has the amazingly-useful readLine method, allowing line-by-line access to a stream, and a PrintWriter behaves exactly like System.out.



  • The classloader trick will load a resource from the classpath whether you are running in Eclipse, from a command-line, from an executable jar, in a servlet, or on Java WebStart:
    Thread.currentThread().getContextClassLoader().getResourceAsStream("whatever.png");
    



  • Here's a slapdash tour of the collections API:
    • List<T> defines a sequence. There are two useful implementations,
      LinkedList<T> and ArrayList<T>, which come with the usual caveats implied by their names.
    • Set<T> defines a set, in the discrete mathematics sense.
      The two common implementations are TreeSet<T> and HashSet<T>, but you should use the latter because you're always providing a useful hashCode method in all of your Java classes—or else you're doing it wrong.
    • Map<K,V> defines a dictionary, an associative array, a lookup table—choose your favorite mental model. Again, we have TreeMap<K,V> and HashMap<K,V>, and you should use the latter and override hashCode in all of your classes.
    • Finally, use guava.



I think that's everything we covered, except for some of the more specific questions. I hope this post is helpful to someone looking for a birds-eye view of Java. As I mentioned at the workshop, when I started using Java in 1998, there was not much to learn and there was basically one place to go to get started. Now, I imagine that novices can be easily overwhelmed by the immensity of just the standard libraries. By the way, the good news here is that the best place to go for an introduction to Java—as long as you aleady know something about programming— is still The Java Tutorials.

At what point intervention?

I find myself very nervous about this afternoon's 3:15 Studio meeting. I have a feeling that some key PBIs are going to be missing, but there's a sense in which that is fixed through Scrum by carrying them over with high priority to the next Sprint. My deeper concern is that the developers are losing steam, in large part because they have been myopically looking at the PBIs rather than keeping one eye on future needs. Alistair Cockburn put it best when he described software development as a cooperative game with two goals: first, meeting the needs of the current iteration; second, setting up for the next one. In looking over students' shoulders, eavesdropping in discussions, and directly working with them, I see the students expending all their effort on the first goal and almost none on the second goal.

There are various things I can do to help as a Product Owner who is also the lead software architect. I could invest time in developing a robust technical design document that describes the pieces of the architecture that are not yet in place. I could run through the product backlog and come up with reasonable estimations for every PBI so that I can make a product burndown chart to show studio velocity.

The key dilemma I keep coming back to, however, is this: at what point to I just sit down and write some code? The game is already based on an entity architecture kernel that I provided, and I am one of the principle stakeholders in the success of the project. I see some of the students seriously struggling with code that, to me, is at most a two-hour job. There is value in having students struggle through these problems so that they can develop problem-solving skills and learn to deal with frustration. On the other hand, one of the best ways to learn is by working with someone more talented. At what point is it better for me to just show them how to write it rather than trying to coax it out of them? For that matter, how do I know when it is better for the project for me to add modules or refactor modules students have already created? These questions make me nervous, and I think it's because there's no "undo" button for teaching.

In my mind, I keep coming back to the Confluence project, where I worked right alongside Carrie and Josh to build that system, and it was good: the system worked and they learned. For that project, I had release time to develop it, and both students received independent study credits, and I don't have any doubt that we did the right thing. 3:15 Studio is formed out of a "regular" class, with an order of magnitude more students. Does that mean it is any different?

Wednesday, October 6, 2010

Civilization, War, and Learning

Those of you who follow my Facebook posts have probably figured out by now that I broke down and bought Civilization V. It's the latest by Sid Meier, whose Pirates! is one of the best games I have ever played, but that's a post for another time. For those who are not familiar with the Civilization series, they are turn-based strategy games that follow the development of civilization from ancient times up to the modern age. Although they are a hallmark of PC turn-based strategy gaming---and I love turn-based strategy games---I have never played any games in the series until now.

Last night, I finished my first game of Civ V. I used the default settings, which were for beginning players, and I happened to be playing as the British Empire. My civilization developed much faster than the opposition, probably more because of the low difficulty setting than any clever strategy of mine. There are multiple ways to win the game peacefully: scientific leadership, diplomacy, and cultural development. Because my civilization was advancing so much more rapidly than my opponents, I took the classic gamer's optimization approach: military victory. After all, why wait for my inevitable cultural victory when I can just send my superior army to crush the opposition and annex their land to mine, thereby winning the game?

As my army crushed the opposition, the in-game music turned from pleasantly ignorable and ambient into rather dark and sad compositions. Every time I declared war and sent my troops over their borders, the music set the mood not of a glorious conquest, but of grief and despair. As my navy bombarded coastal cities, they caught fire, and I could hear the screams of civilians. As I destroyed the last city of the Indian empire, Gandhi appeared on the screen and congratulated me on destroying a kind and peaceful people. As I defeated my last opponent, I received the end-game screen, an image of WWI-era soldiers marching over a barren land, and again the music set a somber tone.

Here is a great example of the power of learning in games, following the themes in Koster's Theory of Fun. The game is clearly designed to be fun, and there is a sense in which my military victory was enjoyable, but even more than that, it made me think. The formal elements of the game (the rules) combined elegantly with the dramatic elements (the music and story) to produce a unique experience. Most games I play follow a single hero who single-handedly destroys the vanilla-evil opposition, and there was much rejoicing. In Civ, I actually felt guilty for destroying these other civilizations just so that I could "win."

I hope to be able to draw on this in my current efforts with the Morgan's Raid game (as well as the potential Underground Railroad project), where there is a similar lesson we wish to subtly teach: although the player takes the role of John Hunt Morgan, he is neither inherently a hero nor a villain, but the Civil War was undeniably an ugly and painful thing. We have an interesting design constraint in the game as well. Since it is designed for 4th grade students to play in schools, it's likely that it will be played without music, in crowded labs or during free time. It was the somber music of Civ that moved me the most; I can only wonder what would have happened if I had been playing without my speakers on, since I can never go back to my first experience.

Wednesday, September 29, 2010

Demon JHM: Final boss of Morgan's Raid

I stopped by the lab to see if any of the 3:15 Studio team members needed anything, and the room was empty except for this.

I think I have to go rewrite the design document now.

Sunday, September 26, 2010

Contemplating creative inquiry: a call for partners

One of the unique features of Ball State is the Virginia Ball Center for Creative Inquiry, known locally as "the VBC." The center supports seminars that: explore the connections among the arts, humanities, sciences, and technology; create a product to illustrate the interdisciplinary study; and engage the community in a public forum. The faculty and students who spend a semester at the VBC are completely committed to the project: the faculty member is relieved of all other teaching and university service responsibilities, and the students earn full-time credit for their participation. The seminars themselves are held off the main body of campus, in the beautiful and inspiring Kitselman Center.

I am considering applying to run a seminar in the next academic year, having talked the possibilities over with a few key people, including my department chair and the director of the center. A VBC seminar would be the natural evolution of my work on game design and development. All of my previous projects share a common shortcoming, namely that they have been shoehorned into 3-credit experiences under conventional university scheduling constraints. A VBC seminar is an opportunity to collaborate with students in a legitimate studio environment. In practical terms, we would really be an indie game studio.

I would like to use the seminar to create a game, created by following principles of agile software development. The two missing specifics are the community partners and the game itself. One compelling idea is to build upon my experience with the Morgan's Raid project to make another explicitly educational game for school-age children, potentially on the Underground Railroad. I already have collaborators and potential community partners for such a project, and creating software for K-12 has a high impact factor. Another option is to make something subversively educational. I agree with Raph Koster's theory that fun and learning are intrinsically tied, and it would be a great design exercise to make something superficially "simply fun" that, in fact, teaches 21st-century values.

This post is both a reflection and a call for partners. If you are part of an organization that has a compelling story to tell, or are in the games industry and want to explore strategic partnerships on community-focused developments, or you have a crazy idea that just might work, let me know. You can leave comments here of course, or you can email me (firstname.lastname at gmail). VBC application materials are due at the end of the calendar year, so there's time to bounce ideas around.

Thanks for reading. By the way, if you're a BSU student who will be around next year, think about participating and spread the word. I want the cream of the multidisciplinary crop!

Wednesday, September 22, 2010

Two Sprints with 3:15 Studio

We are now two sprints into the CS315 game programming class. I have not updated this blog as often as I intended, but I suppose that means I've been busy, which may even imply that I've been productive. The advantage of being healthy in a house full of sick people is that everyone else is sleeping, and I still have the energy to do some writing.

I am a little surprised to see I haven't actually written much about this class since before the semester started. We are in the middle of the fifth week of the semester, but let me start by explaining what happened in the first week.

One week of training

The students were introduced to the "course" by being told that it was not a conventional course at all. Rather, the students were in an orientation week for their positions working for 3:15 Studio, and their project was the implementation of a game based on Morgan's Raid. They were told that the orientation and training would last one week, and we'd move from there right into production. I was also explicit in saying that they were expected to work ten hours per week. This is something I've started telling all of my classes, based on the arithmetic that 40 hours per week is "full time" and 12 credit hours is "full time." With this class, though, it was not a recommendation to allocate that much time but a statement that this was the amount of work required. That is, from day one, this was presented as a situated learning experience, in which the students comprise one studio under my direction.

The rest of the first meeting consisted of introducing the game design, the stakeholders, and the historical context. The students were given a quick introduction to Mercurial and the MercurialEclipse plugin, and they were shown how to upload an image to a shared repository. Their first assignment, then, was to upload a portrait to a shared repository to help us get to know each others' names.

The second day (Wednesday) was a breakneck introduction to test-driven development, entity system architectures, pair programming, and Scrum. This was done in a lecture-oriented style, primarily as a means to maximize throughput. It was expected — and experience has shown — that not much of this was retained by the students, but it did help them build a mental framework of what level of rigor was expected. This resulted in the studio size decreasing from thirty to twenty-five, which I see as a positive step: students who were not willing to make the investment elected to choose another course. (It is an unfortunate phenomenon that, even at the 300-level, students mistake "Game programming" as a light and fun elective, when in fact, it is grueling and fun.)

The third and final meeting of the week (Friday) was mostly devoted to team formation and task allocation. Based on the number of registered students, I directed them to form four teams. The teams were formed primarily based on pre-existing social networks, at least according to my informal observations. At one point, there were three complete teams formed, but a headcount revealed that two students had not actually been incorporated into a team. Two of the teams shed members to join these two to be the final team, whom I will reference later as "that team I mentioned before."

For the first sprint, I wanted to give the students an "easy win" in order to build morale, and I wanted to ease them into Scrum, entity systems, and TDD. Based on this motivation, I set up a product backlog consisting of user stories that were all at the task level. That is, I had pre-sliced problems into tasks achievable by pairs of students. These were, in a sense, not proper product backlog items, since many had to do with software architecture and not anything that has value to the stakeholders, but to me this was a reasonable accommodation in my circumstances.


Sprint One: Two weeks

The first sprint was a success. All of the teams delivered their product backlog items (PBIs) modulo some miscommunication and minor revisions. Most of the tasks were fairly straightforward implementation tasks, the sort that would take me under an hour, but that I expected the students to take much longer since the learning curve was so steep. It's worth mentioning that the team I mentioned before happened to pick up the most difficult of these tasks. Given that the team was made up of a hodgepodge of students as opposed to a motivated group of friends, I was concerned as to how they would handle it, but this team came together in an exemplary way to solve their problems. (More on that in a later blog post, perhaps.)

There was a case around the middle of the sprint where some students broke the build — did I mention we're also using CruiseControl for continuous integration? I took the opportunity to shame them on the studio mailing list, and in that message, reminded everyone to be careful about what they code they push. I emailed these students privately and thanked them for being good sports about being the first to break the build, dooming them to be my sacrificial lambs for the good of the team. I knew these guys, and I knew they could take it. Good job, men. Since then, the only real "breaking" of the build has dealt with images being too large and non-portable Java code that works on only some operating systems.

The production portion of the sprint ended on a Thursday, and the next day we held a combined Sprint Review and Sprint Retrospective. This is really a place where the University's scheduling system is a challenge, since we had to do both in the space of 50 minutes. We could have used more time, but we made the most of the time we had. The Sprint Review revealed one of the major weaknesses of the product backlog design: because the PBIs were primarily architectural, I was the only one of the three Product Owners who could appreciate that progress had been made. The programmers and I were delighted just to get a window open with anything in it, but I think my collaborators expected a little bit more. I assured them that this was a necessary step to get the students up to speed.

The Sprint Review was amazing. We had two timeboxes: ten minutes to discuss what went well, and ten minutes to discuss what could be improved. We could have kept on going with our list of successes, and I could feel the excitement and morale in the air. As for the things to improve, many were very simple to address. We left the meeting on a high — helped by Concannon's chocolate chip cookies. One of the important tips I got from Clinton Keith's book was to take the time to celebrate at the end of a sprint, but with a mix of under- and over-age students, cookies seemed like the safest bet.

After this meeting, I met with my co-PI and we reprioritized the product backlog. Moving into the next sprint, we consciously revised the PBI format to deal strictly with those things that add value to the product owners.

These are the burndown charts for the four teams for Sprint 1.







I used Scrum a few semesters ago in game programming, and since then I've studied it more and been applying it with more care. However, my recollection is that it took us several sprints to get anything approaching the level of steadiness shown in some of these burndown charts. Some of the skips are interesting, since they show places where teams thought they had finished their tasks, then found that someone else pushed code that broke theirs or overwrote theirs—casualities of learning Mercurial—and then had to do clean the repository and get their solutions back in place.


Sprint 2: A 1.5-week short sprint

Sprint two ended today, and it was a short sprint due to weekend conferences: both me and the other lead investigator on the project would be away, and so we couldn't do a two-week sprint as planned. Instead, we decided to have Sprint 2 be a short one followed by a slightly longer Sprint 3.

I had overestimated the diligence of my students when, the weekend before the Sprint Planning meeting for Sprint 2, I emailed some comments on the revised product backlog and sprint backlog formats. As mentioned above, I revised the product backlog into items that required slicing by the students as opposed to pre-sliced tasks, and so I had also revised the Sprint Backlog format so that a PBI could be copied in and individual tasks listed below it. At 2pm we started the Sprint Planning, and it quickly became clear that the students had not appreciated this difference. Teams quickly started committing to PBIs, before they had taken the time to see that these were much heavier PBIs that needed breaking down. I hoped they would see this, but when I saw that teams were also changing the sprint backlog format to match the old one, I interrupted and explained what they should be doing: pulling down a PBI as a team, breaking it into tasks, committing to and estimating for those tasks, and then only committing to another PBI if there was excess capacity within the team.

The unfortunate result of this was that, rather than having a contiguous block of high-priority PBIs selected for the sprint, it was a bit of a toss-up. There was not time in our 50-minute timebox to start over, and so some rather important items were left unclaimed. Also, the teams shied away from high story point PBIs for fear of complexity in a short sprint, and I'm not sure that was unwise.

I felt a little more tension this sprint as more students had to use pieces created outside their team. Also, as I worked with teams, I noticed the overall quality of the code was getting worse. It's not so bad as to be unredeemable, but there are some code smells that would make a seasoned professional reach for a handkerchief. The problem is, of course and again, that it's a team of novices who cannot recognize code smells.

Even though the production was supposed to stop yesterday, I helped one team pull a last-minute victory before the Sprint Review and Retrospective today. The review went well, and my other two Product Owners agreed that it was good to see something actually working, rather than just looking at code that only I could appreciate. There were a few more loose ends this sprint: not all of the PBIs were completed according to their conditions of satisfaction, although this was fairly minor. One teams had committed to PBIs on the product backlog that it had neglected to copy to the team's Sprint Backlog, but I think they were embarrassed enough at this that they would not do it again. Much of this was fallout from the rough Sprint Planning meeting.

During the Sprint Retrospective, the students were much more pensive. No longer were they chomping at the bit to shout out the first positive thing that came to mind: instead, their contributions were more considered. This is natural, I think, and it shows a maturation of the studio. I was glad to see that inter- and intra-team communication, although mentioned as a success in Sprint 1, still was listed here, because communication is the key to keeping this studio together and making the project succeed.

We are currently discussing via our mailing list a few ways to address shortcomings in the system. One of the positive outcomes of this is that now, I think the students are all hungry for more information about software design and refactoring. They are feeling the real pain of real software development. This is very different from other teaching experiences—even my other class—where I have tried to teach the solution without the students really feeling the problem. It looks like we'll have some Community of Practice meetings in which I will lead code reviews or refactoring/redesign sessions. The students are hungry for it, and that should help them absorb some rich ideas.

Because I have them, here are the Sprint 2 burndown charts. They are in the same team order as the previous, so feel free to compare. My only significant comment about them is that, despite the fact that the teams were slicing up PBIs themselves for the first time—and many of them have never done this and never worked on a team before at all—these are still remarkably steady.





Onward to Sprint 3

While I am at the 2010 Consortium of Computing Sciences in Colleges Midwest conference, my students will be responsible for running the Sprint Planning meeting for Sprint 3. I have sorted out the highest priority PBIs, though I still need to do some cleaning up further down the backlog (which, incidentally, currently contains about 85 PBIs). I am confident that they will do a fine job in my absence.

This has been a fantastic teaching opportunity for me. I have invested more time and emotional energy into this project than any other venture since my doctoral dissertation, and I think the students appreciate being involved in this experience. My one niggling fear is that the whole experience cannot be replicated without expending this herculean effort each time, but I will leave sustainability of immersive learning for another writing.

Tuesday, September 7, 2010

A parenting reaction to a teaching problem

Something happened in CS222 today that surprised me. Specifically, I did something that surprised me. More specifically, I did something twice that surprised me. What did I do? I scolded my students.

I always have students close the door to the classroom since it's a noisy hallway. I have mentioned to the students many times that they should not come in late, because it is disrespectful to me and to their peers. I try to be transparent about my pedagogy, my constructivist teaching philosophy, and the idea that knowledge is created within a community of practice. Today, I was in the middle of a brief lesson on seemingly innocuous programming language features that, when misused, can lead to wicked bugs, when a student came into class late. It was about 8 minutes into class, and I cracked, pointing to him and shouting, "You need to stop coming to class late. It's driving me crazy!" Honestly, I don't know if that particular student had come in late before or not, but I was so irritated that I did not care. In retrospect, I hope "you" was interpreted in the plural, but I doubt that it was.

About seven minutes later, I had just finished my little impromptu lesson on the importance of using caution when modifying core language features (like Smalltalk's "new" method or operator overloading in C++), when a student let out a loud and bored-sounding sigh. I rolled with that one, saying something intended to imply my irritation. About three minutes later, the same voice let out the same sigh --- this time while I was in the middle of a demonstration --- and I lost it. I don't remember exactly what I said, but I know I pointed in that region of the room and commanded the person to stop it.

Needless to say, this did not set the right tone for the class. Later on, I told a funny story that involved repeatedly flipping off the classroom, and that seemed to cheer them up. Nothing gets students back like a little vulgarity.

In both instances, it was an immediate emotional pang that drove my reaction. It's the feeling I get when students dehumanize me or their classmates, treating the class as if they're watching a video. It's a feeling of being dehumanized and devalued. Further, it's a clear sign that the student is not trying to be part of a learning community. It's a terrible feeling.

Later on, I asked the students some questions about a piece of code I had just written, and none answered my question nor my request for questions about it. I knew that the non-participatory atmosphere was partially my own fault, so I had them form small groups that would be responsible for sharing either their best answer or their best question. As the students were working in small groups, it gave me time to start reflecting on what had happened, and I realized very quickly that I was treating these students --- the latecomer and the disinterested sigher --- the way I would treat my three-year-old son: I was scolding them, telling them to align their behaviors with accepted practice of politeness and social norms.

This was a personal revelation. In my ten-or-so years of teaching, I have had little trouble talking about technology and methodology, but I have had a much harder time talking about social norms. With a three-year-old, who is naturally testing his boundaries, I am now accustomed to monitoring his actions at home: when his antics shift from impish fun to dangerous or rude, it has to be nipped in the bud. This was exactly my reaction to the students in class: without even pausing to think about it, my "Dad Response" kicked in, and I scolded these students in pure authoritarian style.

As I continue to reflect on these actions and my reactions, I am having a hard time determining if I overreacted or not. Coming to class late is disrespectful to the whole learning community, and beyond that, it is very distracting. I made an example of the latecomer, and I like to rationalize my response as being a matter of fixing broken windows. I suppose the proof of the pudding is in the eating, and we'll see if students stop coming in late. If not, then it was neither worth embarrassing this one student nor worth establishing a negative atmosphere. Would it have been better to put off the day's lesson to have a roundtable discussion about why tardiness is rude, or why emitting sighs of ennui is impolite? I have a hard time imagining that to be the case. I am tempted to spend a few minutes on Thursday telling the students how I feel. Did they know that professors have feelings? It might be cathartic for me, but would it be a valuable use of our limited time together? Worse, would I just be preaching to the choir?