<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-34927953</id><updated>2011-09-11T04:12:00.512-07:00</updated><category term='ruby'/><category term='scala refactoring'/><category term='names'/><category term='scala'/><category term='scala ruby refactoring'/><category term='teaching'/><category term='pimp my library'/><category term='keyword parameters'/><category term='functional programming'/><category term='defaults'/><title type='text'>Jack Cough on Software</title><subtitle type='html'>Thoughts about Languages.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>93</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-34927953.post-6057748785085438363</id><published>2011-07-16T16:18:00.001-07:00</published><updated>2011-07-21T08:54:20.762-07:00</updated><title type='text'>Tail Calls, Tail Recursion, TCO</title><content type='html'>I'm going to tell a story that I think explains Tail Calls, Tail Recursion and TCO. I might decide to post some code about it, I might not. I don't actually find it necessary. First, a few definitions. If they aren't clear now, the stories should make them so.&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Tail Call - When the last thing a function does is call another function, and then immediately returns the result of that call.&lt;/li&gt;&lt;li&gt;Tail Recursion - Just a special case of tail call where the function tail called is the same as the caller function. Tail Recursion won't come up again in this post, so if the definition isn't clear, don't worry about it.&lt;/li&gt;&lt;li&gt;Tail Call Optimization - A compiler technique for avoiding adding an activation record to the stack for a tail call. (However, I don't like the word 'optimization' here. It is more like the correct implementation. More on that later.)&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span" style="font-weight: bold; "&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span class="Apple-style-span" style="font-weight: bold; "&gt;Regular Function Calls&lt;/span&gt;&lt;/h4&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Here, I tell a story about normal function calls, and introduce the theme and characters that will be used throughout the rest of this post. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Imagine that you have the munchies (feel free also, to imagine any reason why you might have the munchies :). Your particular craving at the moment is popcorn. A big bucket of salty, buttery popcorn. Standing next to you is your friend, Mr. Salt. He owns a salt shaker. Standing next to Mr. Salt is his friend Mr. Butter. Mr. Butter owns one of those liquid butter pumping machines that you see at the movie theaters. You don't really care that that happens to be a heart attack in the making. In fact, you don't really care about much of anything right now except the munchies and getting your popcorn :) Standing next to Mr. Butter is his friend Mr. Popper. Mr. Popper has a pop corn popper and a giant bin full of popcorn, and he's more than happy to dish some out. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;You turn to Mr. Salt and ask, "like, duuude...I'd really like some salty, buttery, delicious popcorn right now. Could you get it for me? Here's five bucks." You hand him the five dollars. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Mr. Salt says, "Sure, but just give me a second to get some buttery popcorn and I'll put some salt on it for you." He then turns to Mr. Butter and says, "I can haz buttery popcorn? I got 5 bills." Mr. Butter replies, "Oh hai, u can haz. Hold on a sec." &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Mr. Butter turns to Mr. Popper and asks him for some popcorn, handing him the 5 bucks. Mr. Popper obliges, and hands Mr. Butter a giant bucket of freshly popped plain popcorn.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Mr. Butter takes the popcorn, puts some butter on it, and hands it to Mr. Salt. Mr. Salt then takes the buttery delicious popcorn from Mr. Butter, puts a pile of salt on it, and hands it to Mr. Hungry Man (that's you). &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;These are examples of normal function calls, not tail calls. A tail call, once again, is when you make a function call, and have nothing left to do but return the result. But Mr. Butter and Mr. Salt did have work left to do with the result. Mr. Butter had to take the result (the plain popcorn) and apply butter to it. Similarly, Mr. Salt had to take the buttery popcorn and apply salt to it. Mr. Hungry Man had to eat the popcorn. (Mr. Popper didn't actually make a function call at all, he just immediately returned a result. Think 'def seven = 7').&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Notice that each person in the chain is like an activation record on the stack, and that they all eventually have to be popped off the stack.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;Tail Calls&lt;/span&gt;&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;To demonstrate tail calls, we only need to change the story slightly. You, (Mr. Munch, Mr. Hungry Man, Sir Smokealot) have decided to go on a diet. You ask Mr. Salt for some plain popcorn. He turns to Mr. Butter and asks him for plain popcorn. Mr. Butter turns to Mr. Popper and asks for some plain popcorn. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Here is where we really demonstrate the difference between a regular function call and a tail call. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Mr. Butter takes the popcorn from Mr. Popper and does nothing with it at all except turn around and hand it to Mr. Salt. He doesn't first apply butter to it. And, exactly the same, Mr. Salt takes the plain popcorn from Mr. Butter and turns around and hands it to Mr. Hungry Man. He doesn't put any salt on it. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Those are tail calls. Remember the definition: "&lt;/span&gt;When the last thing a function does is call another function, and immediately return the result of that call." The last thing those middle men did was ask someone else to get them something, took that thing from them and gave it to whoever asked them for it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;One important thing to notice here. I haven't talked at all about tail call optimization. Mr. Salt and Mr. Butter are still on the stack. They still take up space on the stack, and they still need to eventually be popped off the stack. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Before I talk about TCO, let's talk about the &lt;i&gt;need &lt;/i&gt;for TCO. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;The Problem&lt;/span&gt;&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Imagine simply, that the line of people between you and the popcorn was 1000 dudes long. You still just want some plain popcorn, but have to go through 999 middle men to get it. That's 999 guys on the stack. 999 guys that eventually have to get popped off the stack as well. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Ok, fine. That might work. I guess it depends on how big your stack is. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;But now imagine that the line is one million men long! 999999 middle men. 999999 guys on the stack right? WRONG. Stack Fricken Overflow Dood. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;In the JVM world, this is what you get. There are of course techniques to avoid it, but you're severely limited on the JVM because it doesn't support tail call optimization (it doesn't have a tailcall byte code).&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;Tail Call Optimization&lt;/span&gt;&lt;/h4&gt;&lt;span class="Apple-style-span"&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;Okay. Now is the part where I change the story to describe TCO, and how it works. It's actually very easy.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;You turn to Mr. Salt and say, "Can I please have some plain popcorn?" He turns the Mr. Butter and says, "Mr. Hungry Man would like some plain popcorn. Can you please get it for him? I don't really feel like it. In fact, I'm out of here." Mr. Salt then goes home for the day.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;span class="Apple-style-span"&gt;Mr. Butter turns to Mr. Popper and says the same thing: &lt;/span&gt;&lt;span class="Apple-style-span"&gt; "Mr. Hungry Man would like some plain popcorn. Can you please get it for him? I don't really feel like it. In fact, I'm out of here." Mr. Butter than also goes home for the day. &lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Mr. Popper gets a bucket of popcorn and simply hands it to Mr. Hungry Man. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;And that folks, is the end of the story. Case closed!&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;Ok fine, I guess it deserves at least a little more explanation. Mr. Salt, who knows he has a tail call where he would just take the result and give it to Mr. Hungry Man, can instead just have Mr. Butter give it to him. It makes absolutely no difference (ok a tiny difference that I'll explain later) who hands the popcorn to Mr. Hungry Man, so he might as well leave. In technical terms, Mr. Salt and Mr. Butter going home means they go off the stack. This could be implemented in a few different ways - maybe the top activation record is completely torn off the stack, or maybe it is just modified accordingly. Either way, this strategy saves stack space, and a little computation time too (remember that string of a million gotos that would have happened if the stack didn't overflow, all those instructions are saved).&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h4&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;Conclusion&lt;/span&gt;&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;I'd like to take this time to point out a confusion, or at least a point of contention in language designer circles (academics and non-academics alike). Because the term itself 'TCO' contains 'O' many people view TCO as just that, an optimization, while others view it simply as correct language design and implementation.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;I fall into the latter camp. I think it is analogous to garbage collection. I don't think most programmers would consider GC as an optimization, but simply correct implementation. It isn't ok to just run out of heap space because you didn't bother to implement a GC. And so, it isn't ok to run out of stack space just because you didn't bother to correctly implement tail calls. &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;I believe this post is consistent and self contained and I don't want to spoil it with code, too many technical details, or language specific details. For that reason, I believe a Scala related follow up post is in order. It would explain things like:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;&lt;span class="Apple-style-span"&gt;How the Scala compiler can turn tail recursive functions into while loops, and why it can't do so with non-final functions.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span class="Apple-style-span"&gt;What @tailrec does.&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span class="Apple-style-span"&gt;&lt;span class="Apple-style-span"&gt;Mutually recursive functions, trampolining and &lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: monospace; white-space: pre; "&gt;scala.util.control.TailCalls.&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;I also think I could extend this story to explain continuations. Maybe someday I'll get the chance to do that as well.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;h4&gt;&lt;span class="Apple-style-span"&gt;References&lt;/span&gt;&lt;/h4&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Lambda: the ultimate goto&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;a href="http://repository.readscheme.org/ftp/papers/ai-lab-pubs/AIM-443.pdf"&gt; http://repository.readscheme.org/ftp/papers/ai-lab-pubs/AIM-443.pdf&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Fortress Blog - ObjectOrientedTailRecursion&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://tinyurl.com/yjbgks3"&gt; http://tinyurl.com/yjbgks3&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Rich Dougherty - Tail Calls, Tail Rec, Trampolines&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html"&gt; http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;John Rose - Tail Calls in the JVM&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm"&gt; http://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Matthias Felleisen - A Tail-Recursive Machine with Stack Inspection&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://www.ccs.neu.edu/scheme/pubs/cf-toplas04.pdf"&gt; http://www.ccs.neu.edu/scheme/pubs/cf-toplas04.pdf&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Stack Overflow - @tailrec and non-final methods&lt;/li&gt;&lt;/ul&gt;&lt;a href="http://bit.ly/stacko-tailrec"&gt;http://bit.ly/stacko-tailrec&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6057748785085438363?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6057748785085438363/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2011/07/tail-calls-tail-recursion-tco.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6057748785085438363'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6057748785085438363'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2011/07/tail-calls-tail-recursion-tco.html' title='Tail Calls, Tail Recursion, TCO'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6835202548802862480</id><published>2010-12-14T14:08:00.000-08:00</published><updated>2010-12-15T07:09:35.152-08:00</updated><title type='text'>Code Styles and Readability</title><content type='html'>Today at work we went on a quest to make a piece of code as readable as possible. I'm not fully convinced that we've succeeded entirely, but we learned a few things along the way.&lt;br /&gt;&lt;br /&gt;The problem we're trying to solve is pretty simple. Given an activation record which represents the last call on the call stack, generate a List of Strings to be used in building the stack trace. This will require going all the way up to the first call on the stack by following parent pointers, grabbing the name of each procedure.&lt;br /&gt;&lt;br /&gt;Before we begin, we need to understand a few things about the system.&lt;br /&gt;One could imagine these simple classes:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class Procedure_V1(name: String)&lt;br /&gt;case class Activation_V1(procedure: Procedure, parent: Activation)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If that's all there was, there probably wouldn't be much to write about. I'll give a small bit more detail. In our world, a Procedure holds a List of Commands that it executes one by one until it is done. Any Command in this list could be a primitive, or a call to another procedure. If the Command is a primitive, it can just be executed on the spot. One example of a primitive is +. If the command is a call to another procedure then upon execution of this Command, a new Activation gets created. So the objects now look like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class Command_V2(name:String)&lt;br /&gt;case class Procedure_V2(name: String, commands: List[Command])&lt;br /&gt;case class Activation_V2(procedure: Procedure, parent: Activation)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;There's one minor catch that makes this whole thing interesting: any particular Activation might need to put two different entries into the stack trace. 1) Its own procedures name, and possibly 2) The name of its parent's current command. I wish I had time and space enough to explain why, but that's simply out of scope. For now, I'll just explain some simple rules.&lt;br /&gt;&lt;br /&gt;A command should show up in the stack trace only if it calls other code. Activations have a return address which an index into it's parents commands List. It points to currently running command in the parent Activation. These rules allows us to write the final versions of the classes:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class Command(name:String, callsOtherCode: Boolean)&lt;br /&gt;case class Procedure(name: String, commands: List[Command])&lt;br /&gt;case class Activation(procedure: Procedure, parent: Activation, returnAddress:Int)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Lets also say that these classes are sealed (or that we can't modify them). With these, we can take a stab at the original problem.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStack_V1(act: Activation): List[String] = {&lt;br /&gt;  val parentCommandMaybe: Option[String] = Option(act.parent).flatMap(p =&gt; {&lt;br /&gt;    val c = p.procedure.commands(act.returnAddress)&lt;br /&gt;    if(c.callsOtherCode) Some(c.name) else None&lt;br /&gt;  })&lt;br /&gt;  List(Some(act.procedure.name), parentCommandMaybe).flatten :::&lt;br /&gt;          callStack_V1(act.parent)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This was the first version I wrote. I liked it then, I still like it now. But, I wanted to see if I could make it better. First, lets see if we can clean up that last line. The list creation is a little confusing.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStack_V2(act: Activation): List[String] = {&lt;br /&gt;  val parentCommandMaybe: Option[String] = Option(act.parent).flatMap(p =&gt; {&lt;br /&gt;    val c = p.procedure.commands(act.returnAddress)&lt;br /&gt;    if(c.callsOtherCode) Some(c.name) else None&lt;br /&gt;  })&lt;br /&gt;  act.procedure.name :: parentCommandMaybe.toList ::: callStack_V1(act.parent)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Only slightly better. Maybe if we remove the recursion things will be nicer.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStack_V3(act: Activation): List[String] = {&lt;br /&gt;  Iterator.iterate(act)(_.parent).takeWhile(_ != null).toList.flatMap { a =&gt;&lt;br /&gt;    val proc = act.procedure.name&lt;br /&gt;    val parentCommandMaybe: Option[String] = Option(a.parent).flatMap(p =&gt; {&lt;br /&gt;      val c = p.procedure.commands(a.returnAddress)&lt;br /&gt;      if (c.callsOtherCode) Some(c.name) else None&lt;br /&gt;    })&lt;br /&gt;    act.procedure.name :: parentCommandMaybe.toList&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That first bit before the first flatMap turns the stack into a List[Activation]. While that idea is simple enough, the code to do it really isn't. And, the remainder of the code is really hard to follow too. I still manage to struggle to fully understand a single flatMap sometimes, let alone two. Sure the type annotations help explain what is happening, but I still felt I could do better. Let's keep the same idea, but refactor a bit and see if that helps.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def unfold(act: Activation) =&lt;br /&gt;  Iterator.iterate(act)(_.parent).takeWhile(_ != null).toList&lt;br /&gt;&lt;br /&gt;def callStack_V4(act: Activation): List[String] = {&lt;br /&gt;  unfold(act).flatMap { a =&gt;&lt;br /&gt;    val parentCommandMaybe: Option[String] = Option(a.parent).flatMap(p =&gt; {&lt;br /&gt;      val c = p.procedure.commands(a.returnAddress)&lt;br /&gt;      if (c.callsOtherCode) Some(c.name) else None&lt;br /&gt;    })&lt;br /&gt;    act.procedure.name :: parentCommandMaybe.toList&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Maybe thats ok, it gets some of that clutter out of the way and let's us think. But lets take a complete step back and try an imperative version. All the flattening is still hurting my head.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStackImperative(act: Activation): Seq[String] = {&lt;br /&gt;  val buf = collection.mutable.ListBuffer[String]()&lt;br /&gt;  for(a &lt;- unfold(act)) {&lt;br /&gt;    buf += a.procedure.name&lt;br /&gt;    if (a.parent != null) {&lt;br /&gt;      val c = a.parent.procedure.commands(a.returnAddress)&lt;br /&gt;      if (c.callsOtherCode) buf += c.name&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  buf&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is a case where an imperative style actually does quite well. I usually try to avoid this style like the plague, but in this case theres little doubt that this code is simple.&lt;br /&gt;&lt;br /&gt;I still thought I could do better, so I continued. This time with a Racket friend.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStackSchemer(act: Activation): List[String] = {&lt;br /&gt;  def callStackInner(act: Activation): List[String] = {&lt;br /&gt;    if (act == null) Nil&lt;br /&gt;    else {&lt;br /&gt;      val rest = callStackInner(act.parent)&lt;br /&gt;      def parCmd = act.parent.procedure.commands(act.returnAddress)&lt;br /&gt;      act.procedure.name ::&lt;br /&gt;        (if (act.parent != null &amp;&amp; parCmd.callsOtherCode) parCmd.name :: rest&lt;br /&gt;         else rest)&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  callStackInner(act)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The advantage of this approach is that it could be read by a 10 year old. Ok maybe not 10. But, there are no for comprehensions, options, or flattening bits here. However, I do think there is a little bit of mixing up what is happening with how its happening. That is, the result building is mixed up with the structural recusion on the Activation. For this little function, it almost certainly doesn't matter that much. For something larger, it might.&lt;br /&gt;&lt;br /&gt;Let explore a different topic for a bit. Sometimes, even with inner defs, pulling something outside of the body of a function helps clear out the clutter and makes it more readable. We did this already with unfold. There are tradeoffs of course, such as you then have a function in the top level that is only being used in one place. But, lets try it again anyway and see where it gets us..&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def parentCommandMaybe_V1(act: Activation): Option[String] =&lt;br /&gt;  Option(act.parent).flatMap(p =&gt; {&lt;br /&gt;    val c = p.procedure.commands(act.returnAddress)&lt;br /&gt;    if (c.callsOtherCode) Some(c.name) else None&lt;br /&gt;  })&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Pulling that out also helps me realize just how complicated that bit is. Maybe we can do better just on this part. Here are two attempts.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def parentCommandMaybe_V2(act: Activation): Option[String] =&lt;br /&gt;  if(act.parent == null) None&lt;br /&gt;  else{&lt;br /&gt;    val command = act.parent.procedure.commands(act.returnAddress)&lt;br /&gt;    if(command.callsOtherCode) Some(command.name) else None&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;def parentCommandMaybe_V3(act: Activation): Option[String] =&lt;br /&gt;  for{p &lt;- Option(act.parent)&lt;br /&gt;      c = p.procedure.commands(act.returnAddress)&lt;br /&gt;      if c.callsOtherCode}&lt;br /&gt;  yield c.name&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To be quite honest, none of these solutions are glorious. I'm tempted to use V2 because any knuckehead could read it, and its of comparable size. I could have easily decided on V1 or V3 because we don't have any knuckeheads on our team. We do however, occasionally have students on the team and we are attempting to open source our code. Is that a good reason to dumb down the code? No, certainly not. But, if a particular function is of comparable size, then maybe it is a good idea. Or maybe not, maybe leaving the more advanced constructs (like for comprehensions) would make code readers learn more about the language that they are using. I'm undecided on this. Given the lack of wanting to make a decision here, I'll just choose V3.&lt;br /&gt;&lt;br /&gt;Better solutions to this are most welcome.&lt;br /&gt;&lt;br /&gt;Now that we've pulled that out, we can rewrite our function.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStack_V7(act: Activation): List[String] = {&lt;br /&gt;  unfold(act).flatMap { a =&gt; &lt;br /&gt;     act.procedure.name :: parentCommandMaybe_V3(act).toList&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I think this is a really nice version. But...now that we've cleaned up some of the helper methods, lets see what things look like if we put them back in.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def callStack_V8(act: Activation): List[String] = {&lt;br /&gt;  def unfold(act: Activation) =&lt;br /&gt;    Iterator.iterate(act)(_.parent).takeWhile(_ != null).toList&lt;br /&gt;  def parentCommandMaybe_V3(act: Activation): Option[String] =&lt;br /&gt;    for{p &lt;- Option(act.parent)&lt;br /&gt;        c = p.procedure.commands(act.returnAddress)&lt;br /&gt;        if c.callsOtherCode}&lt;br /&gt;    yield c.name&lt;br /&gt;  unfold(act).flatMap { a =&gt; &lt;br /&gt;    a.procedure.name :: parentCommandMaybe(a).toList&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Not bad. It may be a few lines longer than version 1, and it took quite a while to get here, but I do think this version is the best we can do. 'We' being my team. Finally, I'll add in some comments and call it a day. It would be nice if the code was so blatently obvious that this wasn't needed, but it's ok. Comments are helpful.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;/**&lt;br /&gt; * Return a List representing the call stack.&lt;br /&gt; * The list includes procedure names and any commands&lt;br /&gt; * that call other code.&lt;br /&gt; * @param act - the final call on the stack.&lt;br /&gt; **/&lt;br /&gt;def callStack(act: Activation): List[String] = {&lt;br /&gt;  // unfold turns an activation into&lt;br /&gt;  // List(act, act.parent, act.parent.parent ... )&lt;br /&gt;  def unfold(act: Activation) =&lt;br /&gt;    Iterator.iterate(act)(_.parent).takeWhile(_ != null).toList&lt;br /&gt;  // if an activations parent is executing a command that can trigger&lt;br /&gt;  // other code, it also needs to be added to the stack trace.&lt;br /&gt;  def parentCommandMaybe(act: Activation): Option[String] =&lt;br /&gt;    for{p &lt;- Option(act.parent)&lt;br /&gt;        c = p.procedure.commands(act.returnAddress)&lt;br /&gt;        if c.callsOtherCode}&lt;br /&gt;    yield c.name&lt;br /&gt;  // flatMap because each activation can result in 1 or 2 entries&lt;br /&gt;  unfold(act).flatMap { a =&gt; &lt;br /&gt;    a.procedure.name :: parentCommandMaybe(a).toList&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If you can write this better, please do. Send it to me and I'll learn something.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6835202548802862480?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6835202548802862480/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/12/code-styles-and-readability.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6835202548802862480'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6835202548802862480'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/12/code-styles-and-readability.html' title='Code Styles and Readability'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8820874824077824251</id><published>2010-11-27T19:12:00.001-08:00</published><updated>2010-11-27T21:34:14.636-08:00</updated><title type='text'>App Inventor Review (plus some functional programming)</title><content type='html'>&lt;div style="text-align: center;"&gt;&lt;span class="Apple-style-span"&gt;&lt;u&gt;&lt;br /&gt;&lt;/u&gt;&lt;/span&gt;&lt;/div&gt;I App Invented all day today. Half of this was because it was fun, the other half was because it took all day to get anything reasonable done. Before I get into this at all, let me say that I had fun. I think App Inventor could be a cool tool in the future, and it was relatively bug free and nice to use. I think they have done a good job on it and I'm very happy for them. I don't know what their plans are for adding more language features in the future, but even though it was fun, I won't be using it again until they add a few things. I'll explain. &lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But lastly, before I do, I want to say that I hope I simply haven't overlooked anything. These are my impressions after using it for a day, and they are impressions from my language designers perspective. If I've managed to overlook some capabilities because of failure to read everything I was supposed to read, then I apologize. I don't think this is the case though.&lt;br /&gt;&lt;br /&gt;After growing up and becoming a decent functional programmer (and/or growing out of Java), whenever I try to learn a new language that doesn't have certain functions that I've grown accustomed to (like head, tail, list-to-string, string-to-list, filter, map, flatten, and more) I find that I build them immediately and then start actually building something. Guy Steele put this so elegantly in his talk &lt;a href="http://video.google.com/videoplay?docid=-8860158196198824415#"&gt;Growing a Language&lt;/a&gt;. &lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, I set out to build them. But I found out right away that the blocks in App Inventor were severely limited. You do have the ability to create your own functions, but there are no higher order functions so right away you lose the ability to write map and filter (without repeating the mapping and filtering logic every time). Both map and filter could be accomplished with data abstraction (albeit slightly unnaturally), but that doesn't exist either. Ok, I'll be honest, I didn't expect this higher order functions, so this is ok. I didn't really expect data abstraction either. So I'll let that slide too. But, it sure would be nice if we could have a blocks language that does have them. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;App Inventor does have Lists though, and Strings. But, Strings are not Lists, and no functions are provided to convert between the two. This bit was quite frustrating. Having to write string-to-list and list-to-string seemed wrong, especially when those are two of the main data types in the system. Lists did seem to implicitly convert to Strings in certain situations, but wrapped in parens. If I simply wanted to convert [a, b, c, d, c] to "abcde", I had to use my function. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So I set out to build both of those functions, and I started with string-to-list. This is when I found out the really bad news, the one fundamental flaw with App Inventor. You can't have local variables in your procedures... Worse yet, &lt;i&gt;&lt;b&gt;every time&lt;/b&gt;&lt;/i&gt; you need to name something, it becomes a global variable.&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;When you need a temp, create a global.&lt;/li&gt;&lt;li&gt;Globals are event created for every procedure argument. &lt;/li&gt;&lt;/ul&gt;&lt;div&gt;The last one is particularly bad, because if you have two operations that work on lists, you have to pick a new name for the argument to each of the functions. For example, imagine if you had to do this in Scala:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;&lt;blockquote&gt;&lt;div&gt;&lt;div&gt;def head[A](aList:List[A]): A = ...&lt;/div&gt;&lt;/div&gt;&lt;div&gt;def tail[A](anotherList:List[A]): List[A] = ...&lt;/div&gt;&lt;div&gt;def toString(yetAnotherList:List[_]) = ...&lt;/div&gt;&lt;/blockquote&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And imagine further that these names followed you around wherever you go. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You might be thinking, 'Well, maybe its not too big of a problem. After all, it's probably the case that App Inventor was designed for small things, and for teaching.' Well, the global thing is a real problem. Having to explain this to beginners trying to learn would be a nightmare. Thankfully, the App Inventor team does recognize this. Hal Abelson said on &lt;a href="http://groups.google.com/group/appinventor/browse_thread/thread/ef57034a9b075f57"&gt;this thread&lt;/a&gt;, &lt;blockquote&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;"&lt;span class="Apple-style-span" style="font-family: arial, sans-serif; "&gt;We're planning on adding local variables (no ETA).  We agree that these are &lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: arial, sans-serif; "&gt;important for teaching programming."&lt;/span&gt;&lt;/span&gt;&lt;/blockquote&gt;&lt;/div&gt;Phew. But then again, that was August 7th and we're now pushing into December. (But I know how this goes as I've been working on a couple of my own language features for over a year now.)&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now back to the second point; having every procedure stomp all over the global namespace did turn out to be a problem in a relatively small amount of code. Yes I wrote all day, but I did't really churn out that much. Part of this was because I was slowed down mucking through the UI trying to find my procedure call blocks. I ended up with so much stuff in the My Definitions thingy, that it was a nightmare to find anything. This could probably be cleaned up pretty easily if they added the ability to sort it alphabetically. But even so, the globals business is bad for other reasons too. It just sort of continues encouraging imperative programming in a very unsatisfying way. I feel dirty after it. Oh well, hopefully they can get it fixed. Like I said, I did have fun, so I'm not trying to be negative, just blatantly honest.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ok, finally back to string-to-list. Right away I noticed that there wasn't a charAt function. There is a 'segment' function which is basically substring, but I wanted charAt. So I wrote it, and fortunately it was one of the easier functions to write. Here it is:&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;img src="http://2.bp.blogspot.com/_CapVmQaDUgA/TPHX7v1cMOI/AAAAAAAAAEQ/axcXPRvzz7E/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B9.57.02%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544450037722656994" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 398px; height: 225px; " /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;The first time I wrote the string_to_list function, I wrote it using globals in typical imperative style. Here it is:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-size: medium;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;img src="http://2.bp.blogspot.com/_CapVmQaDUgA/TPHY7jEEwJI/AAAAAAAAAEg/UgmQnUWttlA/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B9.56.51%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544451133806002322" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 346px; " /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Hopefully that doesn't come out too difficult to read. If it does, you can just click on it to view it bigger. I just looped until the end of the String, adding to an accumulator. The accumulator was a global, along with the loop index. This is pretty gross, but whatever, it works. I tried it without the globals, but this turned out to be even worse, I think. Well, maybe not worse, but bigger, and uglier:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHZ4GoT_eI/AAAAAAAAAEo/hioJXgRU-j0/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B10.11.11%2BPM.png"&gt;&lt;img src="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHZ4GoT_eI/AAAAAAAAAEo/hioJXgRU-j0/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B10.11.11%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544452174145388002" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 327px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This one might actually be too small to read, and I screwed up the screen shot, but you can click it. I think most of what you need is there. Because I am not using a global, I have to use recursion. But this means I have to have the index and acc parameters passed in. Because I don't want users to have to pass this in, I just used two functions. The actual meat of the function is roughly the same size as the other. Fine. We'll they are both pretty huge, so not fine...but fine.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ok, 1/2 the day is gone and I have string-to-list and charAt written (maybe an exaggeration, I can't really remember). At this point in writing this post I went to look for list_to_string. I couldn't find it. I swear I wrote it. Didn't I? Did I not need it? This just goes to show the problems with finding things in App Inventor. It's a big pain. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So maybe I didn't write it. But I did write some others I was going to need. I've explained most of the problems that I encountered, so most of the rest of the functions can be displayed without ceremony. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here are head and tail:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHcbLybfnI/AAAAAAAAAEw/oeUwopvZUwU/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B10.34.19%2BPM.png"&gt;&lt;img src="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHcbLybfnI/AAAAAAAAAEw/oeUwopvZUwU/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B10.34.19%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544454975848676978" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 384px; height: 400px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Head was fine. Tail was kind of disgusting because I had to mutate a global so that I didn't have to mutate the argument. Try explaining any of that to a beginner. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Zip suffered from problems already discussed:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://1.bp.blogspot.com/_CapVmQaDUgA/TPHdJ8baHSI/AAAAAAAAAE4/_Apt8lFuBaw/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B10.37.41%2BPM.png"&gt;&lt;img src="http://1.bp.blogspot.com/_CapVmQaDUgA/TPHdJ8baHSI/AAAAAAAAAE4/_Apt8lFuBaw/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B10.37.41%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544455779179437346" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 381px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Unzip also demonstrates nothing new:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://4.bp.blogspot.com/_CapVmQaDUgA/TPHdfJvQCyI/AAAAAAAAAFA/TJ6Bm0ixQqU/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B10.39.24%2BPM.png"&gt;&lt;img src="http://4.bp.blogspot.com/_CapVmQaDUgA/TPHdfJvQCyI/AAAAAAAAAFA/TJ6Bm0ixQqU/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B10.39.24%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544456143529577250" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 325px; height: 400px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Filter was problematic as I explained earlier. You can't pass lambdas around, so any time you want to filter you just have to reproduce the logic. There's no way around it. Map too (though I didn't write map, but I guess unzip is just a map). Here is a simple filter. I didn't really test it because I used a much more complicated one. But, I think it should work:&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;a href="http://1.bp.blogspot.com/_CapVmQaDUgA/TPHhapgPpfI/AAAAAAAAAFY/BwzQPno4Pmc/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B10.56.18%2BPM.png"&gt;&lt;img src="http://1.bp.blogspot.com/_CapVmQaDUgA/TPHhapgPpfI/AAAAAAAAAFY/BwzQPno4Pmc/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B10.56.18%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544460464203736562" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 369px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Finally, I wrote flatten. This one proved to be tricky and fun. I haven't actually used it anywhere yet, but thats ok. It was tough to figure out at first, but I got it. See if you can understand it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHjL_YguiI/AAAAAAAAAFg/zXFPMlTZm1Q/s1600/Screen%2Bshot%2B2010-11-27%2Bat%2B11.02.52%2BPM.png"&gt;&lt;img src="http://3.bp.blogspot.com/_CapVmQaDUgA/TPHjL_YguiI/AAAAAAAAAFg/zXFPMlTZm1Q/s400/Screen%2Bshot%2B2010-11-27%2Bat%2B11.02.52%2BPM.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5544462411402099234" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 389px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Some other remarks and random comments:&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Testing was not too bad. When I had a function that didn't quite work right on the phone the first time, I could easily set up a call to it in the IDE, and see the results. That was nice. It would be much nicer to have a way to define actually test cases on these things, but no one ever seems to listen to me on that.&lt;/li&gt;&lt;li&gt;Code organization was a huge problem. As procedures grew, I'd have to shift everything around. It only gives you so much vertical space. Horizontal space seemed unlimited, but it was tricky to make it grow. They have an auto-organize feature, but it did some things that I didn't want it to do, such as moving globals away from the only procedure that they were used in.&lt;/li&gt;&lt;li&gt;When I named something incorrectly (I often put a dash, forgetting that it is illegal), the system yelled at me and says that it is an illegal name, but didn't say why. Then...it reverts back to whatever name was there before. So, if I had typed in a long name, I'm forced to retype it all again. that was super aggravating.&lt;/li&gt;&lt;li&gt;Sometimes it would say there was an error in a procedure, but it wouldnt tell me what the error was. &lt;/li&gt;&lt;li&gt;Things are slow. Yes, I know, I should expect them to be nearly as fast as typing. But, I found myself getting frustrated with just how slow things seemed. certainly, beginners won't be working as fast as myself, but there are times when I could imagine them getting frustrated too. Removing many of the globals would help. A quick-find for procedures would help too.&lt;/li&gt;&lt;li&gt;Message passing, Scratch style, would be very nice. I could easily imagine different GUI components passing messages to each other. My 9 year old son uses that style in Scratch all the time and it works great.&lt;/li&gt;&lt;li&gt;When there was a runtime error, it was difficult to tell what the error was. Additionally, the application would just halt. No option to continue. That seemed odd. Why not just let it continue in its current state and let the user decide to restart?&lt;/li&gt;&lt;li&gt;I was pretty easily able to find things in the documentation the few times that I needed to look things up. That was nice. &lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;That's just about it. I guess I'll conclude. I had fun, I like App Inventor. By the end of the day, I had a working game going (not described here). I think App Inventor could be made pretty awesome by fixing some of the things I mentioned above. I'm not sure I'll continue to teach it to my son or not. On one side of the coin, it can do some pretty fun things with the phone (some of which I haven't tried, and none of which I've written up here.) On the other side, it's got severe limitations and I might as well move my son to Build Your Own Blocks. I probably actually have more comments, but I'm getting pretty tired at this point. Goodnight Moon. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8820874824077824251?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8820874824077824251/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/11/app-inventor-review-plus-some.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8820874824077824251'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8820874824077824251'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/11/app-inventor-review-plus-some.html' title='App Inventor Review (plus some functional programming)'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_CapVmQaDUgA/TPHX7v1cMOI/AAAAAAAAAEQ/axcXPRvzz7E/s72-c/Screen%2Bshot%2B2010-11-27%2Bat%2B9.57.02%2BPM.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2392208901439516075</id><published>2010-02-24T09:01:00.000-08:00</published><updated>2010-03-14T09:55:58.976-07:00</updated><title type='text'>SBT and Test Arguments</title><content type='html'>&lt;br&gt;&lt;br /&gt;If you want to pass arguments to tests in SBT, you've come to the right place. First know this - it only works in certain situations, it's a bit crufty, and its subject to change. But I'll try to keep this page up to date if it does change.&lt;br /&gt;&lt;br /&gt;Another important note, if you want to pass arguments at the sbt command line, you can only do it for test-quick, and test-only (I think). It doesn't work for the default "test" command. This is a bit unfortunate, but there is a workaround (not a very good one, but at least it exists).&lt;br /&gt;&lt;br /&gt;A final note: these examples are for ScalaTest and ScalaCheck. I don't yet have examples for Specs, but Eric has implemented argument handling (in 1.6.2.1-SNAPSHOT for scala 2.7.7 and 1.6.4-SNAPSHOT for scala 2.8.0.Beta1).&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Passing Args to ScalaTest from the Command Line&lt;/h4&gt;&lt;br /&gt;Let's say you have this little ScalaTest class that uses both params and tags:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.scalatest.fixture.FixtureFunSuite&lt;br /&gt;import org.scalatest.Tag&lt;br /&gt;&lt;br /&gt;class WickedCoolTest extends FixtureFunSuite{&lt;br /&gt; type FixtureParam = Map[String,Any]&lt;br /&gt; override def withFixture(test: OneArgTest) {&lt;br /&gt;   test(test.configMap)&lt;br /&gt; }&lt;br /&gt; test("1", Tag("dood1")){ conf =&gt; println("dood1: " + conf) }&lt;br /&gt; test("2", Tag("dood2")){ conf =&gt; println("dood2: " + conf) }&lt;br /&gt; test("3", Tag("dood3")){ conf =&gt; println("dood3: " + conf) }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;To run all tests in in this class use:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To run only tests tagged with "dood1" use:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -n dood1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To run tests tagged with dood1 or dood2, use:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -n "dood1 dood2"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To run all tests except for tests tagged with dood2, run:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -l dood2&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To run all tests except for tests tagged with dood2 dood3, run:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -l "dood2 dood3"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To pass configuration parameters to a test, use:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -Danswer=42&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To pass many config params, add more -D's:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -Danswer=42 -DrealAnswer=54&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Tags and parameters can be used in combination, like so:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;test-only WickedCoolTest -- -n "dood dood2" -Dhey=you -Dm=f&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This runs only tests tagged with dood or dood2 and produces the following output:&lt;br /&gt;&lt;br /&gt;dood: Map(hey -&gt; you, m -&gt; f)&lt;br /&gt;dood2: Map(hey -&gt; you, m -&gt; f)&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Passing Args to ScalaCheck from the Command Line&lt;/h4&gt;&lt;br /&gt;I'll spare you the entire example and just get to the point here.&lt;br /&gt;&lt;br /&gt;To set the minimum number of successful tests, use '-s'&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&gt; test-only *IntParallelArrayCheck -- -s 5000&lt;br /&gt;...&lt;br /&gt;[info] == scala.collection.parallel.mutable.IntParallelArrayCheck ==&lt;br /&gt;[info] OK, passed 5000 tests.&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The rest of the examples are very similar. Consult ScalaCheck itself for further documentation. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;-s (minSuccessfulTests): Number of tests that must succeed in order to pass a property&lt;br /&gt;&lt;li&gt;-d (maxDiscardedTests): Number of tests that can be discarded before ScalaCheck stops testing a property&lt;br /&gt;&lt;li&gt;-n (minSize): Minimum data generation size&lt;br /&gt;&lt;li&gt;-x (maxSize): Maximum data generation size&lt;br /&gt;&lt;li&gt;-w (workers): Number of threads to execute in parallel for testing&lt;br /&gt;&lt;li&gt;-z (wrkSize): Amount of work each thread should do at a time&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Default Arguments&lt;/h4&gt;&lt;br /&gt;Maybe you want to pass default arguments to your test framework of choice. That is, you want to pass the same arguments every time you run your tests (and still be able to pass more dynamically, if you wish). You can do this too, by adding elements to 'testOptions'. Doing so will take effect when you run sbt test, sbt test-only, sbt test-quick, etc. &lt;br /&gt;&lt;br /&gt;Let's say you want the minimum number of ScalaCheck passing tests to be 5000 every time you run ScalaCheck. Here is how you do that: &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;override def testOptions = &lt;br /&gt;  super.testOptions ++ &lt;br /&gt;  Seq(TestArgument(TestFrameworks.ScalaCheck, "-s", "5000")) &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Or maybe you only ever want to run your fast ScalaTest tests.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;override def testOptions = &lt;br /&gt;  super.testOptions ++ &lt;br /&gt;  Seq(TestArgument(TestFrameworks.ScalaTest, "-n", "fast")) &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h4&gt;Custom Test Tasks&lt;/h4&gt;&lt;br /&gt;Maybe you have some test that you run all the time. At the sbt command line, instead of saying &gt; test-quick blah.blah.Blah, you just want to say: &gt; blah.&lt;br /&gt;&lt;br /&gt;You can do that too, and you can pass args to it dynamically, and you get the default arguments as well. You'll have to take the following code and put it into your sbt file. It's ugly, I know, but the results are nice. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;lazy val blah = singleTestTask("blah.blah.Blah")&lt;br /&gt; &lt;br /&gt;private def singleTestTask(className: String) = task { args =&gt;&lt;br /&gt;  defaultTestTask(TestFilter(_ == className) :: &lt;br /&gt;   testOptions.toList ::: ScalaTestArgs(args))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private def newScalaTestArg(l: String*) = &lt;br /&gt;  TestArgument(TestFrameworks.ScalaTest, l:_*)&lt;br /&gt;&lt;br /&gt;private def ScalaTestArgs(args: Seq[String]): List[TestArgument] = {&lt;br /&gt;  def KVArgs(args: Seq[String]): TestArgument = &lt;br /&gt;    newScalaTestArg(args.map("-D" + _):_*)&lt;br /&gt;  def tagsFromArgs(tags: Seq[String]): List[TestArgument] = {&lt;br /&gt;    if (tags.isEmpty) Nil else &lt;br /&gt;      List(newScalaTestArg("-n", tags.mkString(" ")))&lt;br /&gt;  }&lt;br /&gt;  val (kvs, tags) = args.partition(_.contains("="))&lt;br /&gt;  KVArgs(kvs.toSeq) :: tagsFromArgs(tags.toSeq)&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;h4&gt;Subclasses&lt;/h4&gt;&lt;br /&gt;Finally, maybe you want to set up tasks like 'test-fast' and 'test-slow' which only run your fast and slow tests. Let's imagine that you've created a trait called blah.blah.SlowTest and all of your slow tests extend that trait. Tests that don't extend SlowTest are considered to be in the fast group. With the code below, at the sbt command line you'll be able to say &gt; test-fast, and &gt; test-slow. &lt;br /&gt;&lt;br /&gt;Again, it's a bit ugly to put this stuff in your sbt project file, but it works for now, until I come up with a better plan :)&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;lazy val testSlow = &lt;br /&gt;  runSubclassesOf("org.nlogo.util.SlowTest")&lt;br /&gt;lazy val testFast = &lt;br /&gt;  runEverythingButSubclassesOf("org.nlogo.util.SlowTest")&lt;br /&gt;&lt;br /&gt;private def runSubclassesOf(className: String) = {&lt;br /&gt;  val subclass: Boolean =&gt; Boolean = x =&gt; x&lt;br /&gt;  subclassTest(className, subclass)&lt;br /&gt;}&lt;br /&gt;  &lt;br /&gt;private def runEverythingButSubclassesOf(className: String) = {&lt;br /&gt;  val notSubclass: Boolean =&gt; Boolean = x =&gt; ! x&lt;br /&gt;  subclassTest(className, notSubclass)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private def subclassTest(className: String, &lt;br /&gt;                         subclassCheck: Boolean =&gt; Boolean) = task { &lt;br /&gt;  args =&gt;&lt;br /&gt;  lazy val jars = &lt;br /&gt;    testClasspath.get.toList.map(_.asURL).toArray[java.net.URL]&lt;br /&gt;  lazy val loader = &lt;br /&gt;    new java.net.URLClassLoader(jars,buildScalaInstance.loader)&lt;br /&gt;  def clazz(name: String) = Class.forName(name, false, loader)&lt;br /&gt;  lazy val superClass = clazz(className)&lt;br /&gt;  def filter = &lt;br /&gt;    TestFilter(c =&gt; &lt;br /&gt;      subclassCheck(superClass.isAssignableFrom(clazz(c))))&lt;br /&gt;  defaultTestTask&lt;br /&gt;    (filter :: testOptions.toList ::: ScalaTestArgs(args))&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Yeah...&lt;/h4&gt;&lt;br /&gt;Let me know if you have any issues with any of this, I'll be happy to help. I put it together pretty quickly. If there are any glaring errors or omissions, please tell.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2392208901439516075?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2392208901439516075/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/02/sbt-and-test-arguments.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2392208901439516075'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2392208901439516075'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2010/02/sbt-and-test-arguments.html' title='SBT and Test Arguments'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8836349795161961876</id><published>2009-11-13T20:32:00.000-08:00</published><updated>2009-11-13T22:20:27.192-08:00</updated><title type='text'>Introducing Sweet</title><content type='html'>&amp;nbsp;&lt;br /&gt;In this post I introduce Sweet, the fully complete test framework (even with IDE support) in only 99 lines of code. Sweet is compiled against the new Scala-2.8.0.Beta1-RC1, and works great with simple build tool 0.6.3. Sweet lives at: &lt;a href="http://github.com/joshcough/Sweet"&gt;http://github.com/joshcough/Sweet&lt;/a&gt;. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Your First Sweet &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;Sweets are just like ScalaTest's FunSuite, using the test("name"){ ... } style. The syntax is exactly the same:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class HelloWorldSweet extends Sweet {&lt;br /&gt;&lt;br /&gt;  test("hello, world!"){&lt;br /&gt;    "hello, world!" mustBe "hello, world!"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Just this (and one minor sbt configuration) will get you fully up and running with simple build tool. Your tests will be discovered and run automatically by sbt, just as they are with the other Scala test frameworks. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Assertions &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;Sweet currently offers only two assertions, in matchers style: mustBe and mustNotBe. Let's extend the hello world example to show usages of each:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class HelloWorldSweet2 extends Sweet {&lt;br /&gt;&lt;br /&gt;  test("hello, world! with mustBe"){&lt;br /&gt;    "hello, world!" mustBe "hello, world!"&lt;br /&gt;  }&lt;br /&gt;  test("hello, world! with mustNotBe"){&lt;br /&gt;    "hello, world!" mustNotBe "goodbye, world!"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And while were at it, let's how a quick boolean example:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class BooleanAssertionExampleSweet extends Sweet {&lt;br /&gt;&lt;br /&gt;  test("hello, world!"){&lt;br /&gt;    val b = imagaryCallThatReturnsABoolean()&lt;br /&gt;    b mustBe true&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I know it's not much, but it probably covers 90% of common assertions, which are normally of the form:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;assertEquals( 1, 1 )&lt;br /&gt;assertTrue( something )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Could there, should there, will there be more matchers and different types of assertions in the near future? My Magic 8 Ball says, "Rely on it".&lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Running in the IDE &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;Sweet runs in the IDE by piggybacking on the TestNG IDE plugins. Currently, you all you need to do is mix in the SweetTestNGAdapter trait into your test to get full IDE capability. Here, I modify the Hello World example to provide IDE support:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class HelloWorldSweet extends Sweet with SweetTestNGAdapter {&lt;br /&gt;&lt;br /&gt;  test("hello, world!"){&lt;br /&gt;    "hello, world!" mustBe "hello, world!"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's it!&lt;br /&gt;&lt;br /&gt;Note: There is a chance that I simple add this capability right into Sweet so that you don't have to mix in this trait at all, but there are some disadvantages. First, it would require that all users of Sweet also depend on TestNG. Secondly, the community is currently working on a common set of test interfaces that all test frameworks would implement. The hope that eventually all the IDEs (and other tools) would use these interfaces, and that any test framework implementing the API could run in the IDE. For now, I'll leave SweetTestNGAdapter as a trait, and hold out hope.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt; What's next for Sweet? &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;I plan to use Sweet somewhat as an experimental framework for ideas that are a bit too radical for ScalaTest. A staging grounds if you will. Here are some of the things in the works currently, or planned.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Making use of my scala-parallel project, I've already added a Sweet that allows all tests to be run in parallel.&lt;br /&gt;&lt;li&gt;I've added my concurrent programming test API in, so multi-threaded code can be testing very easily.&lt;br /&gt;&lt;li&gt;I plan eventually to add Actor testing API here. &lt;br /&gt;&lt;li&gt;Certain more as well.&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Why Sweet? &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;This is really two questions. Why did I write Sweet, and why should you use Sweet? &lt;br /&gt;&lt;br /&gt;As I explained, I want to use Sweet for experimental ideas. &lt;br /&gt;&lt;br /&gt;You should use Sweet if you're looking for something that is always up to date with the latest Scala builds, and tools. I understand that there's only a handful of people using the nightly builds, and with beta coming out, it won't really matter. But for now, I plan to build Sweet nightly. Also, it's Sweet, Dood. Come on! &lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Implementation &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;Given that it's only 99 lines, I might as well just list the entire implementation here. However, you can also find it at github. Below, I had to make some of the lines shorter so that they would fit in my blog, but I assure you, the actual implementation is 99 lines.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Sweet.scala&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;trait Sweet extends Assertions {&lt;br /&gt;&lt;br /&gt;  private[sweet] var tests = List[TestCase]()&lt;br /&gt;&lt;br /&gt;  case class TestCase(name: String, f: () =&gt; Unit) {&lt;br /&gt;    def apply(reporter: SweetReporter) {&lt;br /&gt;      try{&lt;br /&gt;        reporter(TestStarting(name))&lt;br /&gt;        f()&lt;br /&gt;        reporter(TestSucceeded(name))&lt;br /&gt;      }catch {&lt;br /&gt;        case t: SourAssertionException =&gt; {&lt;br /&gt;          reporter(TestFailed(name, t))&lt;br /&gt;        }&lt;br /&gt;        case t: Throwable =&gt; {&lt;br /&gt;          reporter(TestErrored(name, t))&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    override def toString = name&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def test(name: String)(f: =&gt; Unit) {&lt;br /&gt;    if (tests.map(_.name).contains(name)) println("duplicate test name: " + name)&lt;br /&gt;    tests = tests ::: List(TestCase(name, f _))&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def run(reporter: SweetReporter) {&lt;br /&gt;    tests.foreach(_(reporter))&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Assertions.scala&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;trait Assertions {&lt;br /&gt;&lt;br /&gt;  case class Equalizer(a:Any){&lt;br /&gt;&lt;br /&gt;    def mustBe(b:Any){ &lt;br /&gt;      if( ! a.equals(b) )toss(a + " did not equal " + b + " but should have") &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    def mustNotBe(b:Any) { &lt;br /&gt;      if( a.equals(b) ) toss(a + " must not equal " + b + ", but did") &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    def toss(message: String){ throw new SourAssertionException(message) }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  implicit def Any2Equalizer(a: Any) = Equalizer(a)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;SourAssertionException.scala&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;class SourAssertionException(message: String) extends RuntimeException(message)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;SweetFramework.scala (implementation of Framework from test-interfaces)&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;import org.scalatools.testing._&lt;br /&gt;&lt;br /&gt;class SweetFramework extends Framework {&lt;br /&gt;  def name = "Sweet"&lt;br /&gt;  def tests = Array(new TestFingerprint { &lt;br /&gt;    def superClassName = "sweet.Sweet"; def isModule = false&lt;br /&gt;  })&lt;br /&gt;  def testRunner(testLoader: ClassLoader, loggers: Array[Logger]) = { &lt;br /&gt;    new SweetRunner(testLoader, loggers)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;SweetRunner.scala  (implementation of Runnerfrom test-interfaces)&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;import org.scalatools.testing._&lt;br /&gt;&lt;br /&gt;class SweetRunner(val classLoader: ClassLoader, &lt;br /&gt;  loggers: Array[Logger]) extends Runner {&lt;br /&gt;&lt;br /&gt;  def run(testClassName: String, fingerprint: TestFingerprint, &lt;br /&gt;    eventHandler: EventHandler, args: Array[String]){&lt;br /&gt;    val testClass = Class.forName(testClassName, &lt;br /&gt;                     true, classLoader).asSubclass(classOf[Sweet])&lt;br /&gt;    val sweet = testClass.newInstance&lt;br /&gt;    val reporter = new MySweetReporter(eventHandler)&lt;br /&gt;    sweet.run(reporter)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  class MySweetReporter(eventHandler: EventHandler) extends &lt;br /&gt;    SweetReporter with NotNull{&lt;br /&gt;&lt;br /&gt;    def newEvent(tn: String, r: Result, e: Option[Throwable]) {&lt;br /&gt;      class MyEvent(val testName:String, &lt;br /&gt;                    val description:String, &lt;br /&gt;                    val result:Result, val error:Throwable) extends Event&lt;br /&gt;      eventHandler.handle(new MyEvent(tn, tn, r, e getOrElse null))&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    def apply(event: SweetEvent) {&lt;br /&gt;      event match {&lt;br /&gt;        case t: TestStarting =&gt; &lt;br /&gt;          loggers.foreach(_ info "Test Starting: " + t.testName)&lt;br /&gt;        case t: TestFailed =&gt; &lt;br /&gt;          newEvent(t.testName, Result.Failure, Some(t.reason))&lt;br /&gt;        case t: TestErrored =&gt; &lt;br /&gt;          newEvent(t.testName, Result.Failure, Some(t.reason))&lt;br /&gt;        case t: TestSucceeded =&gt; &lt;br /&gt;          newEvent(t.testName, Result.Success, None)&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;SweetReporter.scala&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;trait SweetReporter {&lt;br /&gt;  def apply(event: SweetEvent) &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;SweetEvent.scala&lt;/b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package sweet&lt;br /&gt;&lt;br /&gt;trait SweetEvent&lt;br /&gt;&lt;br /&gt;case class TestStarting(testName: String) extends SweetEvent&lt;br /&gt;case class TestFailed(testName: String, &lt;br /&gt;  reason:SourAssertionException) extends SweetEvent&lt;br /&gt;case class TestErrored(testName: String, &lt;br /&gt;  reason:Throwable) extends SweetEvent&lt;br /&gt;case class TestSucceeded(testName: String) extends SweetEvent&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt; Proof &lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;Here's proof that it's really just 99 lines:&lt;pre&gt;&lt;br /&gt;$ wc -l Assertions.scala \&lt;br /&gt;        SourAssertionException.scala \&lt;br /&gt;        Sweet.scala SweetEvent.scala \&lt;br /&gt;        SweetFramework.scala \&lt;br /&gt;        SweetReporter.scala \&lt;br /&gt;        SweetRunner.scala \&lt;br /&gt;        SweetTestNGAdapter.scala&lt;br /&gt;     14 Assertions.scala&lt;br /&gt;      2 SourAssertionException.scala&lt;br /&gt;     28 Sweet.scala&lt;br /&gt;      7 SweetEvent.scala&lt;br /&gt;      8 SweetFramework.scala&lt;br /&gt;      4 SweetReporter.scala&lt;br /&gt;     29 SweetRunner.scala&lt;br /&gt;      7 SweetTestNGAdapter.scala&lt;br /&gt;     99 total&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8836349795161961876?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8836349795161961876/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/11/introducing-sweet.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8836349795161961876'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8836349795161961876'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/11/introducing-sweet.html' title='Introducing Sweet'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8096641556378907534</id><published>2009-09-07T18:56:00.000-07:00</published><updated>2009-09-07T20:09:34.341-07:00</updated><title type='text'>Teaching Kids To Read Programs</title><content type='html'>&amp;nbsp;&lt;br /&gt;Today I taught my 8 year old son Jacy how to read some simple programs. I've been taking my time in picking what to teach him next about programming because I don't want to push him too hard. He get's frustrated sometimes and I have to be inventive in my teaching styles. I had an idea a few weeks back about a Simon Says related game that I thought would work, and tried it out today. &lt;br /&gt;&lt;br /&gt;The concept is quite simple, write out a simple if/else if/else statement centered around some particular value, have him read it, then say "Simon Says 'value is something'". Here's a very, very simple example. I write down this program and have him read it:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if x is 7 then jump&lt;br /&gt;else sit down&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then I say, "Simon Says x is 5!", and he would know to sit down.&lt;br /&gt;&lt;br /&gt;This worked, but as soon as I tried some more complicated programs he lost interest almost immediately. I don't give up easily though (or ever), and so I quickly came up with a new plan.&lt;br /&gt;&lt;br /&gt;He complained that he didn't understand, and I think the x was throwing him off just a little bit (even though I think he understood it, and he certainly did later on). So, I decided to use crayons instead, since they are more concrete. Also, I decided to make it a bit more fun by adding &lt;b&gt;pretending&lt;/b&gt; to the mix. I started over with the following program:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if color is red then PICK NOSE&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Of course, all boys like to pretend to pick their nose and puke. This program was much more fun to him and he was much more willing to read it. Like I said, I'm sure he understood the first programs just fine, but it has to be fun. &lt;br /&gt;&lt;br /&gt;Now, instead of saying "Simon Says Color is Red!", I had a box of crayons, and I'd simply pull a crayon out of the box. Less abstract, more concrete, more visible, more involved, more fun. This worked like a charm as he quickly pretended to pick his nose. &lt;br /&gt;&lt;br /&gt;Now that I had his full attention I was easily able to add in an else if statement that I had failed on earlier:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if color is red then PICK NOSE&lt;br /&gt;else if color is black then DIE&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This was easy for him. I'd pull a red crayon out of the box and he'd pretend to pick his nose. I'd pull a yellow crayon out and he'd realized the first two don't match, and he'd pretend to puke. I'd pull a black crayon out and he'd pretend to die. No big deal, but still very cool.&lt;br /&gt;&lt;br /&gt;Now I was able to add in some more interesting boolean logic:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if color is red or yellow then PICK NOSE&lt;br /&gt;else if color is black or blue then DIE&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This was also very trivial to him, as I expect anyone would imagine. But, I think all of this was necessary to get him back to the abstract forms that I started with. Now that I had the fun element, and the else ifs, I was able to go back to a program similar to the one I first failed on. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if x is 7 then PICK NOSE&lt;br /&gt;else if x * 10 is 20 then DIE x times&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This one is a lot more complicated than the any of the previous programs, but I felt that he did get it right from the start, he just needed the right encouragement (puking, picking, and dying, of course). Sure enough, he was ready for it. I said, "Simon Says 'x is 2'", and he pretended to die 2 times. He really did understand what x meant. However, I could see how some of this was a leap, and suggest progressing slower if needed. Here are some examples:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if x is 7 then PICK NOSE&lt;br /&gt;else if x is 5 then DIE 5 times&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;followed by:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if x is 7 then PICK NOSE&lt;br /&gt;else if x is 5 then DIE x times&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;then maybe something simpler than multiplication:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if x is 7 then PICK NOSE&lt;br /&gt;else if x + 1 is 3 then DIE x times&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There's a ton of room to be very creative here, and anyone can go at their very own pace, and each step can be broken down very slowly. This is all very exciting. My son is reading simple code! It won't be long at all before he's writing it. But, certainly it will be great to have him master reading it first. We do much more reading of code than writing as software pro's, and it's a skill that far too many students never learn. :( &lt;br /&gt;&lt;br /&gt;What's next? I'm not sure. Probably nested expressions. I think I could do that by introducing two colors like so:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if first color is red then &lt;br /&gt;  if second color is blue then PICK NOSE&lt;br /&gt;  else THROW TANTRUM&lt;br /&gt;else if first color is black or blue then DIE&lt;br /&gt;else PUKE&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Those of course could get far more complex. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;A few final notes to those who actually intend to try this with their kids.&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;He was very particular about having solid lines separating the if part from the else if parts, and the else parts. This helped him read the program a lot more clearly. I think a good deal of space would have done just as good. My initial programs were a bit bunched up, and he didn't like that at all. &lt;br /&gt;&lt;li&gt;He didn't really feel comfortable reading the program out loud to me. He would read it, and I knew he understood it, but if I asked him to read it out loud he got mad.&lt;br /&gt;&lt;li&gt;Along the same lines, if I asked him to explain how he got his answer he didn't want to tell me. I'd have to point to parts of the program and ask him if that's where he was, but it just didn't go very well at all. He knew the answers, just didn't like talking about it. Help understanding this phenomenon would be appreciated. &lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;Please let me know what you think!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8096641556378907534?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8096641556378907534/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/09/teaching-kids-to-read-programs.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8096641556378907534'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8096641556378907534'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/09/teaching-kids-to-read-programs.html' title='Teaching Kids To Read Programs'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6616271288869278430</id><published>2009-09-01T10:41:00.000-07:00</published><updated>2009-09-01T11:13:51.603-07:00</updated><title type='text'>Changes</title><content type='html'>Back in February I wrote that it was time for me to go back to &lt;a href="http://jackcoughonsoftware.blogspot.com/2009/02/grad-school.html"&gt;grad school&lt;/a&gt;. More or less, that time has come - I've decided to leave my job. I don't believe that this is a reflection of the quality of work at the job (or previous jobs), its just time for me to study languages. I would find my thoughts drifting constantly to languages while at work. I don't think it's fair to the teams I work with (as long as we're not working on languages), and I don't think it's good for me to be in a position that can't possibly allow me to work on everything I want. It's simply time.  &lt;br /&gt;&lt;br /&gt;I want to say thanks to Ken, Daniel, Evan, Mark and Marek at Simon and Schuster. It's a very good development team, and they were very good to me. I wish them absolutely the best of luck on all things in the future. While they all deserve credit, I think Daniel deserves extra credit for being an amazing, intelligent, patient boss. He probably gave me more slack than I earned, and I will never forget that. I would highly recommend the job for someone smart, but junior. It would be a position where you could learn from agile experts, as well as some fun technologies to work with, and a great team. &lt;br /&gt;&lt;br /&gt;As for whats next, I don't have a definite plan yet. I do have tentative plans A and B, and will announce them once things get settled. Unquestionably though, it will be working in languages and/or studying towards Phd. Hopefully it can involve my passion for teaching, especially &lt;a href="http://jackcoughonsoftware.blogspot.com/2009/05/teaching-functional-programming-to-kids.html"&gt;teaching children&lt;/a&gt;. I'm going to take a little bit of time off to spend extra time with my son before I get back into things. He deserves it.&lt;br /&gt;&lt;br /&gt;That's all. Bye.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6616271288869278430?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6616271288869278430/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/09/changes.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6616271288869278430'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6616271288869278430'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/09/changes.html' title='Changes'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5946712505582564238</id><published>2009-07-22T21:21:00.000-07:00</published><updated>2009-07-22T21:49:42.632-07:00</updated><title type='text'>What JVM Language Do You Write Tests In?</title><content type='html'>&amp;nbsp;&lt;br /&gt;At a recent NYC Scala meetup, I got chatted up and basically was asked the following: &lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;I know you've been writing multi-threaded testing API's in Scala, but we're still writing tests in Java, so do you know any good Java multi-threaded testing API's?&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;(As a matter of fact I do, but that's not the point of this post.)&lt;br /&gt;&lt;br /&gt;I couldn't help but immediately feel very bad. I feel genuinely sorry. Overwhelmingly sorry, in fact. Why? Because people in this world are still writing tests using Java. So, I'm calling on people to help me build an argument that can be used by people still trapped in a cave writing tests in Java. Most of the rest of this post will be a rant to start generating ideas, I'll try to formalize the argument by reading comments and then put it into another post. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Random Ranting To Generate Ideas&lt;/h4&gt;&lt;br /&gt;Scala and Groovy and JRuby and Jython and Clojure and so many more are by far better alternatives for testing on the JVM, and some of them have been for a long, long time. I started testing using Scala almost two years ago. I submit that if you can't get your organization to switch your testing language, you should leave. It's not even production code! &lt;br /&gt;&lt;br /&gt;You can still run your old tests anyway, even if just in your current runner. ScalaTest also gives you many alternatives for running all your old tests and new tests very easily in the same runner. &lt;br /&gt;&lt;br /&gt;You might argue that now you have to maintain two different code bases, two different languages for your tests. Honestly, I say &lt;a href="http://www.youtube.com/watch?v=0EcC3mj3oYw"&gt;Come On!&lt;/a&gt;. First, the new code tests will be far easier to maintain than any new tests you would have written in Java. Second, were professional software developers. If you can't manage one extra directory of code, you probably shouldn't be in this business. &lt;br /&gt;&lt;br /&gt;I think of more later.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Poll&lt;/h4&gt;&lt;br /&gt;Also, I'm creating a new poll. What JVM Language Do You Write Tests In? If you are reading this from a feed, you might have to click to get in: &lt;a href="http://jackcoughonsoftware.blogspot.com/"&gt;http://jackcoughonsoftware.blogspot.com/&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5946712505582564238?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5946712505582564238/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/07/what-jvm-language-do-you-write-tests-in.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5946712505582564238'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5946712505582564238'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/07/what-jvm-language-do-you-write-tests-in.html' title='What JVM Language Do You Write Tests In?'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-3015166214405867850</id><published>2009-07-04T21:30:00.000-07:00</published><updated>2009-07-04T23:07:20.029-07:00</updated><title type='text'>Testing Multi Threaded Scala Code</title><content type='html'>&amp;nbsp;&lt;br /&gt;Recently I did a (somewhat brute force) port of &lt;a herf="http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html"&gt;MultithreadedTC&lt;/a&gt;. All of this work stems directly from it, and I deserve basically no credit. However, I've done a bunch of interesting work around it, and I wanted to talk about it a bit. First I want to mention a few important points. &lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;We all know that the concurrency model used in Java has proven to be far too complex. About 5 people in the world can actually do it right. While this test api can be used to test code written in that style pretty easily, I'm not advocating writing anything in that style.&lt;br /&gt;&lt;li&gt;java.util.concurrent is still very useful. This api can be used to test j.u.c, Scala libraries that wrap it, and Scala libraries that use it.&lt;br /&gt;&lt;li&gt;This code will be in an upcoming release of ScalaTest, and (pending discussions) could make its way into Specs as well.&lt;br /&gt;&lt;li&gt;In the very near future this library should be very useful for testing actor code as well. Discussions and experimental implementations are ongoing. Expect a post about that very soon. Additionally, any Actor testing api will most definitely make its way into ScalaTest.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;Onward to an example! I'm going to dump it out, and explain after.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package scala.util.concurrent.locks&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;class PimpedReadWriteLockTest extends MultiThreadedSuite with &lt;br /&gt;  MustMatchers with MustBeSugar {&lt;br /&gt;  &lt;br /&gt;  val lock = new java.util.concurrent.locks.ReentrantReadWriteLock&lt;br /&gt;  import Implicits.RichReentrantReadWriteLock&lt;br /&gt;&lt;br /&gt;  thread("writer thread") {&lt;br /&gt;    waitForTick(1)&lt;br /&gt;    lock.write {tick mustBe 2}&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  thread("reader thread") { &lt;br /&gt;    lock.read { waitForTick(2) } }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  5.threads("reader thread("+_+")") {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  10 anonymousThreads {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;There's a huge amount of stuff going on here, and I'll do my best to explain it one line at a time. Also, for the purposes of understanding and clarity, I might intentionally leave out some details that would only confuse. Okay, go.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class PimpedReadWriteLockTest extends MultiThreadedSuite with &lt;br /&gt;  MustMatchers with MustBeSugar {&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;MultiThreadedSuite is a ScalaTest suite that contains all the goodies for multithreaded testing. Those goodies will be covered as we go. The matchers give me my must methods as seen in: tick mustBe 2. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  val lock = new java.util.concurrent.locks.ReentrantReadWriteLock&lt;br /&gt;  import Implicits.RichReentrantReadWriteLock&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Create a read/write lock, and then import the code to Pimp it. The rich version allows you to say lock.read{...}, and lock.write{...}. These do basically what you would imagine, but here's a shallow example for lock.read (its not exact, but you get the idea):&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  readLock.lock()&lt;br /&gt;  f()&lt;br /&gt;  readLock.unlock()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Creating a test Thread&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;  thread("writer thread") {&lt;br /&gt;    ...&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;On this line, a Thread is created with the name "writer thread". The thread method also returns the Thread, so you could assign it to a val and use it later on like so: val writer = thread("writer thread"){ ... } When the thread is started, it will run the code in between the curly brackets. I'll explain that code now.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Wait For Tick&lt;/h3&gt;&lt;br /&gt;Internally, MultiThreadedSuite maintains a clock. The clocks time starts at 0 and only advances when the following conditions hold:&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;&lt;b&gt;&lt;i&gt;ALL&lt;/i&gt;&lt;/b&gt; test threads are blocked.&lt;br /&gt;&lt;li&gt;At least one of those threads is waiting for the clock to tick.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;Why the last condition? If all threads are blocked, and no one is waiting for a clock tick, you have a deadlock! &lt;br /&gt;&lt;br /&gt;&lt;code&gt;waitForTick(n)&lt;/code&gt; blocks the current thread until time n is reached on the clock. If the current time on the clock is greater than n, then the thread does not block.&lt;br /&gt;&lt;br /&gt;Revisiting the code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  thread("writer thread") {&lt;br /&gt;    waitForTick(1)&lt;br /&gt;    lock.write {tick mustBe 2}&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The writer thread immediately blocks, waiting for tick 1. When time 1 is reached, the thread unblocks, and attempts to acquire the write lock. As we'll find out later shortly, it will be unable to do so just yet. That's the important part of this test.&lt;br /&gt;&lt;br /&gt;Next:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  thread("reader thread") { &lt;br /&gt;    lock.read { waitForTick(2) } }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Just as with the writer thread, this code creates a thread that will run during the test. When the thread runs it will acquire the read lock, and then wait for tick 2. This thread is guaranteed to get the read lock before the writer thread gets the write lock. How? Because the write thread immediately blocks waiting for tick 1. Recall that the clock doesn't tick until ALL threads are blocked. The reader thread doesn't block until it says waitForTick(2), at which point it already has the read lock. :)&lt;br /&gt;&lt;br /&gt;Now, the curious reader might wonder, why waitForTick(&lt;b&gt;2&lt;/b&gt;). Let me explain. The test notices that someone is waiting for a tick, and if all threads are blocked, it advances the clock. The thread waiting for a tick only unblocks if the current time is equal to the time its waiting for, otherwise it stays blocked. The test system sleeps for a little bit, wakes up, realizes that all threads are still blocked and someone is still waiting for a tick, and advances the clock again.&lt;br /&gt;&lt;br /&gt;With that explained, you can see that waitForTick(&lt;b&gt;2&lt;/b&gt;) is just shorthand for:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;waitForTick(1)&lt;br /&gt;waitForTick(2)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Breaking it up this way will help us analyze what is happening in the test, and I'll do that shortly. First though, lets take a look at the rest of the code.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Creating LOTS of threads&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;  5.threads("reader thread("+_+")") {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This code simply creates 5 threads. They all happen to be reader threads, and they are given the names "reader thread(1)" ... "reader thread(5)". It's a convenience method for creating many threads that you want to do exactly the same thing.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  10 anonymousThreads {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt; &lt;br /&gt;Creates 10 anonymous threads that also happen to be reader threads. They are actually given names, because all threads have names. The name is "Thread N", where N corresponds to the number of threads created so far. So these guys will actually get named something like Thread 7 ... Thread 16. I don't really recommend using anonymous threads, but the style is a little bit less verbose, so maybe someone will like it.&lt;br /&gt;&lt;br /&gt;Now, these methods return List[Thread]. I've chosen to ignore the return value here, but I can imagine cases where its very useful to have. The code could easily be rewritten:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  val readers: List[Thread] = 5.threads("reader thread("+_+")") {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;  val namelessReaders: List[Thread] = 10 anonymousThreads {&lt;br /&gt;    lock.read { waitForTick(2) }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Step by Step&lt;/h3&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;waitForTick(1) blocks the writer thread until tick 1 happens.&lt;br /&gt;&lt;li&gt;The reader threads all get the read lock.&lt;br /&gt;&lt;li&gt;waitForTick(1) blocks the reader thread until tick 1 happens. The writer thread is also waiting for tick 1. They will all get the read lock, and then all block waiting for tick 1. When they all get to that point, the clock is advanced, and the threads continue.&lt;br /&gt;&lt;li&gt;The write thread will wake up and try to grab the write lock, but it wont be able to, because the read lock is held 16 times over! It will block.&lt;br /&gt;&lt;li&gt;waitForTick(2) causes the reader threads to block waiting for tick 2. The clock can advance because all the reader threads are blocked waiting for tick 2, and the writer thread is blocked waiting for the write lock. &lt;br /&gt;&lt;li&gt;After tick 2, all the reader threads wake up. The writer thread is still blocked, waiting for the read lock.&lt;br /&gt;&lt;li&gt;The reader threads all give up the read lock in concert.&lt;br /&gt;&lt;li&gt;The writer thread finally gets the write lock. When it does, it makes sure that the current tick is 2. Indeed, it is.  &lt;br /&gt;&lt;/ol&gt; &lt;br /&gt;&lt;h3&gt;Summary&lt;/h3&gt;&lt;br /&gt;This should be the foundation of some really interesting work to come. I'll keep everyone informed.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-3015166214405867850?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/3015166214405867850/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/07/testing-multi-threaded-scala-code.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3015166214405867850'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3015166214405867850'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/07/testing-multi-threaded-scala-code.html' title='Testing Multi Threaded Scala Code'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-186093783112332543</id><published>2009-06-24T19:00:00.000-07:00</published><updated>2009-06-24T21:04:43.627-07:00</updated><title type='text'>Pimp vs Just Plain Fix my Library</title><content type='html'>&amp;nbsp;&lt;br /&gt;I assume most people familiar with Scala are familiar with &lt;a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766"&gt;Pimp My Library&lt;/a&gt;. It's just a fun and useful thing to be able to add a missing method onto an API, or to sometimes be able to treat an object like something else.&lt;br /&gt;&lt;br /&gt;As fun as it is (especially with the word Pimp), I kind of want to take the fun out of it a little bit. I want to say that its not just about adding that one great feature. Let me make this boring and annoying assertion: &lt;b&gt;Pimping is most useful for fixing crappy, terrible, miserable API&lt;/b&gt;. And while that's cool, and useful, it kind of sucks. There's so much terrible code out there that is a nightmare to work with. I feel like I shouldn't have to be fixing up other people's crap, but at least I can. &lt;br /&gt;&lt;br /&gt;Now for an example. Ever dealt with Java's ThreadGroup? Ever want to just get the Threads in a ThreadGroup? Sounds reasonable enough right? Holy Mother.... Couldn't be more wrong. Check out this gem that I lovingly stole straight from the Javadoc:&lt;br /&gt;&lt;br /&gt;&lt;A NAME="enumerate(java.lang.Thread[])"&gt;&lt;!-- --&gt;&lt;/A&gt;&lt;H3&gt;enumerate&lt;/H3&gt;&lt;PRE&gt;public int &lt;B&gt;enumerate&lt;/B&gt;(&lt;A HREF="../../java/lang/Thread.html" title="class in java.lang"&gt;Thread&lt;/A&gt;[]&amp;nbsp;list)&lt;/PRE&gt;&lt;DL&gt;&lt;DD&gt;Copies into the specified array every active thread in this &lt;br /&gt; thread group and its subgroups. &lt;br /&gt; &lt;p&gt;First, the &lt;code&gt;checkAccess&lt;/code&gt; method of this thread group is &lt;br /&gt; called with no arguments; this may result in a security exception. &lt;br /&gt; &lt;p&gt;An application might use the &lt;code&gt;activeCount&lt;/code&gt; method to &lt;br /&gt; get an estimate of how big the array should be, however &lt;i&gt;if the&lt;br /&gt; array is too short to hold all the threads, the extra threads are&lt;br /&gt; silently ignored.&lt;/i&gt;  If it is critical to obtain every active&lt;br /&gt; thread in this thread group and its subgroups, the caller should&lt;br /&gt; verify that the returned int value is strictly less than the length&lt;br /&gt; of &lt;tt&gt;list&lt;/tt&gt;.&lt;br /&gt; &lt;p&gt;Due to the inherent race condition in this method, it is recommended&lt;br /&gt; that the method only be used for informational purposes.&lt;br /&gt;&lt;DT&gt;&lt;B&gt;Parameters:&lt;/B&gt;&lt;DD&gt;&lt;CODE&gt;list&lt;/CODE&gt; - an array into which to place the list of threads.&lt;br /&gt;&lt;DT&gt;&lt;B&gt;Returns:&lt;/B&gt;&lt;DD&gt;the number of threads put into the array.&lt;br /&gt;&lt;/DD&gt;&lt;br /&gt;&lt;/DL&gt;&lt;br /&gt;WHAT?!? This API is just plain broken. It desperately needs fixing. All I want to do is get all the Threads in the Group...why should I have to deal with creating my own Array (and guessing the size), having it work entirely off side effects...And does it really return the number of threads it put into the Array? I'm afraid so. Broken. And does it really SILENTLY IGNORE things when there are too many threads to fit in the array!?! Horrible disaster. &lt;br /&gt;&lt;br /&gt;Not even that fun to fix to be honest, but the resulting code is far more manageable. But here's a solution. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object PimpedThreadGroup {&lt;br /&gt;  implicit def threadGroupToPimpedThreadGroup(tg: ThreadGroup) = {&lt;br /&gt;    new PimpedThreadGroup(tg)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class PimpedThreadGroup(threadGroup: ThreadGroup) {&lt;br /&gt;&lt;br /&gt;  def getThreads: List[Thread] = getThreads(true)&lt;br /&gt;&lt;br /&gt;  def getThreads(recursive: Boolean): List[Thread] = {&lt;br /&gt;    def getThreads(sizeEstimate: Int): Seq[Thread] = {&lt;br /&gt;      val ths = new Array[Thread](sizeEstimate)&lt;br /&gt;      if (threadGroup.enumerate(ths, recursive) == sizeEstimate) &lt;br /&gt;        getThreads(sizeEstimate +10)&lt;br /&gt;      else for (t &lt;- ths; if (t != null)) yield t&lt;br /&gt;    }&lt;br /&gt;    getThreads(threadGroup.activeCount() + 10).toList&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def filter(state: State): List[Thread] = {&lt;br /&gt;    getThreads.filter(_.getState == state)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def exists(state: State): Boolean = {&lt;br /&gt;    getThreads.exists(_.getState == state)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def any_threads_alive_? = {&lt;br /&gt;    getThreads.exists(t =&gt; t.getState != NEW &amp;&amp; t.getState != TERMINATED)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def any_threads_running_? = {&lt;br /&gt;    getThreads.exists(_.getState == RUNNABLE)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def any_threads_in_timed_waiting_? = {&lt;br /&gt;    getThreads.exists(_.getState == TIMED_WAITING)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Most important: def getThreads: List[Thread]. Now I can simply call threadGroup.getThreads and get back a List[Thread]. That's all I ever wanted. Is that too much to ask?&lt;br /&gt;&lt;br /&gt;I can also add something to simply treat a ThreadGroup as a List[Thread], if I want. I'm not sure I like this because it could get me into some trouble (and it always does recursive search), but I do like the power it gives - I can call any method on List directly on the ThreadGroup. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  implicit def ThreadGroupToList(tg:ThreadGroup): List[Thread] = {&lt;br /&gt;    new PimpedThreadGroup(tg).getThreads&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;By the way, I'm not going to explain it. I'm assuming you already know how it works (I might add a few more examples of how it can be used though, but I'm sure most people already understand). If you don't, you can click the Pimp My Library link above, or Google it. There's plenty out there.&lt;br /&gt;&lt;br /&gt;In conclusion, was this a bit of a rant? I guess. Here's what we should take away from this though: Pimp My Library is a very effective tool not just for adding nice things to API's, but fixing broken ones. If it's our duty to refactor our broken code, to always make our code better when we have to modify it, then it's just as much our duty to fix up API's. In this case, we just don't have the original source. Refactoring without source code. It's actually pretty awesome.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-186093783112332543?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/186093783112332543/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/pimp-vs-just-plain-fix-my-library.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/186093783112332543'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/186093783112332543'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/pimp-vs-just-plain-fix-my-library.html' title='Pimp vs Just Plain Fix my Library'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-271760590307083087</id><published>2009-06-14T21:12:00.000-07:00</published><updated>2009-06-14T22:06:52.572-07:00</updated><title type='text'>Scala MultithreadedTC Port</title><content type='html'>I haven't posted in quite a while now, but only because I've been working really hard. I asked Doug Lea if I could help him on his upcoming Scala concurrent data structures endeavor, especially on testing and to my surprise he sounded quite happy about the idea. He's going to get started sometime in July, and I figured from now until then would be a great time to get caught up on testing concurrent data structures, and have a nice framework in place before any code actually gets written. To that end, I've decided to port &lt;a href="http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html"&gt;MultithreadedTC&lt;/a&gt; to Scala.&lt;br /&gt;&lt;br /&gt;The reasons for doing so are quite simple - we can take advantage of Scala's flexible syntax, HOF's, yada yada...I don't think that that needs to be explained yet again. And, I don't think this particular example demonstrates something like, "but here those features are particularly valuable". The resulting code is definitely nicer than the original Java code, and that's simply all.&lt;br /&gt;&lt;br /&gt;Over the next few days I'll probably update this post giving more examples. I'll start with one tonight. Also, you can also learn more about how it all works by clicking the link above.&lt;br /&gt;&lt;br /&gt;I'll start with an example from the original Java code from the MultithreadedTC source, and I'll try to give a reasonable explanation of what is going on. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;1  class MTCTimedOffer extends MultithreadedTestCase {&lt;br /&gt;2   ArrayBlockingQueue&amp;lt;Object&amp;rt; q;&lt;br /&gt;3 &lt;br /&gt;4   @Override public void initialize() {&lt;br /&gt;5     q = new ArrayBlockingQueue&amp;lt;Object&amp;gt;(2);&lt;br /&gt;6   }&lt;br /&gt;7 &lt;br /&gt;8   public void thread1() {&lt;br /&gt;9     try {&lt;br /&gt;10      q.put(new Object());&lt;br /&gt;11      q.put(new Object());&lt;br /&gt;12&lt;br /&gt;13      freezeClock();&lt;br /&gt;14      assertFalse(q.offer(new Object(), 25, TimeUnit.MILLISECONDS));&lt;br /&gt;15      unfreezeClock();&lt;br /&gt;16&lt;br /&gt;17      q.offer(new Object(), 2500, TimeUnit.MILLISECONDS);&lt;br /&gt;18      fail("should throw exception");&lt;br /&gt;19    } catch (InterruptedException success){ assertTick(1); }&lt;br /&gt;20  }&lt;br /&gt;21&lt;br /&gt;22  public void thread2() {&lt;br /&gt;23    waitForTick(1);&lt;br /&gt;24    getThread(1).interrupt();&lt;br /&gt;25  }&lt;br /&gt;26}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This code tests the interactions of two threads. The second thread interrupts the first thread (line 24) as its attempting to offer an object to the queue on line 17. One challenge that the library means to solve is - How can we be sure that thread2 calls interrupt at the appropriate time? It does so by maintaining and internal metronome (or clock). The clock ticks forward only when all threads are blocked and at least one thread is waiting for the clock to tick. &lt;br /&gt;&lt;br /&gt;On line 23 thread2 waits for the clock to tick. Remember, the clock doesn't tick until all threads are blocked. So when does thread1 become blocked? Well, since the queue can only contain two elements, it becomes blocked on line 14, when it tries to offer a third object. However, in this case, we've frozen the clock, so the clock will not tick, and thread2 will continue to wait. &lt;br /&gt;&lt;br /&gt;Finally on line 17 thread1 becomes blocked offering a third object to the queue, and the clock is not frozen. Behind the scenes the framework sees that all threads are blocked, and indeed someone is waiting for the clock to tick (thread2). The clock ticks, and thread2 advances. He then interrupts thread1 using the getThread method. thread1 enters its catch block on line 19, checks to see that the clock has indeed reached 1, and everyone is happy. &lt;br /&gt;&lt;br /&gt;Sort of...&lt;br /&gt;&lt;br /&gt;There are a few things we can do better. Most importantly, of course - we can get rid of a lot of semicolons! Ok maybe that's not most important, but I really hate semicolons. Here's a more serious list of the deficiencies in the code above (oh and, its really not that bad at all). &lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;The call to getThread is not type safe at all, and break on a refactoring if you decided to rename a thread. How does that work anyway? Answer: the threads are named by the method names. On line 8 we have "public void thread1" and so we have a thread named thread1. This was originally done for a good reason - creating threads in Java is very verbose. This cleans that up a lot, at the minor price of some type safety.&lt;br /&gt;&lt;li&gt;When we freeze the clock we could easily forget to unfreeze it, leading to quite a bit of headache.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;There are more, and I will address them here, but let us focus on those two for now. I'll give the Scala equivalent first, then explain how I've addressed those issues. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;1 class MTCTimedOffer extends MultiThreadedSuite {&lt;br /&gt;2&lt;br /&gt;3   val q = new ArrayBlockingQueue[String](2)&lt;br /&gt;4&lt;br /&gt;5   val producer = thread{&lt;br /&gt;6     q put "w"&lt;br /&gt;7     q put "x"&lt;br /&gt;8&lt;br /&gt;9     withClockFrozen {&lt;br /&gt;10      q.offer("y", 25, TimeUnit.MILLISECONDS) mustBe false&lt;br /&gt;11    }&lt;br /&gt;12&lt;br /&gt;13    intercept[InterruptedException] {&lt;br /&gt;14      q.offer("z", 2500, TimeUnit.MILLISECONDS)&lt;br /&gt;15    }&lt;br /&gt;16&lt;br /&gt;17    tick mustBe 1&lt;br /&gt;18  }&lt;br /&gt;19&lt;br /&gt;20  thread{&lt;br /&gt;21    waitForTick(1)&lt;br /&gt;22    producer.interrupt()&lt;br /&gt;23  }&lt;br /&gt;24}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice that the code isn't much smaller, 24 vs 26 lines. I'm not touting a giant absurd improvement in any way. However, lets look at the issues above.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;On line 5 ( val producer = thread{ ) an actual Thread object is returned, and that thread can be referenced by any of the other threads in the system by name, in an intuitive, type safe way. I do this simply, by having the thread method take a HOF and wrapping that HOF in a Thread. Easy. Notice on line 22 the second thread references the producer thread directly.&lt;br /&gt;&lt;br /&gt;Also, If I don't feel like it, I don't have to assign the thread to a val, and I don't have to reference it anywhere. The Thread created in line 20 isn't really needed by anyone else, so it remains anonymous (behind the scenes it actually gets the name thread2, and can still be gotten using the getThread method seen above). &lt;br /&gt;&lt;li&gt;The second issue was a very simple one where we could forget to unfreeze the clock. Simple is ok, because all these simple fixes added up big in the long run, IMO. This issue is solved by using the withClockFrozen which appears on line 9. This is also a method that takes a function. It then does the work of freezing the clock for you, running the function, then unfreezing the clock. Simple, but effective.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;Ok, its really late, and I have to work tomorrow. But, expect this post to be updated regularly in the near future. I'll likely be working with Bill Venners and Eric T. on getting this stuff into ScalaTest and/or Specs, and DL on improving this stuff, and hopefully Bill Pugh, the original author. Any ideas, comments, improvements, etc would be greatly appreciated! I'll have the source code somewhere where people can see it very soon. Bye!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-271760590307083087?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/271760590307083087/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/scala-multithreadedtc-port.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/271760590307083087'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/271760590307083087'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/scala-multithreadedtc-port.html' title='Scala MultithreadedTC Port'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4032710692682806518</id><published>2009-06-01T08:51:00.000-07:00</published><updated>2009-06-01T13:00:51.006-07:00</updated><title type='text'>Comedy: Scala vs. Ruby vs. Objective C</title><content type='html'>&amp;nbsp;&lt;br /&gt;Please submit your favorite (or least favorite) language!&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(255, 0, 0);"&gt;Added: &lt;span style="color: rgb(255, 0, 0);"&gt;Java, Clojure, JavaScript&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Scala&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;this.computers = Array(&lt;br /&gt; Map("Name" -&gt; "MacBook", "Color"-&gt;"White"),&lt;br /&gt; Map("Name" -&gt; "MacBook Pro", "Color"-&gt;"Silver"),&lt;br /&gt; Map("Name" -&gt; "iMac", "Color"-&gt;"White"))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Ruby&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;self.computers = [&lt;br /&gt; {:Name=&gt;"MacBook", :Color=&gt;"White"},&lt;br /&gt; {:Name=&gt;"MacBook Pro", :Color=&gt;"Silver"},&lt;br /&gt; {:Name=&gt;"iMac", :Color=&gt;"White"}]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Objective C&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;NSDictionary *row1 =&lt;br /&gt; [[NSDictionary alloc] initWithObjectsAndKeys:&lt;br /&gt;   @"MacBook", @"Name", @"White", @"Color", nil];&lt;br /&gt;NSDictionary *row2 =&lt;br /&gt; [[NSDictionary alloc] initWithObjectsAndKeys:&lt;br /&gt;   @"MacBook Pro", @"Name", @"Silver", @"Color", nil];&lt;br /&gt;NSDictionary *row3 =&lt;br /&gt; [[NSDictionary alloc] initWithObjectsAndKeys:&lt;br /&gt;   @"iMac", @"Name", @"White", @"Color", nil];&lt;br /&gt;&lt;br /&gt;NSArray *array =&lt;br /&gt; [[NSArray alloc] initWithObjects: row1, row2, row3, nil];&lt;br /&gt;&lt;br /&gt;self.computers = array;&lt;br /&gt;&lt;br /&gt;[row1 release];&lt;br /&gt;[row2 release];&lt;br /&gt;[row3 release];&lt;br /&gt;[array release];&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Java&lt;/h3&gt;&lt;br /&gt;Assuming this field:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; Map&amp;lt;String, String&amp;gt;[] computers;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Then:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;Map[] maps = {&lt;br /&gt;     new HashMap(){{&lt;br /&gt;         put("Name", "MacBook");  &lt;br /&gt;         put("Color", "White");&lt;br /&gt;     }},&lt;br /&gt;     new HashMap(){{&lt;br /&gt;         put("Name", "MacBook Pro");&lt;br /&gt;         put("Color", "Silver");&lt;br /&gt;     }},&lt;br /&gt;     new HashMap(){{&lt;br /&gt;         put("Name", "iMac");     &lt;br /&gt;         put("Color", "White");&lt;br /&gt;     }}&lt;br /&gt; };&lt;br /&gt; this.computers = maps;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice you can't use generics with the array creation, and, 4 space indenting! Yeah!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Clojure&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;(def computers [&lt;br /&gt; {:Name "MacBook"}&lt;br /&gt; {:Name "MacBook Pro" :Color "Silver"}&lt;br /&gt; {:Name "iMac" :Color "White"}])&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;h3&gt;JavaScript&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;this.computers =&lt;br /&gt;[{'name':'MacBook', 'color':'White'},&lt;br /&gt;{'name':'MacBook Pro', 'color':'Silver'},&lt;br /&gt;{'name':'iMac', 'color':'White'}];&lt;br /&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4032710692682806518?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4032710692682806518/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/comedy-scala-vs-ruby-vs-objective-c.html#comment-form' title='22 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4032710692682806518'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4032710692682806518'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/06/comedy-scala-vs-ruby-vs-objective-c.html' title='Comedy: Scala vs. Ruby vs. Objective C'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>22</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5852438469434094787</id><published>2009-05-31T07:30:00.000-07:00</published><updated>2009-05-31T07:52:14.241-07:00</updated><title type='text'>Good Use Case for Named Arguments</title><content type='html'>&amp;nbsp;&lt;br /&gt;I found what I consider a really great use case for using keyword arguments. I'm sure there are tons of them, I just want to list this one.&lt;br /&gt;&lt;br /&gt;Here I have some code that I had in CPU Simulator that I was using to test a FlipFlopChain, which is essentially just an N Bit Memory (maybe I'll rename it that).&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    val data = AllGeneratorNumber(8)&lt;br /&gt;    val chain = FlipFlopChain(data, Generator.on)&lt;br /&gt;    ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice that the second parameter to FlipFlopChain is Generator.on. What is this parameter though? We have to navigate into FlipFlopChain just to find out that it represents the write bit. If we didn't have the source, we might have no idea.&lt;br /&gt;&lt;br /&gt;So I changed the code to make it more explicit, by declaring a writeBit val.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    val data = AllGeneratorNumber(8)&lt;br /&gt;    val writeBit = Generator.on&lt;br /&gt;    val chain = FlipFlopChain(data, writeBit)&lt;br /&gt;    ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that I never use the writeBit again in the test code, its just there to help the reader understand what that second parameter is.&lt;br /&gt;&lt;br /&gt;With keyword arguments, there is a much better solution:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;    val data = AllGeneratorNumber(8)&lt;br /&gt;    val chain = FlipFlopChain(data, writeBit=Generator.on)&lt;br /&gt;    ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Win!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5852438469434094787?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5852438469434094787/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/good-use-case-for-named-arguments.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5852438469434094787'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5852438469434094787'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/good-use-case-for-named-arguments.html' title='Good Use Case for Named Arguments'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5544435410931005490</id><published>2009-05-30T20:31:00.001-07:00</published><updated>2009-06-01T12:58:33.342-07:00</updated><title type='text'>Some Simple Scala Refactorings</title><content type='html'>&amp;nbsp;&lt;br /&gt;I constantly go back and tinker with my old Scala code, especially in my CPU Simulator project. When I'm in the old code I notice something that I haven't really noticed before - the code is still good. In a previous life when I wrote Java code, I'd go back and look at old code and want to throw up. Scala is so concise that this just doesn't happen. Yes, I do find room for improvement here and there, but overall I'm still really happy with the code (there was an exception, when I didn't know anything about functional programming, and refactored from imperative to functional...but that doesn't count). &lt;br /&gt;&lt;br /&gt;Anyway, I have a few refactorings that I wanted to mention.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Refactoring to Case Classes&lt;/h3&gt;&lt;br /&gt;I refactored all of my LogicGate classes to be case classes instead of regular classes. The reason? The code is just prettier. I'm not a huge fan of the new keyword in general, and I especially don't like it littering up my code. &lt;br /&gt;&lt;br /&gt;Old Code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class XorGate(inputA: PowerSource, inputB: PowerSource) &lt;br /&gt;  extends LogicGate {&lt;br /&gt;  val output: PowerSource = &lt;br /&gt;    new AndGate(&lt;br /&gt;      new OrGate(inputA, inputB), &lt;br /&gt;      new NandGate(inputA, inputB))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;New Code:&lt;pre&gt;&lt;br /&gt;case class XorGate(inputA: PowerSource, inputB: PowerSource) &lt;br /&gt;  extends LogicGate {&lt;br /&gt;  val output: PowerSource = &lt;br /&gt;    AndGate(OrGate(inputA, inputB), NandGate(inputA, inputB))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The difference is small, but I literally had hundreds of new calls littered throughout my code. Now, I could also mention the extra power that case classes give as well - nice toString, pattern matching, hash code and equals... I happened to not really be using most of those things in the CPU simulator, so I don't have an immediate example. Oh well. In my opinion/experience, favor case classes over regular classes.&lt;br /&gt;&lt;br /&gt;This does violates encapsulation somewhat though. Previously, inputA and inputB weren't accessible from outside the class. I can get around that easily enough by adding private to my vals:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class XorGate(private val inputA: PowerSource, &lt;br /&gt;                   private val inputB: PowerSource) &lt;br /&gt;  extends LogicGate {&lt;br /&gt;  val output: PowerSource = &lt;br /&gt;    AndGate(OrGate(inputA, inputB), NandGate(inputA, inputB))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now I'm not exposing those fields, I still have all the power mentioned above, and I don't have the pesky "new" statements hanging around.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Refactoring to Fewer Files&lt;/h3&gt;&lt;br /&gt;I noticed something a little unsettling. I had separate files LogicGate.scala, AndGate.scala, OrGate.scala, NandGate.scala NorGate.scala, XorGate.scala. One for each type of gate. Several files, and they were all very very small, less than 10 lines each, all with a common package statement, and similar imports. &lt;br /&gt;&lt;br /&gt;So I tried something - putting them all into one file. This is something I normally do by default now. I'm not sure when I started putting lots of classes into one file and not spreading them out...Anyway, in my opinion the result was a lot better. Instead of 6 files roughly 5-10 lines long, I have one file less than 40 lines long. I got rid of the redundant package and import statements. But most importantly, now I can see everything there is to know about my logic gates on the screen at one time.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package com.joshcough.cpu.gates&lt;br /&gt;&lt;br /&gt;import electric.{Relay, Inverter, Wire, PowerSource}&lt;br /&gt;&lt;br /&gt;object LogicGate{&lt;br /&gt;  implicit def logicGateToPowerSource( lg: LogicGate ): PowerSource = lg.output&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait LogicGate{&lt;br /&gt;  val inputA: PowerSource&lt;br /&gt;  val inputB: PowerSource&lt;br /&gt;  val output: PowerSource&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class AndGate(val inputA: PowerSource, &lt;br /&gt;  val inputB: PowerSource) extends LogicGate {&lt;br /&gt;  val output: PowerSource = Relay(inputA, Relay(inputB))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class NandGate(val inputA: PowerSource, &lt;br /&gt;  val inputB: PowerSource) extends LogicGate{&lt;br /&gt;  val output = new Wire&lt;br /&gt;  Inverter(inputA)--&gt;output&lt;br /&gt;  Inverter(inputB)--&gt;output&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class NorGate(val inputA: PowerSource, &lt;br /&gt;  val inputB: PowerSource) extends LogicGate{&lt;br /&gt;  val output: PowerSource = Inverter(inputB, Inverter(inputA))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class OrGate(val inputA: PowerSource, &lt;br /&gt;  val inputB: PowerSource) extends LogicGate{&lt;br /&gt;  val output = new Wire&lt;br /&gt;  inputA--&gt;output&lt;br /&gt;  inputB--&gt;output&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class XorGate(val inputA: PowerSource, &lt;br /&gt;  val inputB: PowerSource) extends LogicGate {&lt;br /&gt;  val output: PowerSource = &lt;br /&gt;    AndGate(OrGate(inputA, inputB), NandGate(inputA, inputB))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I know some people who have said they will never do this, never having more than one class in a file. I think that's wrong. When you have several small classes, seeing everything at once overrules most arguments. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;More&lt;/h3&gt;&lt;br /&gt;I probably should suck it up and turn my logic gates into actual functions at some point in the near future. That should provide some really interesting material on refactoring. Until then, cya.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5544435410931005490?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5544435410931005490/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/some-simple-scala-refactorings.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5544435410931005490'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5544435410931005490'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/some-simple-scala-refactorings.html' title='Some Simple Scala Refactorings'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2122822796117235776</id><published>2009-05-30T14:25:00.000-07:00</published><updated>2009-05-31T05:28:55.351-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='defaults'/><category scheme='http://www.blogger.com/atom/ns#' term='names'/><category scheme='http://www.blogger.com/atom/ns#' term='keyword parameters'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Simple Scala Keyword Parameters</title><content type='html'>Everything here is mostly intuitive, but I'm putting it here for personal reference. Should be helpful to a lot of people though. There's probably a whole ton of interesting cases I'm leaving out, and I'll try to keep this updated when I think of them. For now I'm covering Default Values, No Default Values, and Overloading. (Note, this doesn't come out until 2.8, I'm working off trunk)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt; Default Values&lt;/h3&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Define a class that takes two keyword args, name and lives, and provide default values.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; case class Cat(name:String="kitty", lives:Int=9)&lt;br /&gt;defined class Cat&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate the cat providing no arguments.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat&lt;br /&gt;res1: Cat = Cat(kitty,9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing both params, unnamed.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; Cat("Java", 1)&lt;br /&gt;res2: Cat = Cat(Java,1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing just the first param, unnamed.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; Cat("Scala")&lt;br /&gt;res3: Cat = Cat(Scala,9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing both params, named.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(name="newspeak", lives=20)&lt;br /&gt;res4: Cat = Cat(newspeak,20)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing both params in reverse order. (Only works if names the argument names are given.)&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(lives=20, name="newspeak")&lt;br /&gt;res5: Cat = Cat(newspeak,20)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing the first param, named.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(name="newspeak")&lt;br /&gt;res6: Cat = Cat(newspeak,9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing the second param, named.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; Cat(lives=4)                     &lt;br /&gt;res7: Cat = Cat(kitty,4)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing the first argument unnamed, and the second argument named!&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat("Lua", lives=1)&lt;br /&gt;res8: Cat = Cat(Lua,1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Attempt to instantiate a cat providing the first argument named, and the second argument unnamed. You can't do it! After you name a parameter, the parameters that follow must be named.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(name="Lua", 1)     &lt;br /&gt;&lt;console&gt;:7: error: positional after named argument.&lt;br /&gt;      new Cat(name="Lua", 1)&lt;br /&gt;                          ^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3&gt;No Default Values&lt;/h3&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Redefine class Cat without supplying default values. This means values &lt;i&gt;must&lt;/i&gt; be provided when instantiating a cat (more generically, calling a function).&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; case class Cat(name:String, lives:Int)&lt;br /&gt;defined class Cat&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing both params, unnamed.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; Cat("Java", 1)&lt;br /&gt;res9: Cat = Cat(Java,1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing both params, named.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(name="Douglas", lives=42)          &lt;br /&gt;res10: Cat = Cat(Douglas,42)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Attempt to instantiate a cat, not providing values for the arguments.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;console&gt;:7: error: not enough arguments for constructor Cat:&lt;br /&gt;(name: String,lives: Int)Cat, unspecified parameters:&lt;br /&gt;value name, value lives&lt;br /&gt;      new Cat&lt;br /&gt;      ^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3&gt;Overloading&lt;/h3&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Redefine the class, overloading the constructor.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; case class Cat(name:String="kitty", lives:Int=9){&lt;br /&gt;    | def this(name:String) = this(name, -54)&lt;br /&gt;    | }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat providing just the first argument, unnamed. Since the compiler does find a method with the exact signature (in this case - one String), it calls it.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat("Martin")&lt;br /&gt;res11: Cat = Cat(Martin,-54)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Here's a couple of other similar, and interesting cases. First, overload the constructor giving the argument a different name than the one defined in the primary constructor.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; case class Cat(name:String="kitty", lives:Int=9){&lt;br /&gt;    | def this(x:Int) = this("hello", x+99)   &lt;br /&gt;    | }&lt;br /&gt;defined class Cat&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat, using the keyword 'lives'. Since the overloading method uses the name x, and x!=lives, and the original constructor uses 'lives', that is the method that is invoked.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(lives=8)                                &lt;br /&gt;res12: Cat = Cat(kitty,8)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Instantiate a cat - same as the String overloading case above.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; new Cat(8)     &lt;br /&gt;res13: Cat = Cat(hello,107)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2122822796117235776?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2122822796117235776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/simple-scala-keyword-parameters.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2122822796117235776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2122822796117235776'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/simple-scala-keyword-parameters.html' title='Simple Scala Keyword Parameters'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2775141324203986629</id><published>2009-05-19T19:39:00.000-07:00</published><updated>2009-05-20T07:20:25.015-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='functional programming'/><category scheme='http://www.blogger.com/atom/ns#' term='teaching'/><title type='text'>Teaching Functional Programming To Kids</title><content type='html'>I started teaching some of the basic concepts of functional programming to my 8 year old son yesterday, and wanted to write a little about it. The wonderful thing about it is that kids really are ready to learn the concepts at a very young age. I'm not actually teaching him programming, just concepts, but when the time comes, he'll basically already know how to program.&lt;br /&gt;&lt;br /&gt;I have what I think is an absolutely perfect example. It's one that all parents and kids can identify with: The Dr. Seuss Star Belly Sneetch machine.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_CapVmQaDUgA/ShOE5GdJFsI/AAAAAAAAADE/xUuocqWrogs/s1600-h/285_top_10_list.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 167px;" src="http://3.bp.blogspot.com/_CapVmQaDUgA/ShOE5GdJFsI/AAAAAAAAADE/xUuocqWrogs/s400/285_top_10_list.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5337756099884422850" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;This is a simple machine that takes in a Sneetch without a star on its belly, and spits out a Sneetch with a star on its belly. I'm just going by memory here to say that I think kids can probably understand this concept at the age of 3. In this post I'm going to use this style to represent machines:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;               -----------&lt;br /&gt;              |           |  &lt;br /&gt; Sneetch ---&gt; |     *     | ---&gt; Star Bellied Sneetch&lt;br /&gt;              |           |&lt;br /&gt;               -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is the same as the actual picture above, but works for all cases since I don't have pictures for all the concepts I want to represent. &lt;br /&gt;&lt;br /&gt;In the Dr. Seuss book there is also the opposite machine that removes the star from a star bellied Sneetch.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;               -----------&lt;br /&gt; Star Bellied |           |  &lt;br /&gt; Sneetch -&gt;   |     -*    | ---&gt; Sneetch&lt;br /&gt;              |           |&lt;br /&gt;               -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;While that seems really simple, it's all we need to start teaching a wide range of concepts to kids. I started with this one, because of its similarity with the machines above (for all the things below, Jacy and I worked them out on a whiteboard. But, paper is just as good):&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt;           |           |  &lt;br /&gt; 10  ---&gt;  |     +5    | ---&gt; 15&lt;br /&gt;           |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here we have a machine that adds five to whatever you put into it. Very simple, very easy for kids to understand. It helps to run a few more inputs through (0, 10, a billion) just to let them know that the box doesn't just take 10 and give 15, it works with all numbers.&lt;br /&gt;&lt;br /&gt;After this one I followed up with another very easy one.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt;           |           |  &lt;br /&gt; 10  ---&gt;  |     -5    | ---&gt; 5&lt;br /&gt;           |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;At this point he pointed out, "Well it could be a divided by two machine instead." This was unexpected, and impressive, and at some point I'll talk about it further...but not yet. It was great to feel that he was understanding it though.&lt;br /&gt;&lt;br /&gt;Now that he was getting it, it was time to change things up just a little bit. I introduced the plus and minus machines, which take two inputs instead of one.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |     +     | ---&gt; 19&lt;br /&gt; 12  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 12  ---&gt;  |           |  &lt;br /&gt;           |     -     | ---&gt; 5&lt;br /&gt; 7   ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;These presented no challenge whatsoever. In fact (I guess rather surprisingly), nothing I taught him presented any sort of challenge. Next I introduced the biggest and smallest machines (which we programmers call max and min).&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |  Biggest  | ---&gt; 12&lt;br /&gt; 12  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |  Smallest | ---&gt; 7&lt;br /&gt; 12  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 10  ---&gt;  |           |  &lt;br /&gt;           |  Smallest | ---&gt; 10&lt;br /&gt; 10  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I guess he was a bit surprised when I showed him the last one. But, it only took showing him the answer once for him to fully understand.&lt;br /&gt;&lt;br /&gt;I then added an equals machine that spits out YES! if the two numbers are equal, and NO! if they aren't (true and false, obviously). This is different because now we were no longer working with numbers as the inputs and outputs.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |     =     | ---&gt; NO!&lt;br /&gt; 12  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |     =     | ---&gt; YES!&lt;br /&gt; 7   ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Simple, but effective.&lt;br /&gt;&lt;br /&gt;Now, Jacy and I have done considerable work with logic gates, and I wanted to show him how logic gates are really just like machines. I also taught him the word Function at this point, but didn't push it. Kids can relate to machines, not functions. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            ------------&lt;br /&gt; ON  ---&gt;  |            |  &lt;br /&gt;           |  AND GATE  | ---&gt; OFF&lt;br /&gt; OFF ---&gt;  |            |&lt;br /&gt;            ------------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            ------------&lt;br /&gt; ON  ---&gt;  |            |  &lt;br /&gt;           |  OR GATE   | ---&gt; ON&lt;br /&gt; OFF ---&gt;  |            |&lt;br /&gt;            ------------&lt;br /&gt;&lt;/pre&gt;&lt;pre&gt;&lt;br /&gt;            ------------&lt;br /&gt; ON  ---&gt;  |            |  &lt;br /&gt;           |  AND GATE  | ---&gt; ON&lt;br /&gt; ON  ---&gt;  |            |&lt;br /&gt;            ------------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;While the logic gate examples seem simple, it tied two worlds that we've been working on together very nicely.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Fun&lt;/h4&gt;&lt;br /&gt;My son has a really short attention span, and all the while I'm doing this I have to think of different ways to make it fun. If it's not fun, hes just going to go play video games. Rightfully so, video games are fun. There were a few ideas I tinkered with before settling on the Dr. Seuss machine. One was a monster that stuffs stuff into his mouth and then spits out the answer. I thought that one was kind of neat. The point is, if you plan on teaching your child, think of something fun they can relate to.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Combining Machines&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;I could sense we needed some more fun at this point, and we'd learned enough basic machines that I thought it would be great to start combining them. After trying this, I recommend starting with all alike boxes. We did something a little more complicated and I ended up going too fast, and fell back on this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;           -----------&lt;br /&gt; 7   --&gt;  |           |             -------&lt;br /&gt;          |     +     | --&gt; 19 --&gt; |       |&lt;br /&gt; 12  --&gt;  |           |            |       |&lt;br /&gt;           -----------             |       |&lt;br /&gt;                                   |   +   | --&gt; 39&lt;br /&gt;           -----------             |       |&lt;br /&gt; 10  --&gt;  |           |            |       |&lt;br /&gt;          |     +     | --&gt; 20 --&gt; |       |&lt;br /&gt; 10  --&gt;  |           |             -------&lt;br /&gt;           -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;After you get this first larger machine done, its pretty easy to add in more complicated machines. However, it might be good to wait until the next day, as Jacy was definitely getting it, but might have been getting a little fried. Here's an example though:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;           -----------&lt;br /&gt; 7   --&gt;  |           |             -------&lt;br /&gt;          |     +     | --&gt; 19 --&gt; |       |&lt;br /&gt; 12  --&gt;  |           |            |       |&lt;br /&gt;           -----------             |       |&lt;br /&gt;                                   |   =   | --&gt; NO!&lt;br /&gt;           -----------             |       |&lt;br /&gt; 10  --&gt;  |           |            |       |&lt;br /&gt;          |     +     | --&gt; 20 --&gt; |       |&lt;br /&gt; 10  --&gt;  |           |             -------&lt;br /&gt;           -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And obviously, change the 7 to an 8 and get a YES! Different kinds of boxes doing and spitting out different kinds of things. In essence, this is really all we do as programmers. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Types&lt;/h4&gt;&lt;br /&gt;Being a lover of static type systems, I also talked to him about types, by saying "kind(s) of things". For example, I asked him, "What kind of thing does this machine take in (or what kind of thing do you put into this machine)?"&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt;           |           |  &lt;br /&gt; 10  ---&gt;  |     +5    | ---&gt; 15&lt;br /&gt;           |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Answer: Number. I avoided Integer for now. What kind of thing does it spit out? Answer: Number.&lt;br /&gt;&lt;br /&gt;I then showed him this next example, which should arguably have a section of its own:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt;           |           |  &lt;br /&gt; D   ---&gt;  |     +5    | ---&gt; I&lt;br /&gt;           |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This machine looks exactly the same as the machine above, except you put Letters into it, and it spits out letters. We also did months. Both are interesting because they have to loop around. I didn't have to teach him that, he just got it.&lt;br /&gt;&lt;br /&gt;Then I introduced a formal notation for types:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt; 7   ---&gt;  |           |  &lt;br /&gt;           |     +     | ---&gt; 19&lt;br /&gt; 12  ---&gt;  |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;br /&gt;(Number,Number) -&gt; Number&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And introduced machines that change the type (he had seen it already, but only with YES! and NO! This, I think, is a better example):&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;            -----------&lt;br /&gt;           |           |  &lt;br /&gt; 5   ---&gt;  | To Letter | ---&gt; E&lt;br /&gt;           |           |&lt;br /&gt;            -----------&lt;br /&gt;&lt;br /&gt;Number -&gt; Letter&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;He understands the notation and can write it if I give him slots to fill in like this:&lt;br /&gt;&lt;br /&gt;______ -&gt; ______&lt;br /&gt;&lt;br /&gt;or&lt;br /&gt;&lt;br /&gt;(______, ______) -&gt; _______&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Things I don't know how to teach, Yet&lt;/h4&gt;&lt;br /&gt;I certainly didn't try to teach him anything about machines that take in machines and spit out machines. Also, some of my boxes were polymorphic, but I don't think I know how to explain that to him. &lt;br /&gt;&lt;br /&gt;For now, I think Jacy and I will just do this same stuff for a while, reinforcing it. I'm not sure what the best thing to teach him next is. Some of the stuff here I've skimped on writing up, and we actually spent more time on than it seems. &lt;br /&gt;&lt;br /&gt;Anyway, this was all really, really fun, for both of us.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2775141324203986629?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2775141324203986629/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/teaching-functional-programming-to-kids.html#comment-form' title='49 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2775141324203986629'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2775141324203986629'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/teaching-functional-programming-to-kids.html' title='Teaching Functional Programming To Kids'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_CapVmQaDUgA/ShOE5GdJFsI/AAAAAAAAADE/xUuocqWrogs/s72-c/285_top_10_list.jpg' height='72' width='72'/><thr:total>49</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8092570995813002854</id><published>2009-05-14T19:49:00.000-07:00</published><updated>2009-05-14T21:55:34.889-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala refactoring'/><title type='text'>Refactoring in Scala</title><content type='html'>Another really long post, but why not!&lt;br /&gt;&lt;br /&gt;My Lexer is now approaching 500 lines with roughly 350 lines of test code. Maybe that's still trivial, but it doesn't feel trivial. Maybe it doesn't feel trivial because it does a lot. Those 500 lines of code cover so many features. Yesterday night I started to add a bunch more features, and realized a few spots needed some heavy refactoring to achieve what I want. Here's what I wanted to add:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;New line support. Yes, my previous lexer could only lex one line at a time. Syntax errors indicated the offset, but not the line. A parser should know what line and file the token occurred in.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Better handling and testing of syntax errors.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Separate Scala lexing from Lexer core, providing a reusable Lexer framework for Lexing any language.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;I had a few other goals as well. I wanted to have the tests be much more organized, mostly arranging for testing individual Finders. So far, everything was lumped together in one giant test. I wanted to do a general cleanup of my Lexer trait, and extract the mutability from it. And as usual, I wanted to make sure things were nice and clean and short and readable. I have a few goals on my plate that I didn't get to as well. Comments, Strings, Chars, peeking at the next token without mutating. Some of that stuff might require the Finders to be away of a Context of some sort. I hope not. Also, maybe I could write a preprocessor to replace any comments with white space. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Multi Line Support&lt;/h4&gt;&lt;br /&gt;Anyway, lets get to the new line support. Like I said, the main goal was to have better syntax error support, knowing the line and the offset, not just the offset. But the parser needs to more information that just the offset, as well. In order to do this, I decided to introduce the idea of a CompilationUnit, which holds all the code. Previously, the Lexer just worked with a single array. &lt;br /&gt;&lt;br /&gt;Old code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait Lexer extends SyntaxErrorHander {&lt;br /&gt;  var chars: FunctionalCharArray&lt;br /&gt;  var currentIndex = 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;New code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait Lexer extends CompilationUnitWalker with SyntaxErrorHander {&lt;br /&gt;  var unit: CompilationUnit&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice something else important here. The old code held its chars and was responsible for handing its own mutation, and the mutation was a bit cluttered in with the lexing logic. It wasn't horrible, but not great. Now the mutation is all self contained in CompilationUnitWalker, who manages the current line and current character pointers. I'll save the listing for that trait until the end, as its where all the ugliness lives. But that's the good news, its no longer in Lexer. For now though, it helps to see the interface for that trait:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait CompilationUnitWalkerInterface {&lt;br /&gt;  var unit: CompilationUnit&lt;br /&gt;  def skipChar: Unit&lt;br /&gt;  def skipChars(i: Int): Unit&lt;br /&gt;  def skipLine: Unit&lt;br /&gt;  def currentLine: FunctionalCharArray&lt;br /&gt;  def currentLineNumber: Int&lt;br /&gt;  def currentOffset: Int&lt;br /&gt;  def eofReached_? : Boolean&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The finders need the current line, Tokens and errors need currentLineNumber and currentOffset, and the Lexer itself needs to know if it processed the whole file (eofReached_?), and needs commands to move in the array (the skip methods). Since some of this stuff wasn't in the original code, this was a refactoring and a feature add at the same time. No big deal though, just pointing it out. &lt;br /&gt;&lt;br /&gt;I'll show the remainder of the Lexer code in the next section. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Syntax Error Handling&lt;/h4&gt;&lt;br /&gt;We're a little bit closer to getting syntax errors with line numbers in them. I didn't show the SyntaxErrorHandler trait in the last post, but it was trivial. It just took a SyntaxError Token (which I've decided was stupid because SyntaxErrors are not tokens), and it just printed them out. Here's both now:&lt;br /&gt;&lt;br /&gt;Old code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait SyntaxErrorHander{&lt;br /&gt;  def syntaxError(error:SyntaxError):Unit = {&lt;br /&gt;    println(error)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;New code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait SyntaxErrorHander{&lt;br /&gt;  def syntaxError(unit: CompilationUnit, &lt;br /&gt;                  lineNumber: Int, offset: Int):Unit = {&lt;br /&gt;    println("Syntax Error(" + unit + ", line number:" + &lt;br /&gt;               lineNumber + ", offset:" + offset + ")")&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Not much different, but now the handler takes the CompilationUnit, and the line number and offset. Those are all we really need to handle the requirement. And I do it like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait AddToCompilationUnitSyntaxErrorHander extends SyntaxErrorHander{&lt;br /&gt;  override def syntaxError(unit: CompilationUnit, &lt;br /&gt;                           lineNumber: Int, offset: Int):Unit = {&lt;br /&gt;    super.syntaxError(unit, lineNumber, offset)&lt;br /&gt;    unit.syntaxError(lineNumber, offset)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The code for calling into the syntax error handler in the Lexer actually shaped up nicely as well:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait Lexer extends CompilationUnitWalker with SyntaxErrorHander {&lt;br /&gt;  var unit: CompilationUnit&lt;br /&gt;&lt;br /&gt;  def finders: List[FunctionalCharArray =&gt; Option[Lexeme]]&lt;br /&gt;&lt;br /&gt;  def nextToken: Token = {&lt;br /&gt;&lt;br /&gt;    // if we've already lexed the whole file, get the f out.&lt;br /&gt;    if (eofReached_?) return EOF(currentLineNumber)&lt;br /&gt;&lt;br /&gt;    // find all possible Lexemes&lt;br /&gt;    val matches = &lt;br /&gt;      finders.map(f =&gt; f(currentLine)).filter(_.isDefined).map(_.get)&lt;br /&gt;&lt;br /&gt;    // if we've found no lexemes, syntax error! adjust and try again.&lt;br /&gt;    if (matches.isEmpty) {&lt;br /&gt;      syntaxError(unit, currentLineNumber, currentOffset)&lt;br /&gt;      skipChar&lt;br /&gt;      return nextToken&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // the longest match found should be on top...i think...&lt;br /&gt;    val longestMatch = matches.sort(_.size &gt;= _.size).head&lt;br /&gt;&lt;br /&gt;    // deal with the best lexeme&lt;br /&gt;    handleLexeme(longestMatch)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def handleLexeme(lex: Lexeme) = lex match {&lt;br /&gt;    case NewLine =&gt; {&lt;br /&gt;      skipLine&lt;br /&gt;      nextToken&lt;br /&gt;    }&lt;br /&gt;    case WhiteSpace(_) =&gt; {&lt;br /&gt;      skipChar&lt;br /&gt;      nextToken&lt;br /&gt;    }&lt;br /&gt;    case lex =&gt; {&lt;br /&gt;      val indexOfLexeme = currentOffset&lt;br /&gt;      skipChars(lex.data.length)&lt;br /&gt;      Token(lex, currentLineNumber, indexOfLexeme)&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In the middle of the nextToken we check to see if matches is empty. If it is, we haven't found any Lexeme's and we call the syntaxError method with the current CompilationUnit (which we hold), and the currentLineNumber, currentOffset which we get from the walker. Done!&lt;br /&gt;&lt;br /&gt;Also notice the handleLexeme method at the end, because this completes the first requirement. When it creates a new Token, it passes the currentLineNumber as well. I'm still debating putting the CompilationUnit in the Token as well. Certainly a parser will know which unit its working on, but it might be helpful. I guess I'll wait til I start writing my parser to find out.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Refactoring Towards Reuse&lt;/h4&gt;&lt;br /&gt;Refactoring Towards Reuse was by far the most broad and complicated requirement/idea in the set - I thought. But as it turns out, it only took a few minutes total. All I had to do was move a few files, change a few names, honestly almost nothing. &lt;br /&gt;&lt;br /&gt;First, I created a package called scala under lex, created a Scala file called ScalaLexer.scala, and started pulling in anything that looked Scala specific. I ended up with this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait ScalaLexer extends Lexer with ScalaFinders with &lt;br /&gt;  AddToCompilationUnitSyntaxErrorHander&lt;br /&gt;&lt;br /&gt;trait ScalaFinders extends&lt;br /&gt;    ScalaCharFinders with NumberFinder with ScalaIdentifinder with&lt;br /&gt;    WhiteSpaceFinder with CaseClassFinder with CaseObjectFinder&lt;br /&gt;&lt;br /&gt;case object CaseClass  extends SimpleLexeme("case class")&lt;br /&gt;case object CaseObject extends SimpleLexeme("case object")&lt;br /&gt;&lt;br /&gt;object ScalaIOLBuiler extends IdentifierOnlyLexerBuilder{&lt;br /&gt;  def apply(cu: CompilationUnit) = {&lt;br /&gt;    new ScalaIOL{ var unit: CompilationUnit = cu }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;trait ScalaIOL extends IdentifierOnlyLexer with ScalaIdentifinder&lt;br /&gt;&lt;br /&gt;case class ScalaTwoPartIdentifinder(&lt;br /&gt;  w1: String, w2: String, l: Lexeme) extends&lt;br /&gt;  TwoPartIdentifinder(ScalaIOLBuiler, w1,w2,l)&lt;br /&gt;&lt;br /&gt;trait CaseClassFinder extends LexemeFinder {&lt;br /&gt;  override def finders =&lt;br /&gt;    super.finders ::: &lt;br /&gt;    List(ScalaTwoPartIdentifinder("case", "class", CaseClass).find _)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait CaseObjectFinder extends LexemeFinder {&lt;br /&gt;  override def finders =&lt;br /&gt;    super.finders ::: &lt;br /&gt;    List(ScalaTwoPartIdentifinder("case", "object", CaseObject).find _)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait ScalaCharFinders extends LexemeFinder {&lt;br /&gt;  override def finders = super.finders ::: CharFinders(&lt;br /&gt;      Underscore, Comma, Dot, Eq, Semi, Colon, LeftParen,&lt;br /&gt;      RightParen, LeftCurly, RightCurly, LeftBrace, RightBrace&lt;br /&gt;  )&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I also moved Identifinder into the Scala package as well, since it's Scala specific. All in all, I didn't have to do much. It's only about 30 lines of code and a lot of it can probably be cleaned up and reduced further. &lt;br /&gt;&lt;br /&gt;Now, if I wanted to lex Java I'd probably have to write a similar 30 lines of code, plus a JavaIdentifinder. I should do it, because then I'd find further areas for factoring out common code. &lt;br /&gt;&lt;br /&gt;So I guess in my next installment I'll do just that, and, I'll show the testing at that point too. The testing is coming along really nicely. At some point I plan to contrast this code with the real Scala lexer code, and the tests for it (I still have to find those).&lt;br /&gt;&lt;br /&gt;For now I'll give a quick snippit of the testing I did for handling multiple lines, but I'll wait to explain it:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait NewLineTests extends LexerTest{&lt;br /&gt;&lt;br /&gt;  test("new lines") {&lt;br /&gt;    checkCode("x,\ny",&lt;br /&gt;      (0,0) -&gt; Identifier("x"),&lt;br /&gt;      (0,1) -&gt; Comma,&lt;br /&gt;      (1,0) -&gt; Identifier("y"))&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  test("more new lines"){&lt;br /&gt;    checkCode("""x,&lt;br /&gt;    y,&lt;br /&gt;      z""",&lt;br /&gt;      (0,0) -&gt; Identifier("x"),&lt;br /&gt;      (0,1) -&gt; Comma,&lt;br /&gt;      (1,4) -&gt; Identifier("y"),&lt;br /&gt;      (1,5) -&gt; Comma,&lt;br /&gt;      (2,6) -&gt; Identifier("z"))&lt;br /&gt;  } &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's all for now. It's late.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8092570995813002854?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8092570995813002854/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/refactoring-in-scala.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8092570995813002854'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8092570995813002854'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/refactoring-in-scala.html' title='Refactoring in Scala'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2102637242405446021</id><published>2009-05-14T19:08:00.000-07:00</published><updated>2009-05-14T19:49:58.680-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala ruby refactoring'/><title type='text'>Scala over Ruby  - My Debate Ends</title><content type='html'>I've maintained posts about things I like in better about Scala and/or Ruby, but, it's time to put an end to the debate. I've been doing Ruby every day for almost 6 months now, and finally conclude that for me, it just doesn't feel nearly as nice as Scala. It's not ever close, to be blunt.&lt;br /&gt;&lt;br /&gt;My main reason? Refactoring. Over the years I've become very good at refactoring; I've actually been called a refactoring machine. I have &lt;i&gt;a lot&lt;/i&gt; of experience refactoring really, really terrible code. Yes, this sucks, I have a history of picking the wrong &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/back.html"&gt;job&lt;/a&gt;. Fortunately though, I also have some experience refactoring really nice code as well. The code that I'm working on now in Ruby is fairly new, and quite good. All the Scala code that I write is pretty good (room for improvement, but pretty good). &lt;br /&gt;&lt;br /&gt;I can refactor so easily in Scala with huge confidence and I can't do that in Ruby at all. In Ruby:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;It takes a long time to make major refactorings.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;I'm never fully confident in my refactorings and almost always get annoyed by runtime errors.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Sometimes the stack traces are all messed up and I can't figure out where my actual error is.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Most code you run into isn't going to have enough test coverage to help anyway.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;For all the preachers of TDD and instant feedback - tests untimately/inevitably take (far) longer than the compiler. So I really don't have the instant feedback I need.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;If you skip refactorings in Ruby because they are hard, your code becomes harder and harder to refactor. This goes for statically typed languages as well, but, it's a lot harder with Ruby, especially considering the points above.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Ad infinitum...&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;In my next post I'm going to cover a bunch of major refactorings I just did to my Lexer, and how easy it was.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2102637242405446021?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2102637242405446021/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/scala-over-ruby-my-debate-ends.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2102637242405446021'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2102637242405446021'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/scala-over-ruby-my-debate-ends.html' title='Scala over Ruby  - My Debate Ends'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8080812643741864567</id><published>2009-05-12T17:00:00.001-07:00</published><updated>2009-05-12T21:07:00.940-07:00</updated><title type='text'>A Scala Lexer</title><content type='html'>This is a really long post, but IM(not so)HO, its really fun!&lt;br /&gt;&lt;br /&gt;Sunday I decided, "I'm going to write my own Lexer for Scala", simply because I felt like it. I'm only about 8 hours in, but I've got a lot of functionality. &lt;i&gt;And&lt;/i&gt; its only about 300 lines of code so far. Now, that 300 lines doesn't cover nearly all of Scala. It's lacking XML handling, and comments, has limited support for numbers, and String literals, Unicode characters and error handling. But, it does have a lot of nice features including the ability to understand most (maybe all) identifiers, and operators.&lt;br /&gt;&lt;br /&gt;There are other really nice things about it as well. First, its very functional - it uses HOF's to recognize tokens and it's mostly immutable, with its mutable state isolated to one very small area. Second, the tests for it are simple end elegant. Third, its quite reusable, as I've managed to leverage several components from within itself.&lt;br /&gt;&lt;br /&gt;Before I get to the implementation, let me show how to use it. It can be done very simply at the command line. Example:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; import com.joshcough.compiler.lex._&lt;br /&gt;import com.joshcough.compiler.lex._&lt;br /&gt;&lt;br /&gt;scala&gt; val code = "x"                                    &lt;br /&gt;code: java.lang.String = x&lt;br /&gt;&lt;br /&gt;scala&gt; val lexer = new SimpleLexer(code) with Identifinder&lt;br /&gt;lexer: com.joshcough.compiler.lex.SimpleLexer with com.joshcough.compiler.lex.Identifinder = SimpleLexer(FunctionalCharArray([C@b6aea4))&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken                                   &lt;br /&gt;res0: com.joshcough.compiler.lex.Token = Token(Identifier(x),0)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken                                   &lt;br /&gt;res1: com.joshcough.compiler.lex.Token = EOF(1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In this code I create a Lexer only capable of recognizing identifiers by mixing in the trait Identifinder (and yes, that trait name is awesome). The "code" that I use here is simply the String x. When I ask the lexer for its tokens, it gives me back exactly what I'd expect, Token(Identifier(x),0), and EOF(1). This means it found the identifier x at offset 0, and found EOF at index 1. Simple, but obviously not yet very useful. Luckily, the identifier recognition is much more powerful. Let's see some more examples (From now on, where appropriate, I'll remove redundant type info from the output or replace it with "...", and simply indent the output):&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; lexer lexing "--&gt;"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(--&gt;),0)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; EOF(3)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer lexing "_ewrk_1212_adf435445_^^^"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(_ewrk_1212_adf435445_^^^),0)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Much better. But what happens if I pass in something that the lexer shouldn't understand?&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; lexer lexing "1"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; SyntaxError(0)&lt;br /&gt; res4: com.joshcough.compiler.lex.Token = EOF(1)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Not too terrible. "1" isn't a valid identifier and since this lexer only recognizes identifiers, it spits out "SyntaxError(0)", because it did not recognize the input starting at position 0. Now, this is actual System.out output. That's all you get by default. The actual Scala compiler simply adds an error to the Compilation unit with the offset. There really isn't much a lexer can do with errors. Later, I'll show how we can cache them off as well.&lt;br /&gt;&lt;br /&gt;The last lexer failed to recognize numbers. That's easy enough to fix. Simply mix in NumberFinder:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; val lexer = new SimpleLexer(code) with &lt;br /&gt;  Identifinder with NumberFinder   &lt;br /&gt;&lt;br /&gt;scala&gt; lexer lexing "123"                                                 &lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Number(123),0)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer lexing "--&gt;"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken   &lt;br /&gt; Token(Identifier(--&gt;),0)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now we can recognize identifiers and numbers. Next up we'll start recognizing all of these single characters: [ ] { } ( ) , . : _ = ; This as just as easy as the others - just mix in CharFinders&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt;lexer lexing "(x,y);"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken      &lt;br /&gt; Token(LeftParen,0)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(x),1)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Comma,2)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(y),3)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(RightParen,4)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Semi,5)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice that we haven't seen any white space yet. In fact, the lexer here isn't yet capable of handling white space. To do that - you guessed it - mix in WhiteSpaceFinder.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;scala&gt; val lexer = new SimpleLexer(code) with Identifinder with&lt;br /&gt; NumberFinder with CharFinders with WhiteSpaceFinder&lt;br /&gt;lexer lexing "( x , y );"&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken                                                                                            &lt;br /&gt; Token(LeftParen,0)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(x),2)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Comma,4)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Identifier(y),6)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(RightParen,8)&lt;br /&gt;&lt;br /&gt;scala&gt; lexer.nextToken&lt;br /&gt; Token(Semi,9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice that like any good lexer, this lexer simply skips over the white space, handing you the next actual token at its right location. &lt;br /&gt;&lt;br /&gt;There are a few more, such as RocketFinder (finds =&gt;), CaseClassFinder (finds "case class" and returns it as one Lexeme instead of two seperate identifiers), and CaseObjectFinder (which does exactly the same thing). But, I'm not going to show examples of their usage. I want to get to the implementation. &lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Lexer Implementation&lt;/h4&gt;&lt;br /&gt;Earlier I made claim that the Lexer was "mostly immutable". Of course, it has to be somewhat mutable to return something different to the parser on successive calls to nextToken. To do this, the Lexer uses a FunctionCharArray, which is just a very thin wrapper around Array[Char]. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class FunctionalCharArray(chars: Array[Char]) {&lt;br /&gt;  def skip(i: Int) = new FunctionalCharArray(chars.drop(i))&lt;br /&gt;  def size = chars.size&lt;br /&gt;  def nextChar: Option[Char] = get(0)&lt;br /&gt;&lt;br /&gt;  def get(index: Int): Option[Char] = {&lt;br /&gt;    if (chars.size &gt; index) Some(chars(index)) else None&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Taking a brief peek into the Lexer we find that its the FunctionCharArray that is mutated:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait Lexer extends SyntaxErrorHander {&lt;br /&gt;&lt;br /&gt;  var chars: FunctionalCharArray&lt;br /&gt;&lt;br /&gt;  var currentIndex = 0&lt;br /&gt;&lt;br /&gt;  def finders: List[FunctionalCharArray =&gt; Option[Lexeme]]&lt;br /&gt;&lt;br /&gt;  ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;There are a few other interesting bits here. The lexer also mutates its currentIndex. It puts the currentIndex into the Tokens when Lexemes are found. We'll see how that works just a bit later on. Most importantly though, is the fact that almost everything else runs through the Lexer's &lt;i&gt;finders&lt;/i&gt;. &lt;br /&gt;&lt;br /&gt;The finders are actually quite simple. Given a FunctionalCharArray, the finders return an Option[Lexeme]. They return Some(Lexeme...) if they found what they expected at the very beginning of the array, and None otherwise. The remainder of the array is simply ignored by the finder. A few simple examples should help.&lt;br /&gt;&lt;ul&gt;&lt;li&gt;The Identifinder returns Some(Identifier(x)) when its given the an array containing 'x' as its only element, and None if the first character in the array is a character that can't legally start an identifier.&lt;li&gt;The NumberFinder returns Some(Number(123)) when given this array: ['1', '2', '3', ' ', '+', ' ', '7']&lt;li&gt;The CharFinders only ever look at the first element in the array.&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;To fully demonstrate just how simple they are, we need to see some. Have at you!&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait WhiteSpaceFinder extends LexemeFinder {&lt;br /&gt;  override def finders = super.finders ::: List(findWhiteSpace _)&lt;br /&gt;&lt;br /&gt;  def findWhiteSpace(chars: FunctionalCharArray): Option[Lexeme] = {&lt;br /&gt;    chars.nextChar match {&lt;br /&gt;      case Some(' ') | Some('\t') | Some('\n') =&gt; Some(WhiteSpaceLex)&lt;br /&gt;      case _ =&gt; None&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The first thing to notice about this finder is that it immediately adds a finder method to it's super. This is what enabled us to keep mixing in finder after finder in the beginning of this post. &lt;br /&gt;&lt;br /&gt;The finder that it adds is its own findWhiteSpace method. As I explained, it takes a FunctionalCharArray and returns an Option[Lexeme]. In this case, it peeks at the top character in the array, and it that char is a space, tab or new line, it returns a Some with the Lexeme, and if its not, it returns None. Simple. &lt;br /&gt;&lt;br /&gt;That one is pretty trivial though, it only needs to look at one character. Let's take a look at one that's more involved. Here is a version of CaseClassFinder. It's not the exact implementation, but I've only changed it slightly to help demonstrate. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class IdentifierOnlyLexer(var chars: FunctionalCharArray) extends&lt;br /&gt;  Lexer with WhiteSpaceFinder with Identifinder&lt;br /&gt;&lt;br /&gt;trait CaseClassFinder extends LexemeFinder {&lt;br /&gt;  override def finders = super.finders ::: List(findCaseClass _)&lt;br /&gt;&lt;br /&gt;  def findCaseClass(chars: FunctionalCharArray) = {&lt;br /&gt;    if (chars.size &lt; 10) None&lt;br /&gt;    else {&lt;br /&gt;      val lexer = new IdentifierOnlyLexer(chars)&lt;br /&gt;&lt;br /&gt;      (lexer.nextToken, lexer.nextToken) match {&lt;br /&gt;        case (Token(Identifier("case"), _), &lt;br /&gt;              Token(Identifier("class"), _)) =&gt; {&lt;br /&gt;          Some(CaseClass)&lt;br /&gt;        }&lt;br /&gt;        case _ =&gt; None&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I love this example because it's small, but not trivial, and because it reuses components in the lex package. Before I explain, let's think about what a CaseClassFinder should do. If it see's "case", followed by "class" at the beginning of the array, then it should return the Lexeme CaseClass. Otherwise, it should return None. But, its more important to think about that in a slightly different way:&lt;br /&gt;&lt;br /&gt;If a CaseClassFinder finds &lt;i&gt;the Identifier "case"&lt;/i&gt; followed by &lt;i&gt;the Identifier "class"&lt;/i&gt;, then it should return CaseClass. &lt;br /&gt;&lt;br /&gt;Well, we already know how to find identifiers...it was the first thing I showed in this post! As it turns out, that's exactly how CaseClassFinder does it as well. It creates a new Lexer with its input, an IdentifierOnlyLexer (technically, it could fire up a Lexer with all the finders, but it's overkill). It then asks the Lexer for its first two tokens, and if those Tokens contain the Lexemes Identifier("case"), and Identifier("class") the it knows its found a case class. BAM!&lt;br /&gt;&lt;br /&gt;The Indentifinder and NumberFinder traits are too long to show here. I'll post a link to the codebase. &lt;br /&gt;&lt;br /&gt;Now, we have a few things to do to wrap up. I still need to show the how the Lexer itself actually uses the finders. And, the astute reader might have already realized that two finders might both return a Lexeme. For example, given the Array [':',':'], the Colon finder would return Colon, and the Identifinder would return Identifier(::). The Lexer handles this case easily. The real value &lt;i&gt;must&lt;/i&gt; be the longer of the two. Simple as that. Now lets take a look at all of Lexer.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Lexer Implementation (for real this time!)&lt;/h4&gt;&lt;pre&gt;&lt;br /&gt;1 trait Lexer extends SyntaxErrorHander {&lt;br /&gt;2  &lt;br /&gt;3   var chars: FunctionalCharArray&lt;br /&gt;4   var currentIndex = 0&lt;br /&gt;5&lt;br /&gt;6   def finders: List[FunctionalCharArray =&gt; Option[Lexeme]]&lt;br /&gt;7&lt;br /&gt;8   def nextToken: Token = {&lt;br /&gt;9 &lt;br /&gt;10    def skip(i: Int) {currentIndex += i; chars = chars.skip(i)}&lt;br /&gt;11&lt;br /&gt;12    val token = nextToken_including_whitespace_and_syntaxerror&lt;br /&gt;13&lt;br /&gt;14    token match {&lt;br /&gt;15      case SyntaxError(i) =&gt; {&lt;br /&gt;16        syntaxError(SyntaxError(i))&lt;br /&gt;17        skip(1)&lt;br /&gt;18        nextToken&lt;br /&gt;19      }&lt;br /&gt;20      case EOF(_) =&gt; token&lt;br /&gt;21      case Token(WhiteSpaceLex, _) =&gt; skip(1); nextToken&lt;br /&gt;22      case Token(lex, _) =&gt; skip(lex.data.length); token&lt;br /&gt;23    }&lt;br /&gt;24  }&lt;br /&gt;25&lt;br /&gt;26  private def nextToken_including_whitespace_and_syntaxerror = {&lt;br /&gt;27    if (chars.nextChar == None) EOF(currentIndex)&lt;br /&gt;28    else {&lt;br /&gt;29      val lexemesFound: List[Lexeme] = {&lt;br /&gt;30        finders.map(f =&gt; f(chars)).filter(_ match {&lt;br /&gt;31          case Some(t) =&gt; true&lt;br /&gt;32          case _ =&gt; false&lt;br /&gt;33        }).map(_.get)&lt;br /&gt;34      }&lt;br /&gt;35&lt;br /&gt;36      if (lexemesFound.size == 0) return SyntaxError(currentIndex)&lt;br /&gt;37    &lt;br /&gt;38      val lexemesSorted = &lt;br /&gt;39          lexemesFound.sort(_.data.size &gt;= _.data.size)&lt;br /&gt;40&lt;br /&gt;41      Token(lexemesSorted(0), currentIndex)&lt;br /&gt;42    }&lt;br /&gt;43  }&lt;br /&gt;44&lt;br /&gt;45  def lexing(s: String): Lexer = {&lt;br /&gt;46    lexing(new FunctionalCharArray(s.toCharArray))&lt;br /&gt;47  }&lt;br /&gt;48&lt;br /&gt;49  def lexing(cs: FunctionalCharArray): Lexer = {&lt;br /&gt;50    chars = cs; currentIndex = 0; this&lt;br /&gt;51  }&lt;br /&gt;52}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;First, look at the nextToken_including_whitespace_and_syntaxerror which starts on line 26. This method returns the best Token possible (like :: vs : ), but more importantly, it always returns a Token. It returns WhiteSpace and SyntaxError tokens as well. The calling method, nextToken, is the guy in charge of filtering those out, resetting, and continuing. But, well get to that in just a second. For now, lets enumerate the nextToken_including_whitespace_and_syntaxerror methods steps. &lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;The first thing it does is check if there are any characters left. If there are none, it simply returns EOF. Any more calls to nextToken will continue to return EOF until the Lexer gets new data (via the lexing methods).&lt;br /&gt;&lt;li&gt;It then calls all of its finders with the current array: finders.map(f =&gt; f(chars))&lt;br /&gt;&lt;li&gt;It then immediately filters the results, because its only interested in any finders that actually returned Some(Lexeme...), and not none. Of course.&lt;br /&gt;&lt;li&gt;At that point (line 36) it checks to see that someone actually found a Lexeme (if (lexemesFound.size == 0) return SyntaxError(currentIndex)). If no finders found anything, the we must have some unrecognized character in the input. Syntax Error!&lt;br /&gt;&lt;li&gt;On line 38 it sorts the Lexemes by size, aiming to get the largest. &lt;br /&gt;&lt;li&gt;Finally it returns the largest token (ignoring any other matches).&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;Now I'll explain the nextToken method, and then wrap up. &lt;br /&gt;&lt;br /&gt;The first action nextToken takes is to call the nextToken_including_whitespace_and_syntaxerror on line 12. With that token, it must make a decision.&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;If it receives a SyntaxError, then call the notify the syntax error handler of it, and in an attempt to reset/restart - move ahead one space in the input, and recur. &lt;br /&gt;&lt;li&gt;If it receives an EOF, just hand it over to the Parser, it should know what to do with it.&lt;br /&gt;&lt;li&gt;If it receives WhiteSpace, then also move ahead one space and recur. There might be a better strategy here (and/or for syntax errors), but this one is simple, and works ok.&lt;br /&gt;&lt;li&gt;Finally, if it gets a legitimate token, then move the entire array ahead by the length of the Lexeme that was found, and return the token. The next time nextToken is called, it should start at the new location, one character beyond the end of this token.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;Wrapping up, the way I've implemented this, I don't think it will be that difficult at all the add in missing features. XML will probably be a bear, just because. I guess I don't have String literal support at all, so I'll add that next, and Char literals too. They should be mostly straightforward. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;If you're actually still reading, awesome! Thanks! I hope you've learned something. You can find all the actual source code &lt;a href="http://code.google.com/p/compilerplayground/source/browse/#svn/trunk/src/main/scala/com/joshcough/compiler/lex"&gt;here&lt;/a&gt;. Not bad for about 8 hours huh?&lt;br /&gt;&lt;br /&gt;Oh BTW, my only two references for this were the Dragon Book (2 ed), and the Scala compiler itself. &lt;br /&gt;&lt;br /&gt;Bye!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8080812643741864567?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8080812643741864567/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/scala-lexer.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8080812643741864567'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8080812643741864567'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/scala-lexer.html' title='A Scala Lexer'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-9173650868355721162</id><published>2009-05-04T20:13:00.000-07:00</published><updated>2009-05-04T22:36:42.655-07:00</updated><title type='text'>Typed Lambda Calculus For Me (And Maybe You)</title><content type='html'>I'm reading chapter 10 of &lt;a href="http://www.cambridge.org/catalogue/catalogue.asp?isbn=9780521898850"&gt;Lambda-Calculus and Combinators&lt;/a&gt; by J. Roger Hindley and Jonathan P. Seldin, and I wanted to put down some notes. These notes are mostly for myself, much in the spirit of why I started this blog - to measure my own progress. However, since I know I have readers I'll write it in a way that people learn something. If people are interested in this though, since I'm already investing time in it, I'd be happy to do into more detail on the beginners stuff and/or some of the history behind this (I might just do it anyway). Also if anyone smarter than me finds any errors here, or has tips to explain it better, please do. Okay Go.&lt;br /&gt;&lt;br /&gt;In the book there is this nugget:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;(λx:p-&gt;ø-&gt;t.&lt;br /&gt; (λy:p-&gt;ø.&lt;br /&gt;   (λz:p.((x:p-&gt;ø-&gt;t z:p):ø-&gt;t (y:p-&gt;ø z:p):ø):t):p-&gt;t&lt;br /&gt; ):A&lt;br /&gt;):B&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You (the reader) are supposed to solve this for A and B. &lt;br /&gt;&lt;br /&gt;For those of you unfamiliar with lambda calculus, and/or typed lambda calculus, this is a lot easier than it looks. What I'll do here is try to explain the steps nice and slow, and then at the bottom maybe try to write this in Scala to demonstrate. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Explicit Type Information&lt;/h3&gt;&lt;br /&gt;Ok, the important thing here is that we are given a lot of information. Here's a list of the things we definitely know about the types in the statement above:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;x:p-&gt;ø-&gt;t&lt;/li&gt;&lt;br /&gt;&lt;li&gt;y:p-&gt;ø&lt;/li&gt;&lt;br /&gt;&lt;li&gt;z:p&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;In more detail:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;x is a function that takes a p and returns a function that takes an ø and returns a t.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;y is a function that takes a p and returns an ø&lt;/li&gt;&lt;br /&gt;&lt;li&gt;z is simply a p&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Or in Scala:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;val x:p=&gt;ø=&gt;t&lt;/li&gt;&lt;br /&gt;&lt;li&gt;val y:p=&gt;ø&lt;/li&gt;&lt;br /&gt;&lt;li&gt;val z:p&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;How do we know this? Well, that's basic typed lambda calculus. Here are a couple of very basic notes:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;The statement (λx:p-&gt;ø-&gt;t.M) is a function that takes an argument, x, which is of type p-&gt;ø-&gt;t. Arrows imply function types and hence x is a function that takes a p and returns a function that takes an ø and returns a t.&lt;/li&gt; &lt;br /&gt;&lt;li&gt;The return value of the function in this tiny example is M (above is much more complicated, but that's what were getting to).&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;h3&gt;Function Application&lt;/h3&gt;&lt;br /&gt;Now, using what we know about the types, and the rest of the statement, what else can we figure out? Hmm, I guess we should talk about function application, by looking at the innermost bit of the statement above. &lt;br /&gt;&lt;br /&gt;We see this: (x:p-&gt;ø-&gt;t z:p):ø-&gt;t, and this means we are calling the function x with the argument z. Remember that everything after the colons are simply types. Ignoring the types, we could just write (x z) which is basic function application in lambda calulus. In Scala this would be simply x(z). And what type does calling x yield? Not to beat it into your brain, but remember that x is a function that takes a p and returns a function that takes an ø and returns a t. Calling it with a p will yield a function that takes an ø and returns a t, or more simply ø-&gt;t.&lt;br /&gt;&lt;br /&gt;In the original statement, we had (x:p-&gt;ø-&gt;t z:p):ø-&gt;t, and this is correct, as I just explained. &lt;br /&gt;&lt;br /&gt;That isn't the only function application in the statement either. Right next to it we see (y:p-&gt;ø z:p):ø. Does this check out? Remember that y is a function that takes a p and returns an ø, and z is a p. Perfect. Applying y with argument x yields a ø. &lt;br /&gt;&lt;br /&gt;Now, that fact that I said "right next to it" is meaningful. Now that we've resolved the first two applications, we end up with another application! The result of the first application ((x:p-&gt;ø-&gt;t z:p):ø-&gt;t) was ø-&gt;t, and the result of the second was a ø, and these also match. Applying ø-&gt;t to an ø results in a t. And now we've finished this big inner statement: ((x:p-&gt;ø-&gt;t z:p):ø-&gt;t (y:p-&gt;ø z:p):ø):t. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Building Functions&lt;/h3&gt;&lt;br /&gt;Now that we've looked at the internal parts of the statement boiling it all down to a t, we can start to work our way outwords. Recall that λ is used to denote a function. λx:Int."hey" is a function that takes an Int (named x) and returns a String, "hey". Fully typed this would be (λx:Int."hey"):String&lt;br /&gt;&lt;br /&gt;Working our way one step outwards from our function applications, we have (λz:p.((x:p-&gt;ø-&gt;t z:p):ø-&gt;t (y:p-&gt;ø z:p):ø):t):p-&gt;t. Recall that we already determined the inner part to be a t. We can now thing of this as (λz:p.(some arbitrary t)):p-&gt;t. And that's correct. This is a function that takes a argument z of type p, and returns a t. Hence its type: p-&gt;t. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Solving for A&lt;/h3&gt;&lt;br /&gt;Lets take a look back to remember what were trying to solve. One thing we need to find is A:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;(λy:p-&gt;ø.&lt;br /&gt;   (λz:p.((x:p-&gt;ø-&gt;t z:p):ø-&gt;t (y:p-&gt;ø z:p):ø):t):p-&gt;t&lt;br /&gt; ):A&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We've already determined the inner part to be correct - its p-&gt;t. Using what we just learned about creating functions with λ, and what we learned about types earlier, we know that (λy:p-&gt;ø. whatever):A builds a function that takes an argument, y:p-ø. That is - an argument y of type function from p to ø. &lt;br /&gt;&lt;br /&gt;Additionally, this new function returns an A. But remember that the type of a function is not just its return type, it is (input type -&gt; output type). So A must be the functions input type (which we know to be the type of the argument y, or p-&gt;ø) -&gt; the functions return type (which is the return type of the inner statement, which we solved earlier to be p-&gt;t). &lt;br /&gt;&lt;br /&gt;A is (p-&gt;ø)-&gt;(p-&gt;t).&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Solving for B&lt;/h3&gt;&lt;br /&gt;To Solve for B, we do &lt;i&gt;exactly&lt;/i&gt; what we did solving for A.&lt;br /&gt;&lt;br /&gt;Recall:&lt;br /&gt;&lt;pre&gt;(λx:p-&gt;ø-&gt;t.&lt;br /&gt; (λy:p-&gt;ø.&lt;br /&gt;   (λz:p.((x:p-&gt;ø-&gt;t z:p):ø-&gt;t (y:p-&gt;ø z:p):ø):t):p-&gt;t&lt;br /&gt; ):A&lt;br /&gt;):B&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Or:&lt;br /&gt;&lt;pre&gt;(λx:p-&gt;ø-&gt;t.whatever:A):B&lt;/pre&gt;&lt;br /&gt;Clearly the first half of B (the input type) is (p-&gt;ø-&gt;t). The output type is the type of whatever, which (from looking just above) is A. &lt;br /&gt;&lt;br /&gt;So B is (p-&gt;ø-&gt;t)-&gt;A&lt;br /&gt;&lt;br /&gt;And fully expanded:&lt;br /&gt;&lt;br /&gt;B is (p-&gt;ø-&gt;t)-&gt;(p-&gt;ø)-&gt;(p-&gt;t)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Formal Listing&lt;/h3&gt;&lt;br /&gt;This came directly from the book. I'm not sure if I can even legally put this all here. If I hear that I can't, I'll immediately take it down. All the information here is explained in detail above.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;x:p-&gt;o-&gt;t     z:p             y:p-&gt;o     z:p&lt;br /&gt;-----------------            ---------------&lt;br /&gt;     (xz):o-&gt;t                      (yz):o&lt;br /&gt;--------------------------------------------&lt;br /&gt;                (xy(yz)):t      &lt;br /&gt;           -----------------------&lt;br /&gt;            (λx:p.(xy(yz))t):p-&gt;t&lt;br /&gt;-----------------------------------------------&lt;br /&gt;(λy:p-&gt;o((λx:p.(xy(yz))t)p-&gt;t)): (p-&gt;o)-&gt;(p-&gt;t)&lt;br /&gt;------------------------------------------------&lt;br /&gt;(λx:p-&gt;o-&gt;t ((λy:p-&gt;o((λx:p.(xy(yz))t)p-&gt;t)): &lt;br /&gt;  (p-&gt;o)-&gt;(p-&gt;t))): (p-&gt;o-&gt;t)-&gt;(p-&gt;o)-&gt;(p-&gt;t)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;The Scala Code To Prove It&lt;/h3&gt;&lt;pre&gt;&lt;br /&gt;trait Lambda {&lt;br /&gt;  type p&lt;br /&gt;  type ø&lt;br /&gt;  type t&lt;br /&gt;  type A = (p=&gt;ø)=&gt;(p=&gt;t)&lt;br /&gt;  type B = (p=&gt;ø=&gt;t)=&gt;A&lt;br /&gt;&lt;br /&gt;  val f:B = {(x: p =&gt; ø =&gt; t) =&gt; {(y: p =&gt; ø) =&gt; {(z: p) =&gt; {(x(z)(y(z)))}}}}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-9173650868355721162?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/9173650868355721162/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/typed-lambda-calculus-for-me-and-maybe.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9173650868355721162'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9173650868355721162'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/05/typed-lambda-calculus-for-me-and-maybe.html' title='Typed Lambda Calculus For Me (And Maybe You)'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-523934206295313877</id><published>2009-04-25T22:53:00.000-07:00</published><updated>2009-04-25T23:06:32.561-07:00</updated><title type='text'>Scala Testing Presentation Outline</title><content type='html'>Here's the outline for my upcoming presentation on Scala and Testing. It's a bit ambitious, and I know I won't get through it all, but that's okay.  If there's anything glaringly missing, now is the last chance to let me know. It also seems like this could be the start of something bigger, like a short book called something like, "Scala Testing for Java Developers"...maybe. However, the talk is only geared toward Java developers for the first few minutes or so.&lt;br /&gt;&lt;br /&gt;Without further ado:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;1) The prereqs ... Just Java code&lt;br /&gt;        a) "Production" code&lt;br /&gt;          - A simple List interface&lt;br /&gt;          - An ugly LinkedList implementation&lt;br /&gt;        b) Testing Java with Java&lt;br /&gt;          - JUnit&lt;br /&gt;          - Testng&lt;br /&gt;&lt;br /&gt;2) The basics ... Testing Java code with Scala&lt;br /&gt;        a) JUnit with Scala&lt;br /&gt;         - JUnit3 (test, setup/teardown)&lt;br /&gt;         - JUnit4 Annotations&lt;br /&gt;        b) TestNG with Scala&lt;br /&gt;         - @Test&lt;br /&gt;         - @DateProviders&lt;br /&gt;         - All Annotations available&lt;br /&gt;&lt;br /&gt;3) The basics ... More testing Java with Scala - Intro to ScalaTest&lt;br /&gt;        a) Suite&lt;br /&gt;         - test methods&lt;br /&gt;         - assert with ===&lt;br /&gt;         - expect(x){}&lt;br /&gt;         - intercept&lt;br /&gt;        b) BeforeAndAfter&lt;br /&gt;        c) TimedTest (displays time information for each class and test ran)&lt;br /&gt;        d) TestNGSuite&lt;br /&gt;         - decorate original TestNG test from step 3, "with TestNGSuite"&lt;br /&gt;         - run in both runners&lt;br /&gt;&lt;br /&gt;4) Scala extending/implementing Java classes/interfaces&lt;br /&gt;        a) ScalaLinkedList (simple extention of Java LinkedList class)&lt;br /&gt;        b) ScalaMutableList (ugly impementation of simple List interface)&lt;br /&gt;&lt;br /&gt;5) Testing Scala with Scala&lt;br /&gt;        a) Briefly redo #4 - but by testing the new Scala code. &lt;br /&gt;        b) minor intermission - Can we backtrack and test the new Scala code with Java?&lt;br /&gt;&lt;br /&gt;6) A nicer, Functional List implemention in Scala&lt;br /&gt;&lt;br /&gt;7) Testing Scala with Scala&lt;br /&gt;        a) FunSuite&lt;br /&gt;          -(including HOF's for those who don't know...maybe?)&lt;br /&gt;          -explain how tests methods work&lt;br /&gt;&lt;br /&gt;8) Advanced ScalaTest&lt;br /&gt;        a) ScalaTest matchers (in a FunSuite)&lt;br /&gt;        b) Overview of OOTB matchers&lt;br /&gt;          -String, List, Hash, Option matchers, etc.&lt;br /&gt;        c) Combining matchers with and/or&lt;br /&gt;        d) Extending ScalaTest matchers - Creating your own matchers&lt;br /&gt;&lt;br /&gt;9) Specs&lt;br /&gt;        a) Specifications&lt;br /&gt;        b) Matchers&lt;br /&gt;        c) Extending Specs matchers - Creating your own matchers&lt;br /&gt;&lt;br /&gt;10) Mocking in Scala (via Specs)&lt;br /&gt;        a) Mockito&lt;br /&gt;        b) JMock&lt;br /&gt;&lt;br /&gt;11) ScalaCheck (via ScalaTest Checkers)&lt;br /&gt;        a) Properties&lt;br /&gt;        b) Generators&lt;br /&gt;        c) Arbitrary Magic&lt;br /&gt;&lt;br /&gt;12) Ant&lt;br /&gt;        a) ScalaTest&lt;br /&gt;        b) JUnit Scala and Java run together&lt;br /&gt;        c) Specs runs as JUnit&lt;br /&gt;        d) TestNG Scala and Java run together&lt;br /&gt;&lt;br /&gt;13) Scala Frameworks Interoperability&lt;br /&gt;        a) ScalaTest and Specs&lt;br /&gt;        b) ScalaTest and ScalaCheck&lt;br /&gt;        b) Specs and ScalaCheck&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-523934206295313877?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/523934206295313877/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/scala-testing-presentation-outline.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/523934206295313877'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/523934206295313877'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/scala-testing-presentation-outline.html' title='Scala Testing Presentation Outline'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5260809863260764637</id><published>2009-04-19T18:18:00.001-07:00</published><updated>2009-04-19T18:30:12.956-07:00</updated><title type='text'>IntelliJ Now Supports ScalaTest</title><content type='html'>IntelliJ 8 now has support for ScalaTest (at least as of build 9805). I believe it comes in via the Scala plugin. It works, but, when I right clicked on my test class I expected to see a run option for ScalaTest and I didn't, which stinks. Not seeing it also made me think it just didn't work. It does.&lt;br /&gt;&lt;br /&gt;To run a ScalaTest test in IntelliJ, you have to add a run configuration. Most Intellij users probably know how to do this, but for those who don't, here are the steps.&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Click "Edit Configurations" in the Run menu dropdown (right next to the green play arrow).&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Click the + button to add a new run configuration. This brings up a dropdown containing different runners.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;ScalaTest is in the list, choose it.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Fill in the classname of your test by typing it, or selecting the "..." button to bring up the class finder dialog.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Click ok.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Run!&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;Thanks IntelliJ Scala guys! Now if you can only get that right click thing working...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5260809863260764637?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5260809863260764637/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/intellij-now-supports-scalatest.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5260809863260764637'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5260809863260764637'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/intellij-now-supports-scalatest.html' title='IntelliJ Now Supports ScalaTest'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6783152482604372285</id><published>2009-04-19T11:46:00.000-07:00</published><updated>2009-04-19T13:08:23.646-07:00</updated><title type='text'>Quotes</title><content type='html'>&lt;h4&gt;Quote from &lt;a href="http://gbracha.blogspot.com/"&gt;Gilad Bracha&lt;/a&gt;&lt;/h4&gt;&lt;blockquote&gt;&lt;span style="font-style: italic;"&gt;"Tangent: Yes, I did spend ten years at Sun. A lot of it was spent arguing that Java was not the final step in the evolution of programming languages. I guess I’m just not very persuasive."&lt;/span&gt;&lt;/blockquote&gt;&lt;br /&gt;Gilad is one of my heroes. The work he's doing on Newspeak seems very, very promising.&lt;br /&gt;&lt;br /&gt;Sun totally failed in ignoring him. I remember when he left he posted an unflattering blog about Sun, about how he felt that he couldn't get anything done there. He was very frustrated. I'm very glad to feel like I have &lt;a href="http://jackcoughonsoftware.blogspot.com/2009/02/nyse-new-york-scala-enthusiasts.html"&gt;something in common&lt;/a&gt; with such a smart guy.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Quote from &lt;a href="http://www.microsoft.com/presspass/exec/techfellow/hejlsberg/default.mspx"&gt;Anders Hejlsberg&lt;/a&gt;&lt;/h4&gt;From &lt;a href="http://oreilly.com/catalog/9780596515171/"&gt;Masterminds of Programming&lt;/a&gt;, which is (so far) an absolutely fabulous book: &lt;blockquote&gt;&lt;span style="font-style: italic;"&gt;"I think to be really good at something, you have to be passionate about it too. That's something you can't learn. That's just something that you have, I think. I got into programming not because I wanted to make lots of money or because someone told me to. I got into it because I just got totally absorbed by it. You just could not stop me. I had to write programs. It was the only thing I wanted to do. I was very, very passionate about it.&lt;br /&gt;&lt;br /&gt;You have to have that passion to get really good at something, because that makes you put in the hours, and the hours are the real key. You need to put in a lot of work."&lt;/span&gt;&lt;/blockquote&gt;&lt;br /&gt;Anyone who knows me well knows that this describes me exactly. I particularly like, "You just could not stop me. I had to write programs, It was the only thing I wanted to do." I guess I have an important quality in common with another of my heroes. For some childish reason, I'm very excited about this.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Quote from Bill Venners&lt;/h4&gt;&lt;blockquote&gt;&lt;span style="font-style: italic;"&gt;"I charge $1 for each paren, and $598 for knowing where to put them!"&lt;/span&gt;&lt;/blockquote&gt;&lt;br /&gt;'Nuff said!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6783152482604372285?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6783152482604372285/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/quotes.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6783152482604372285'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6783152482604372285'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/quotes.html' title='Quotes'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7143522262460311424</id><published>2009-04-17T12:07:00.000-07:00</published><updated>2009-04-17T17:57:09.979-07:00</updated><title type='text'>Tests and Booleans and Matchers</title><content type='html'>I was working with the new ScalaTest matchers API recently when I came across something that made me think (I usually don't think). I had something simple like:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;Nil.empty must be(true)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This seems harmless enough, but when I made it fail intentionally the error message I got was something reasonably similar to:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;Expected true but got false.&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This obviously isn't a very good error message, and I was thinking at first the maybe we should provide the user API to provide their own error message. Something like so:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;Nil.empty must be(true, "expected Nil to be empty, but it wasn't!")&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This also seems harmless enough. However, I talked this over with Bill Venners and in this case there is a way to do it using symbols and reflection that gives better error messages:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;Nil must be('empty)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;If this fails, it will give a nice error message like:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;Nil was not empty&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This is ok, but type safety people will scream, and they'd probably be right. And, does this work in all cases and can we always get good error messages? I think no. Let me explain why.&lt;br /&gt;&lt;br /&gt;What if we have an object that has a method that takes an argument and returns a boolean like this theoretical surroundedBy method that could exist on String:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;def surroundedBy( s: String ) = startsWith(s) &amp;amp;&amp;amp; endsWith(s)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;We can't use the symbol form here because the method takes a parameter. So what can we do? If we go back to the original form then we are back to our original bad error message.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;"htth".surroundedBy( "h" ) must be (true)&lt;br /&gt;"http".surroundedBy( "h" ) must be (false)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Do we have any other options? Yes (with caveats as well). But first lets think about what we'd really like to write here. If we were writing pure English, it would be this:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;"htth" must be surrounded by "h"&lt;br /&gt;"http" must not be surrounded by "h"&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;&lt;h3&gt;Matchers&lt;/h3&gt;&lt;br /&gt;ScalaTest 0.9.5 came out with a new Matchers API that I'll touch on briefly here, and point you to documentation for more. Using matchers, we can get our client code pretty close to this. We'll have to define our custom matcher first:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;case class surroundedBy(r:String) extends BeMatcher[String] {&lt;br /&gt;  def apply(l: String) =&lt;br /&gt;    MatchResult(&lt;br /&gt;      l.surroundedBy(r),&lt;br /&gt;      l + " was not surrounded by " + r,&lt;br /&gt;      l + " was surrounded by " + r&lt;br /&gt;    )&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;And our client test code turns out to be pretty close to the English:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;"htth" must be(surroundedBy("h"))&lt;br /&gt;"http" must not be surroundedBy("h")&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;I like this a lot, but, only if its going to be used a lot. Otherwise, if it's a one off test, I could just kick it back way old school and use an assert with an error message:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;assert( "htth".surroundedBy("h") === true,&lt;br /&gt;     "expected http to be surrounded by h, but it wasnt." )&lt;br /&gt;assert( "http".surroundedBy("h") === false,&lt;br /&gt;     "expected http not to be surrounded by h, but it was!!!" )&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This is less readable code, but it is &lt;span style="font-style: italic;"&gt;less&lt;/span&gt; code - about 6 lines less when you include the custom matcher. You get more or less the same error message in this case as well. It is quite ugly though. In this case I'd much rather have an API that just gives me what I originally wanted:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;"htth".surroundedBy("h") must be(true,&lt;br /&gt; "expected htth to be surrounded by h, but it wasnt.")&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;or better:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;"htth" must be('surroundedBy, "h")&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;I could see this one existing easily. It's really nice, but not type safe.&lt;br /&gt;&lt;br /&gt;Anyway, maybe there already are better alternatives like the ones I've explained I simply don't know about. Maybe I haven't done my homework and I should be scolded. I really hope not, and I'll happily write up (and more importantly - use) anything I find that helps make this code more readable. Until alternatives surface, I guess I'll somewhat reluctantly stay with these rules:&lt;br /&gt;&lt;br /&gt;When testing methods that return booleans you can&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Use the symbol style ('empty) if the method takes no arguments and you aren't terrible concerned about type safety.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Use old school assertions when the method takes arguments but you won't have a lot of repetitive tests for the method.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Use a custom matcher otherwise&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;You'll also find that ScalaTest (and Specs which is unfortunately not covered here) provides many matchers that can use for many common types.&lt;br /&gt;&lt;br /&gt;In my next post I'll provide a much deeper overview of how to write your own custom matchers in ScalaTest, starting by explaining what that surroundedBy case class means.&lt;br /&gt;&lt;br /&gt;In the meantime, you can look at &lt;a href="http://www.artima.com/weblogs/viewpost.jsp?thread=246279"&gt;ScalaTest Matchers&lt;/a&gt; and &lt;a href="http://code.google.com/p/specs/wiki/MatchersGuide"&gt;Specs Matchers&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Here's all the custom matcher code:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;package org.scalatest.examples&lt;br /&gt; &lt;br /&gt;import org.scalatest.matchers.MustMatchers._  &lt;br /&gt;import org.scalatest.matchers._&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;class MatcherTest extends FunSuite with MustMatchers{&lt;br /&gt; &lt;br /&gt;  implicit def surroundable[T](l:String) = new {&lt;br /&gt;    def surroundedBy(r:String) = l.startsWith(r) &amp;&amp; l.endsWith(r)&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  case class surroundedBy(r:String) extends BeMatcher[String] {&lt;br /&gt;    def apply(l: String) = &lt;br /&gt;      MatchResult(&lt;br /&gt;        l.surroundedBy(r), &lt;br /&gt;        l + " was not surrounded by " + r, &lt;br /&gt;        l + " was surrounded by " + r&lt;br /&gt;      )&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  test("weve got the place surrounded"){&lt;br /&gt;    "htth" must be(surroundedBy("h"))&lt;br /&gt;    "http" must not be surroundedBy("t")&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7143522262460311424?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7143522262460311424/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/tests-and-booleans-and-matchers.html#comment-form' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7143522262460311424'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7143522262460311424'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/tests-and-booleans-and-matchers.html' title='Tests and Booleans and Matchers'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1379519345318497875</id><published>2009-04-12T20:34:00.000-07:00</published><updated>2009-04-12T20:51:34.697-07:00</updated><title type='text'>ScalaTest IDE Support coming soon.</title><content type='html'>I've written something that allows me to write my tests in ScalaTest as normal (don't have to use any TestNG annotations in my tests), but also run them in all the IDE's, piggybacking off the TestNG IDE plugins. The code isn't in ScalaTest yet, but I'm guessing it likely will get in soon.&lt;br /&gt;&lt;br /&gt;Until then, anyone using FunSuite can borrow this code and temporarily use MiniFunSuite instead. This all seems to work quite well.&lt;br /&gt;&lt;br /&gt;Here's the client/test code:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;class FunSuiteExample extends FunSuiteTestNGAdapter{&lt;br /&gt;  test("hey"){ println("hey") }&lt;br /&gt;  test("fail"){ assert( 1 === 2 ) }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;And here's the library code:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;import org.scalatest.testng.TestNGSuite&lt;br /&gt;import org.testng.annotations.{DataProvider, Test}&lt;br /&gt;&lt;br /&gt;trait MiniFunSuite{&lt;br /&gt;  var testMap = Map[String, Function0[Unit]]()&lt;br /&gt;  def test(name:String)(f: =&gt; Unit) = testMap += (name -&gt; f _)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait FunSuiteTestNGAdapter extends MiniFunSuite with TestNGSuite{&lt;br /&gt;&lt;br /&gt;  @DataProvider{ val name="tests" }&lt;br /&gt;  def tests = testMap.map{ case (s,f) =&gt; Array(s,f) }.toList.toArray&lt;br /&gt;&lt;br /&gt;  @Test{ val dataProvider = "tests" }&lt;br /&gt;  def scalaTest(testName:String, f: =&gt; Unit) = { f }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1379519345318497875?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1379519345318497875/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/scalatest-ide-support-coming-soon.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1379519345318497875'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1379519345318497875'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/scalatest-ide-support-coming-soon.html' title='ScalaTest IDE Support coming soon.'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1764139546007354534</id><published>2009-04-08T05:33:00.000-07:00</published><updated>2009-04-08T06:33:26.061-07:00</updated><title type='text'>Twitter/Ruby/Scala/Blah</title><content type='html'>For some reason I feel compelled to chime in on this debate. I like both languages. I like Scala more, but Ruby is fun.&lt;br /&gt;&lt;br /&gt;(Reader Beware: This post was written in one pass with little to no editing.)&lt;br /&gt;&lt;br /&gt;I don't like how people get all steamed about their languages, as if it's part of them. But, if used properly, this energy can be channeled into creating better languages, so I guess its a necessary evil. The problem is, it not often used properly. Developers seem to just get mad at each other instead of talking through things civilly, and thinking critically and objectively. This is nothing new, and nothing that hasn't been said a thousand times I'm sure, but I think serves well as a nice introduction.&lt;br /&gt;&lt;br /&gt;Maybe the problem is that so many of the elements of programming languages are based on feel, as opposed to simple fact. I wish we'd all think more logically and have nice intelligent debates, and I wish we could support our arguments more with fact.&lt;br /&gt;&lt;br /&gt;Now for a debate. I was tweeting with Daniel Spiewak who said, &lt;br /&gt;&lt;br /&gt;"Obie has once again decided to completely miss the point. Twitter's legacy code is bad *because* of Ruby, not in spite. The experiences described by @stevej and @al3x precisely mirror my own: it isn't impossible to write large, maintainable Ruby...just hard."&lt;br /&gt;&lt;br /&gt;I asked him if he could elaborate on "because of", and to that he replied,&lt;br /&gt;&lt;br /&gt;"Ruby makes it *hard* to architect a large infrastructure and to keep it maintainable. I think that dynamic typing is part of the problem, but not all of it. Possibly the way the module system works? It isn't impossible to do large apps in Ruby (as Obie and Ola remind us), but it takes more effort and more discipline. Java and Scala both make this sort of large scale code base much easier to create and maintain."&lt;br /&gt;&lt;br /&gt;Now, I don't necessarily disagree with that (and recall that I do like Ruby). But I'd like to point out that I've been on a lot of Java projects that were completely unmaintainable. You could easily call them absolute disasters. In fact, the majority of the Java projects that I've been on have been disasters (yes, yes get your laughs in and tell me that its my fault...but its not. I did a lot to help those failing/flailing projects). Maybe that's because I've picked bad projects, and haven't many changes to work with great teams on applications built correctly from the start. &lt;br /&gt;&lt;br /&gt;But, I think that emphasizes my point a little. Who has? How many projects are built correctly from the ground up, by talented, disciplined developers? I'd say not many. Most developers are horrible, and the language wouldn't make a shred of difference. And for those developers who are really good, the language probably doesn't make that much difference either. A group of solid developers could easily build something far more maintainable in Ruby than the garbage developers who are writing in Java.&lt;br /&gt;&lt;br /&gt;But can those same developers build something more maintainable in Java or Scala? I think it depends on a whole number of things (listed at the end of the post). If there's a good chance of turnover on the project, then you probably want something with type information in the code because it serves so well as documentation. But if there's little chance of turnover it probably doesn't matter. &lt;br /&gt;&lt;br /&gt;That said, even with turnover, because Ruby is inherently higher level that Java its probably more easy to maintain. Java is just not a good language anymore, it has not stood the test of time. It came about to fix some problems with C++, and had a syntax that appealed to those developers, but that was 1994. It has not evolved. Ruby is so much more expressive than Java that the lack of type information probably doesn't mean much at all.&lt;br /&gt;&lt;br /&gt;Scala on the other hand, probably no contest for large projects. I think Twitter made the right decision. They get the type safety, the type documentation, and the high level expressiveness all together. I do like Ruby a lot, but Scala just feels better to me, and feel is very important, even if its not measurable. &lt;br /&gt;&lt;br /&gt;But all that could be wrong. How many large projects have actually been built in Scala? Few. I said in the beginning that I want people to think critically and objectively. It would be nice if we could base some of these debates on fact. Are there any facts out there that large Java projects are more maintainable than Ruby? There may well be, and if so, we should get that information out there. Then again, there may be documentation that supports the opposite. &lt;br /&gt;&lt;br /&gt;So I'm not really calling for comments here, though they are always welcome. What I am calling for is experiments, evidence, observations, or facts that support that one language is more maintainable than the other for any sized project.&lt;br /&gt;&lt;br /&gt;Here are some questions whose answers would be helpful (in no particular order):&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;What language was used?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;What was the size of the project:&lt;br /&gt;  &lt;ol&gt;&lt;br /&gt;   &lt;li&gt;LOC? Production and Test code.&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Number of developers?&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Number of testers?&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;How long did the project take?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;What was the amount turnover?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;What was the experience level of the developers?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The amount of time the team has been together?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The amount of time the developers have spent with the language used?&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Type of project? (Obviously if the language chosen was a horrible choice for the project, it makes a difference)&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;This information is probably pretty difficult to come by. The lack of it shouldn't impede intelligent debate, but the presence of it could help us as a community.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1764139546007354534?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1764139546007354534/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/twitterrubyscalablah.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1764139546007354534'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1764139546007354534'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/twitterrubyscalablah.html' title='Twitter/Ruby/Scala/Blah'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5577999004989047464</id><published>2009-04-04T20:14:00.000-07:00</published><updated>2009-04-06T10:39:04.766-07:00</updated><title type='text'>Random Thoughts</title><content type='html'>I haven't written in a while, but that doesn't mean that a lot hasn't been going on, just nothing I really felt the need to write about unfortunately. I do have some random thoughts about some things though, and so here they are.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Little Things&lt;/h3&gt;&lt;br /&gt;I've noticed in some of the comments on my posts that people like to point out that some of the things I mention are no big deal - like not having to put a dot in a method call:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;p ! t&lt;br /&gt;&lt;br /&gt;vs.&lt;br /&gt;&lt;br /&gt;p.!(t) or in Ruby: p.! t&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I'd like to point out that sure, they are little things. But, little things add up. The more and more of the little things that a language gets right, the more of a joy it is to program in. Scala seems to get a lot of these things right. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Java 7&lt;/h3&gt;&lt;br /&gt;I remember months ago (at least 4) I asked, "will Java 7 ever come out?" I did a brief google search and see no evidence that its any closer. Why is this? It's insane. &lt;br /&gt;&lt;br /&gt;I think the main reason is (so many people have realized and stated this before) that programming language by committee is BS. There must be a dictator running the show. I hope this is a road that Scala doesn't go down.&lt;br /&gt;&lt;br /&gt;There are plenty more reasons of course. Holding on for dear life to backwards compatibility is a bad idea IMO. If companies don't want to move forward to a new version because something has changed, then well, you aren't really at risk of losing them as users anyway. If they want to stay on the old version, let them. As a language designer you should not sacrifice the language. You should always do your best to put out the best language possible. If the language is the best, then when the company finally decides to move off the old version, they will move to the latest version. If your language isn't the best, they won't. No big deal.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;ScalaTest&lt;/h3&gt;&lt;br /&gt;I'm finally getting back into ScalaTest development. I'm really excited about it. It's been a while. I'll be giving a presentation at the next Scala meetup on testing in Scala. It won't be specifically to ScalaTest - I'll be including specs, matchers, mocking, ScalaCheck, lots of cool stuff. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Ruby&lt;/h3&gt;&lt;br /&gt;Ruby is definitely rubbing off on me. I read an interesting quite by Matz that said something along the lines of, "It really comes down to just how you feel writing in a language that matters". I feel good writing Ruby. I feel even better writing Scala (though I do sometimes end up in fights with the type system and get angry). I feel HORRIBLE writing Java. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;camelcase vs. underscores&lt;/h3&gt;&lt;br /&gt;I've decided that camelcase is much harder to read than underscores, and wish the Java and Scala communities would make the switch. WhenIReadCamelCaseAndEverythingIsBunchedUp, its_just_harder_to_read_than_underscores. I think this is especially true as the statement gets longer. TwoWords is not so_bad. ButAfterThat I think underscores_win_out.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Management&lt;/h3&gt;&lt;br /&gt;I can't begin to explain how good it feels to have good management again. I had a great one a few years back by the name of Eric Golin. He was so incredibly smart and knew how to speak to me and how to get the best out of all times. This is how I feel at my current job. Management has worked extremely hard to get things running smoothly. It just feels great. &lt;br /&gt;&lt;br /&gt;I've had so many terrible, terrible, terrible managers in the past - almost all of them. Its an absolute drag. I need to do better to make sure it doesn't happen again.&lt;br /&gt;&lt;br /&gt;Here's one tip - if anyone in the management chain wears sunglasses indoors, run like hell.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;C++?&lt;/h3&gt;&lt;br /&gt;I don't have much experience in C++ at all, but, in what little time that I've spent with it, I like it. And I like it a hell of a lot more than Java. Now, I know Java's appeal was that it fixed so many problems C++ developers had to face, but...for the most part I think it just appealed to the 90% of developers who aren't any good. &lt;br /&gt;&lt;br /&gt;But, Java probably was a good step back in order to fix some of those problems, in order to allow really nice things like Scala to come along. You know, I used to really like Java, until Scala came along. Now seeing Java code makes me throw up in my mouth a little. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Algorithms&lt;/h3&gt;&lt;br /&gt;I need to get better at explaining fundamental algorithms. Its not that I don't understand the concepts, I just don't do a good job of explaining my understanding of them. I will improve this. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;School&lt;/h3&gt;&lt;br /&gt;School is a perfect place for me. I have to go back. I change jobs often because I lose interest. I need to be challenged, always. I need new ideas. I need really smart people I can talk to all the time. Very few jobs can offer even half of what I need. I get all these things and more at school. &lt;br /&gt;&lt;br /&gt;If I need a challenge, I just pick a challenging class. Almost everyone in my program will be really smart, and interested in exactly the same things as me. Fantastic. And, I wont have to deal with sunglasses indoors.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5577999004989047464?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5577999004989047464/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/random-thoughts.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5577999004989047464'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5577999004989047464'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/04/random-thoughts.html' title='Random Thoughts'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-650902996763981661</id><published>2009-02-18T19:01:00.001-08:00</published><updated>2009-02-18T19:07:05.498-08:00</updated><title type='text'>Grad School</title><content type='html'>I plan on going back to grad school, full time maybe, part time maybe. I want to go for language design, as that's really all I'm interested in, and all I've been concentrating on for the past couple of years (outside of work).&lt;br /&gt;&lt;br /&gt;I think the obvious choice is EPFL, but I'm not yet sure what my chances are of getting in. NYU part time is also a good option.&lt;br /&gt;&lt;br /&gt;I'm very, very excited about this. In the past two years or so I went nuts and bought probably a dozen language design/compiler books, a dozen math books, and a bunch of books on actual languages. I've clearly been getting ready for this for quite some time, and the time is right.&lt;br /&gt;&lt;br /&gt;I need to write my statement of objectives, and if anyone is willing to proofread for me, that would be awesome.&lt;br /&gt;&lt;br /&gt;Also, if EPFL doesn't work out, I'd be willing to give some other schools a shot, but only for language design. Anyone out there have any good experiences to share?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-650902996763981661?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/650902996763981661/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/02/grad-school.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/650902996763981661'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/650902996763981661'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/02/grad-school.html' title='Grad School'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8160472419089136835</id><published>2009-02-18T18:36:00.000-08:00</published><updated>2009-02-18T18:51:22.203-08:00</updated><title type='text'>NYSE =&gt; New York Scala Enthusiasts</title><content type='html'>Monday, February 23rd, meeting of &lt;a href="http://www.meetup.com/New-York-Scala-Enthusiasts/"&gt;NYSE&lt;/a&gt;, or New York Scala Enthusiasts*. I suspect I'll be presenting regularly, but I won't be presenting at the first meeting - I think someone is speaking about the Actor model this time. My first presentation will likely be about ScalaTest, Specs, and other Scala testing alternatives.&lt;br /&gt;&lt;br /&gt;I encourage people who actually care about programming to join us, and programmers who don't care about programming to fall off the GW bridge.&lt;br /&gt;&lt;br /&gt;*&lt;span style="font-size:85%;"&gt; (Very funny that its called NYSE, given my very infamous stay with the actual company, and how that sham of a technology company wouldn't accept Scala at all, despite my best efforts. Anyway, looks like there will finally be a NYSE in town that embraces Scala.)&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8160472419089136835?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8160472419089136835/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/02/nyse-new-york-scala-enthusiasts.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8160472419089136835'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8160472419089136835'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/02/nyse-new-york-scala-enthusiasts.html' title='NYSE =&gt; New York Scala Enthusiasts'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4334783594570423487</id><published>2009-01-28T09:55:00.000-08:00</published><updated>2009-01-28T19:55:48.064-08:00</updated><title type='text'>Deeper Look at the Apply Method in Scala</title><content type='html'>In Scala, there is a language feature generally referred to as "The Apply Method" that has the following rules:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Any object that has an &lt;i&gt;apply&lt;/i&gt; method can be called with the &lt;i&gt;.apply&lt;/i&gt; omitted.&lt;/li&gt;&lt;li&gt;Functions are no more than objects.&lt;/li&gt;&lt;/ol&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Let's take a look at an example. Given the following abbreviated definition of class Array, and an instance &lt;i&gt;a&lt;/i&gt;, &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Array{&lt;br /&gt;  def get(index:Int) = { ...some code to get from the array... }  &lt;br /&gt;  def apply(index:Int) = get(index)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;val a = new Array(whatever)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Then the following calls are essentially equivalent:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;a.apply(7)&lt;br /&gt;a(7)&lt;br /&gt;&lt;/pre&gt;and also:&lt;pre&gt;&lt;br /&gt;a.get(7) &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;(the call to get is only equivalent because apply simply calls get. apply could have any implementation, of course.)&lt;br /&gt;&lt;br /&gt;While apply is really useful in cleaning up syntax, the real beauty of it is hidden just below the surface. (Note: Some of the following might not be implemented exactly as I describe, I'm not 100% sure, but for the sake of understanding, I think it's okay.)&lt;br /&gt; &lt;br /&gt;Scala'a apply is a concept that can be considered universally across functions or methods, objects, anonymous functions, case classes, and the like. In Scala, a method is nothing more than a Function object containing an apply method which takes the same arguments as the method itself. &lt;br /&gt;&lt;br /&gt;Let's take a look at a more in depth example. All three of the following are basically equivalent:&lt;br /&gt;&lt;pre&gt;  &lt;br /&gt;  def shout1( word: String ) = println(word + "!")&lt;br /&gt;&lt;br /&gt;  val shout2 = new Function1[String, Unit] {&lt;br /&gt;    def apply(word: String) = println(word + "!")&lt;br /&gt;  } &lt;br /&gt;&lt;br /&gt;  val shout3 = (word:String) =&gt; println(word + "!")&lt;br /&gt;&lt;/pre&gt;  &lt;br /&gt;All three are of type Function1[String,Unit], which has an apply method that takes a String and returns Unit. Notice that &lt;i&gt;shout3&lt;/i&gt; uses anonymous function syntax. This is really nothing more than syntactic sugar for Function1. All three can be called like so:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  shout1("hey")&lt;br /&gt;  shout2("hey")&lt;br /&gt;  shout3("hey")&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The following client code further demonstrates that they all derive from the same type. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  def ohYeah( f: String =&gt; Unit ){&lt;br /&gt;    f.apply("oh yeah")&lt;br /&gt;    f apply "oh yeah"&lt;br /&gt;    f("oh yeah")&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  ohYeah(shout1)&lt;br /&gt;  ohYeah(shout2)&lt;br /&gt;  ohYeah(shout3)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;However, one thing I find odd that cannot be done is the following:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  shout1.apply("hey") // compiler error!&lt;br /&gt;  shout2.apply("hey") // ok&lt;br /&gt;  shout3.apply("hey") // ok&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If anyone smarter than me cares to chime in on that one, I'd be quite happy. Apparently Scala doesn't always treat actual methods exactly the same as the equivalent Function values, but I'm not sure why. I tend to think it should. There must be a good reason.&lt;br /&gt;&lt;br /&gt;The first rule applies to top level objects, functions, and objects defining apply, but what about classes? Are classes no more than objects in the language, the same way that functions are?&lt;br /&gt;&lt;br /&gt;Unfortunately, it appears the answer is No. &lt;br /&gt;&lt;br /&gt;Before we get into that, let's that a quick look at the exception to that - case classes. For any case class C, you can say C(), and that returns you an instance of that class. Hmm...  C(). That looks an awful lot like what we've been looking at. As it turns out, it is. &lt;br /&gt;&lt;br /&gt;In Scala, when you define a case class, a corresponding top level object with the same name is created. This object is a factory which creates objects of the original class. It contains an apply method that takes the same arguments as the constructor of the original class and simply calls that constructor.  &lt;br /&gt;&lt;br /&gt;A quick example should help:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  case class Dood(name: String)&lt;br /&gt;&lt;br /&gt;  class DoodClient {&lt;br /&gt;    val a = new Dood("Jack")&lt;br /&gt;    val b = Dood("Daniels")&lt;br /&gt;    val c = Dood.apply("Cough")&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The expressions in b and c are equivalent. b is just shorthand for c. In both lines, Dood refers to the top level object Dood, and not the class. &lt;br /&gt;&lt;br /&gt;Knowing all this, I should correct myself. I said case classes are an exception to the rule that classes aren't simply objects in the language. This isn't really true. Creating the case class Dood creates both a class and a top level object. It's that object that has the apply, and the class itself still isn't a full fledged object. &lt;br /&gt;&lt;br /&gt;But why? Well, I think the short answer is that on the JVM classes aren't top level objects. That seems like a cop out answer though. Let me explore it for a bit, though I'm really just thinking out loud. &lt;br /&gt;&lt;br /&gt;If they were top level objects containing an apply method then we could probably do away with the new keyword entirely, and then any call to any object would simply be a call to apply. Things would be entirely consistent both from the internal language representation, and from the perspective of the developer as well. &lt;br /&gt;&lt;br /&gt;But what are the consequences of this? I guess I'm not sure. I'm going to have to think through it a bit harder. I'd appreciate comments from anyone with more knowledge on the subject than myself.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4334783594570423487?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4334783594570423487/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/01/deeper-look-at-apply-method-in-scala.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4334783594570423487'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4334783594570423487'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/01/deeper-look-at-apply-method-in-scala.html' title='Deeper Look at the Apply Method in Scala'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1595928509466277900</id><published>2009-01-26T06:28:00.000-08:00</published><updated>2009-01-26T06:31:59.215-08:00</updated><title type='text'>Maven: WTF</title><content type='html'>I'm on the train, trying to do a build, and this happens:&lt;br /&gt;&lt;br /&gt;[INFO] ------------------------------------------------------------------------&lt;br /&gt;[INFO] Building myProject&lt;br /&gt;[INFO]    task-segment: [clean]&lt;br /&gt;[INFO] ------------------------------------------------------------------------&lt;br /&gt;[INFO] artifact org.scala-tools:maven-scala-plugin: checking for updates from scala-tools.org&lt;br /&gt;[WARNING] repository metadata for: 'artifact org.scala-tools:maven-scala-plugin' could not be retrieved from repository: scala-tools.org due to an error: Error transferring file&lt;br /&gt;[INFO] Repository 'scala-tools.org' will be blacklisted&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;WTF?&lt;br /&gt;&lt;br /&gt;Because I'm not online maven totally explodes and threatens to blacklist stuff?&lt;br /&gt;&lt;br /&gt;I'm sure this is 'configurable' or whatever...but wtf, this just shouldn't happen. Since I wasn't online, I couldn't easily lookup what to do, so I couldn't build at all. Thanks Maven.&lt;br /&gt;&lt;br /&gt;I'm thoroughly annoyed.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1595928509466277900?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1595928509466277900/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/01/maven-wtf.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1595928509466277900'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1595928509466277900'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2009/01/maven-wtf.html' title='Maven: WTF'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1257555704756049836</id><published>2008-12-28T11:22:00.000-08:00</published><updated>2008-12-28T12:01:42.338-08:00</updated><title type='text'>More On My Scala Query DSL</title><content type='html'>I know I promised to explain some things that I still haven't explained, but unfortunately I won't be doing that just yet. I've been too busy coding. I made some cool additions to what I do have though. Now, I can query over more things that just a dictionary of words. In this post I'll show some examples using music scales. Additionally, I added orderBy, and limit stuff, which was really fun. &lt;br /&gt;&lt;br /&gt;I've added google code project for this as well, because I kept adding stuff to my cpusimulator project, and it clearly didn't belong. Here's the link: &lt;a href="http://code.google.com/p/dslplayground/"&gt;dslplayground&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Here's some examples:&lt;br /&gt;&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  val c_maj_and_a_min = contains(Chord("C", Maj), Chord("A", Min))&lt;br /&gt;2&lt;br /&gt;3  var scales_desc = &lt;br /&gt;     Scale find(c_maj_and_a_min) limit 4 orderBy (rootChord, Desc)&lt;br /&gt;4  var scales_asc  = &lt;br /&gt;     Scale find(c_maj_and_a_min) orderBy (rootChord, Asc) limit 3&lt;br /&gt;5  &lt;br /&gt;6  scales_desc foreach println&lt;br /&gt;7  println("-------------------------")&lt;br /&gt;8  scales_asc  foreach println&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Here I'm searching for all Scales (just major and minor scales) that contain Cmaj, and Amin.&lt;br /&gt;&lt;br /&gt;On line 3 I'm limiting my search to 4 scales, and ordering the results by the rootChord of the scale, descending. &lt;br /&gt;&lt;br /&gt;On line 4 I'm limiting my search to 3 scales, and ordering the results by the rootChord of the scale, ascending. But, notice I've done this in the opposite order as line 3. (The behavior changes though, if I limit the unordered result set before I order it, or after...not sure what to think about that.)&lt;br /&gt;&lt;br /&gt;Lines 6,7, and 8 yield:&lt;br /&gt;&lt;br /&gt;List(Chord(G,Maj), Chord(A,Min), Chord(B,Min), Chord(C,Maj), Chord(D,Maj), Chord(E,Min), Chord(F#,Dim))&lt;br /&gt;List(Chord(F,Maj), Chord(G,Min), Chord(A,Min), Chord(Bb,Maj), Chord(C,Maj), Chord(D,Min), Chord(E,Dim))&lt;br /&gt;List(Chord(D,Min), Chord(E,Dim), Chord(F,Maj), Chord(G,Min), Chord(A,Min), Chord(Bb,Maj), Chord(C,Maj))&lt;br /&gt;List(Chord(C,Maj), Chord(D,Min), Chord(E,Min), Chord(F,Maj), Chord(G,Maj), Chord(A,Min), Chord(B,Dim))&lt;br /&gt;-------------------------&lt;br /&gt;List(Chord(A,Min), Chord(B,Dim), Chord(C,Maj), Chord(D,Min), Chord(E,Min), Chord(F,Maj), Chord(G,Maj))&lt;br /&gt;List(Chord(C,Maj), Chord(D,Min), Chord(E,Min), Chord(F,Maj), Chord(G,Maj), Chord(A,Min), Chord(B,Dim))&lt;br /&gt;List(Chord(D,Min), Chord(E,Dim), Chord(F,Maj), Chord(G,Min), Chord(A,Min), Chord(Bb,Maj), Chord(C,Maj))&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The fantastic thing about all this is the implementation. I've genericized the stuff I did with Scrabble in a really clean way, and to add search support for an already existing Scale library all I had to do was:&lt;br /&gt;&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;object Scale extends Search[Scale]{&lt;br /&gt;  def all = notes.map(MajorScale(_)) ::: notes.map(MinorScale(_))&lt;br /&gt;  def rootChord( s: Scale ) = s.rootChord&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object ScaleMatchers {&lt;br /&gt;  def contains(chords: Chord*) = (s: Scale) =&gt; {&lt;br /&gt;    chords.foldLeft(true){ (b,c) =&gt; b &amp;&amp; (s contains c) }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;By extending the Search trait, I get all sorts of nice ability to search. All I need to do is provide the definition of the &lt;span style="font-style:italic;"&gt;all&lt;/span&gt; function. Then, I just define some matchers (in this case only one), and I'm all set to start searching through my data. &lt;br /&gt;&lt;br /&gt;Hopefully I'll be able to extract out some of the common matcher stuff as well. I don't think this will be all that difficult. &lt;br /&gt;&lt;br /&gt;Its important to note a choice that I've made here. I'm forcing the definition of the &lt;span style="font-style:italic;"&gt;all&lt;/span&gt; method. Basically, right now, every search loads all the data, and then works on it. Certainly this won't scale, but, this is just a simple little DSL. The underlying implementation could be optimized later. Doug Lea taught me that that is the way you should design languages. First, work on getting the language correct, then worry about performance.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1257555704756049836?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1257555704756049836/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/more-on-my-scala-query-dsl.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1257555704756049836'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1257555704756049836'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/more-on-my-scala-query-dsl.html' title='More On My Scala Query DSL'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6648779017242530887</id><published>2008-12-22T14:45:00.000-08:00</published><updated>2008-12-23T15:01:11.976-08:00</updated><title type='text'>Fun DSL Query Language for Scala</title><content type='html'>(Quick Note: If you just want to skip to the code, it's interspersed throughout the post. But, for your convenience, I've also put it all in one place at the &lt;a href="#code"&gt;bottom&lt;/a&gt; of the post.)&lt;br /&gt;&lt;br /&gt;I've done it! Sick as a dog yesterday, I refactored the crap out of my Scrabble stuff, to create a really powerful query DSL. The kicker? It's only 24 lines of code! It allows you to do all sorts of crazily powerful queries. Lets take a look. I'm so excited! I can't stop typing exclamation points! I actually think this is the best code I've ever written. &lt;a href="#one"&gt;1&lt;/a&gt; &lt;br /&gt;&lt;br /&gt;I'd love to talk about the code smells of my last post, and how I ended up where I did, but to be honest, the code seems so much different now that it would be difficult. I'll just dive in. &lt;br /&gt;&lt;br /&gt;Once again I'll start with the test code, which models the original requirements. Don't worry if you don't understand &lt;span style="font-style:italic;"&gt;how&lt;/span&gt; it works just yet, because I'll explain later. For this first bit, I'm just going to try to explain &lt;span style="font-style:italic;"&gt;what&lt;/span&gt; it does.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val dictionary = new Dictionary(getWords())&lt;br /&gt;  val tray = "defilnr"&lt;br /&gt;&lt;br /&gt;  // the 4 original requirements&lt;br /&gt;  val all  = dictionary find includes_all(tray) &lt;br /&gt;  val any  = dictionary find includes_any(tray)&lt;br /&gt;  val only = dictionary find includes_only(tray)&lt;br /&gt;  val all_and_only = &lt;br /&gt;    dictionary find (includes_all(tray) and includes_only(tray))&lt;br /&gt;    &lt;br /&gt;  print(all, only, all_and_only)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Let me sum up what's going on here. &lt;ul&gt;&lt;li&gt;With "all", I've filtered the dictionary to find words that include &lt;span style="font-style:italic;"&gt;all&lt;/span&gt; the letters in my tray. This produces a small list of very long words - something like: List(adenoliomyofibroma, antifederal, antifederalism, antifederalist, ... )&lt;/li&gt;&lt;li&gt;Similarly with "any", I've filtered the dictionary to find words that include &lt;span style="font-style:italic;"&gt;any&lt;/span&gt; of the letters in my tray. This produces a gigantic list that I won't even begin to list here.&lt;/li&gt;&lt;li&gt;With "only", I've filtered the dictionary to find words that include &lt;span style="font-style:italic;"&gt;only&lt;/span&gt; of the letters in my tray. This produces &lt;/li&gt; a very large list - something like: List(d, d, de, dee, deed, deedeed, deer, defend, defender, defer, ... )&lt;/li&gt;&lt;li&gt;Finally, the important query, with "all_and_only", filtered the dictionary to find words that include words that include &lt;span style="font-style:italic;"&gt;all&lt;/span&gt; the letters in my tray, and &lt;span style="font-style:italic;"&gt;only&lt;/span&gt; the letters in my tray, just as the code reads. This produces something much more helpful to me in Scrabble: List(flinder, infielder)&lt;/li&gt;&lt;/ul&gt; &lt;br /&gt;A key thing to notice is the "and" on this line:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;    dictionary.filter(includes_all(tray) and includes_only(tray))&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;But like I said, I'll explain the &lt;span style="font-style:italic;"&gt;hows&lt;/span&gt; later. Now I'll introduce a couple of new concepts with this line of code:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;   val all_or_min_10 = dictionary(includes_all(tray) or  max_length(7))&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;The two new concepts on this line are:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;"or", which is very similar to "and" and very self explanatory.&lt;/li&gt;&lt;li&gt;Notice I'm not calling dictionary "find" some_criteria, I'm just calling dictionary(some_criteria). I'll explain how this works later as well. I'm not actually sure I like it, but I figured I'd give it a shot to see how the code looks.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Time for more:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val xin_or_max_4 = &lt;br /&gt;    dictionary search (starts_with("xin") or max_length(4))&lt;br /&gt;  val van_or_min_4 = &lt;br /&gt;    dictionary search (ends_with("van") and min_length(4))&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Some more new concepts on these lines are:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;The "search" method is also an alias for find. But, the actual aliasing is pretty neat, so it will be cool to show how later.&lt;/li&gt;&lt;li&gt;Several new criteria functions - &lt;span style="font-style:italic;"&gt;starts_with, ends_with, max_length, min_length&lt;/span&gt;, which I think are also very self explanatory in what they do.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;If I'm moving quickly its because I'm really excited to get into the next part, where I build up a much more complex query.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Complex Queries&lt;/h3&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val complex_query =&lt;br /&gt;    (&lt;br /&gt;      (starts_with("d") and ends_with("ing")) or&lt;br /&gt;      (starts_with("b") and ends_with("ed"))&lt;br /&gt;    ) and max_length(7) and min_length(4)&lt;br /&gt; &lt;br /&gt;  var result = dictionary find complex_query&lt;br /&gt;  print(result)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Yes! This seems to have really put it all together. In this query I'm asking for words that start with 'd' and end with 'ing', OR words that start with 'b' and end with 'ed', and any words found must have a maximum length of 7 and a minimum length of 4. I build up the query first, and then ask the dictionary to execute it for me. This seemingly innocent feature plays an important role in abstraction. Which hopefully we'll get to see in just a bit.&lt;br /&gt;&lt;br /&gt;Executing this query gives me something like: List(babied, backed, bagged, baked, balled, banded, bangled, banked, barbed, barred, ... dueling, duffing, dumping, during, dusting, dyeing, dying)&lt;br /&gt; &lt;br /&gt;&lt;h3&gt;Adding onto existing queries&lt;/h3&gt;&lt;br /&gt;But, I'm not satisfied with my results. Maybe I can't seen to find a place on the Scrabble board where an "a" can be used, and I don't have one in my tray. I want to re-execute my query, but remove all the a's. Here's how: &lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val complex_query_without_a = complex_query and includes_none("a")&lt;br /&gt;  result = dictionary find complex_query_without_a&lt;br /&gt;  print(result)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Fancy Schmancy! Executing this query gives me: List(bebed, bebled, bedded, beedged, beetled, beeweed, beinked, beliked, ... dueling, duffing, dumping, during, dusting, dyeing, dying)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Language Features&lt;/h3&gt;&lt;br /&gt;Before we go into the &lt;span style="font-style:italic;"&gt;hows&lt;/span&gt;, lets take a very, very quick theory break. Taken straight from &lt;a href="http://mitpress.mit.edu/sicp/"&gt;SICP&lt;/a&gt;, any language gives you three things:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Primitive Expressions&lt;/li&gt;&lt;li&gt;A means of combination&lt;/li&gt;&lt;li&gt;A means of abstraction&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Does this little DSL cover those criteria? Yes (though point 3 is somewhat shaky). Anyway, as we cover the hows, we'll refer back to those points to demonstrate how this DSL fulfills them. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Primitive Expressions&lt;/h3&gt;&lt;br /&gt;We're finally to the implementation (though I suppose many of you probably just scrolled down).&lt;br /&gt;&lt;br /&gt;The query criteria methods are basically our primitive expressions in this DSL. &lt;a href="#one"&gt;2&lt;/a&gt; Here is the list of primitives provided, and their implementations. I suspect that other primitives will be added soon. &lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  object WordMatchers{&lt;br /&gt;2    def includes_only(s: String) = (t: String) =&gt; &lt;br /&gt;          inverse(s).foldLeft(true)((b,c) =&gt; b &amp;&amp; (! (t contains c)))&lt;br /&gt;3    def includes_none(s: String) = (t: String) =&gt; &lt;br /&gt;          s.foldLeft(true)((b,c)  =&gt; b &amp;&amp; (! (t contains c)))&lt;br /&gt;4    def includes_all(s: String)  = (t: String) =&gt; &lt;br /&gt;          s.foldLeft(true)((b,c)  =&gt; b &amp;&amp; (t contains c))&lt;br /&gt;5    def includes_any(s: String)  = (t: String) =&gt; &lt;br /&gt;          s.foldLeft(false)((b,c) =&gt; b || (t contains c))&lt;br /&gt;6    def starts_with(s: String)   = (t: String) =&gt; t startsWith s&lt;br /&gt;7    def ends_with(s: String)     = (t: String) =&gt; t endsWith  s&lt;br /&gt;8    def max_length(max: Int)     = (s: String) =&gt; s.trim.length &lt;= max&lt;br /&gt;9    def min_length(min: Int)     = (s: String) =&gt; s.trim.length &gt;= min&lt;br /&gt;10   def inverse( s: String ) = &lt;br /&gt;          "abcdefghijklmnopqrstuvwxyz".filter(!s.contains(_) )&lt;br /&gt;11 }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Ok...I hope no one kills me when I say I'm going to save the &lt;span style="font-style:italic;"&gt;how&lt;/span&gt; for this one for the next post. That's the implementation. It's pretty crazy, and can probably only be read by pretty experienced developers. I'm really tired and still not feeling great, so I'm going to wait so I don't mess it up.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Means of Combination&lt;/h3&gt;&lt;br /&gt;The means of combination in this DSL are very simple (at least from a users standpoint). They are simply &lt;span style="font-style:italic;"&gt;and&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;or&lt;/span&gt;. &lt;br /&gt;&lt;br /&gt;The implementation of those combinations are pretty complex though. &lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  object Criteria{&lt;br /&gt;2    implicit def funcToCriteria[T](f: Function1[T, Boolean]) = &lt;br /&gt;       new Criteria(f) &lt;br /&gt;3  }&lt;br /&gt;4  class Criteria[T](val f: Function1[T, Boolean]) {&lt;br /&gt;5    def apply(t: T) = f(t)&lt;br /&gt;6    def &amp;&amp; (c: Criteria[T]): Criteria[T] = (t: T) =&gt; f(t) &amp;&amp; c.f(t)&lt;br /&gt;7    def || (c: Criteria[T]): Criteria[T] = (t: T) =&gt; f(t) || c.f(t)&lt;br /&gt;8  }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Criteria is some seriously powerful magic, and is totally awesome. I'm also going to wait, and explain both the primitives, and combinations in the next post, which will probably be just tomorrow night. Maybe I'll just update it right here. Maybe I shouldn't even post this yet until I'm finished, but I know there are people that read my blog and this is too cool to wait on!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Execution&lt;/h3&gt;&lt;br /&gt;Before we take a look at our means of abstraction, lets take a quick look at the Dictionary class, which is something like the DSL's runtime environment, and VM. It holds the words (the environment), and executes the queries which search over those words (VM).&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  case class Dictionary( words: List[String] ) {&lt;br /&gt;2    def apply(criteria: Criteria[String]) = words.filter(criteria(_))&lt;br /&gt;3    def find = apply _; def filter = apply _; def search = apply _;&lt;br /&gt;4  }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Its fairly simple, simply asking the Criteria to evaluate themselves, for each word in the dictionary. If the word doesn't fit the criteria, it is filtered out.&lt;br /&gt;&lt;br /&gt;One thing that I really wanted to get to (which doesn't have a whole lot of importance, but is really cool) is  the method aliasing. Check out line 3. I've aliased find, filter, and search all to apply, so that a user can call any of them. Maybe that's confusing and not needed, but it was fun. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Means of Abstraction&lt;/h3&gt;&lt;br /&gt;This DSL borrows its means of abstraction from the Scala language itself, but so far does a pretty poor job of it. &lt;br /&gt;&lt;br /&gt;Let's revisit the very last example:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val complex_query_without_a = complex_query and includes_none("a")&lt;br /&gt;  result = dictionary find complex_query_without_a&lt;br /&gt;  print(result)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;I intentionally left out the declaration of complex_query. Do you remember what it does? I suspect not. I could tell you that its a query "asking for words that start with 'd' and end with 'ing', OR words that start with 'b' and end with 'ed', and any words found must have a maximum length of 7 and a minimum length of 4. But, I shouldn't have to. Somehow the code &lt;span style="font-style:italic;"&gt;should&lt;/span&gt; provide that information upon reading it. There are ways we could do this, but they aren't great, in my opinion.&lt;br /&gt;&lt;br /&gt;We could say:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  val starts_with_d_and_ends_with_ing_OR_starts_with_b_and_on_and_on_and_on =&lt;br /&gt;    (&lt;br /&gt;      (starts_with("d") and ends_with("ing")) or&lt;br /&gt;      (starts_with("b") and ends_with("ed"))&lt;br /&gt;    ) and max_length(7) and min_length(4)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;But, that really doesn't work. I mean, not only does the variable name go right off the stinkin' page, but the entire implementation is encoded into it. I think that its possible that this DSL fails at doing a great job of abstraction because the underlying nature of the thing its trying to represent - queries matching specific criteria - doesn't really lend itself to abstraction very well. If anyone has any ideas on how this could be improved, I'd be grateful.  &lt;br /&gt;&lt;br /&gt;OK....that's all for now. I know this thing sort of deteriorated at the end as I got tired, but I'll fix it up really soon. Hope you love it!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Implementation&lt;/h3&gt;&lt;br /&gt;As promised, here's all the code in one place:&lt;br /&gt;&lt;a name="code"&gt;&lt;/a&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;package com.joshcough.scrabble&lt;br /&gt;&lt;br /&gt;import Criteria._&lt;br /&gt;import Dictionary._&lt;br /&gt;import WordMatchers._&lt;br /&gt;import org.testng.annotations.Test&lt;br /&gt;import scala.io.Source&lt;br /&gt;&lt;br /&gt;class ScrabbleTest {&lt;br /&gt;&lt;br /&gt;  val lines = Source.fromFile("/usr/share/dict/words").getLines&lt;br /&gt;  val words = lines.toList.map(_.trim.toLowerCase)&lt;br /&gt;  val dictionary = Dictionary(words)&lt;br /&gt;&lt;br /&gt;  @Test def tests {&lt;br /&gt;&lt;br /&gt;    val tray = "defilnr"&lt;br /&gt;&lt;br /&gt;    // the 4 original requirements&lt;br /&gt;    val all =  dictionary find includes_all(tray)&lt;br /&gt;    val any =  dictionary find includes_any(tray)&lt;br /&gt;    val only = dictionary find includes_only(tray)&lt;br /&gt;    val all_and_only = dictionary find &lt;br /&gt;      (includes_all(tray) and includes_only(tray))&lt;br /&gt;    print(all, only, all_and_only)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    // additional cool things &lt;br /&gt;    // (use of Dictionary.apply and Criteria's "||" method )&lt;br /&gt;    val all_max_7     = &lt;br /&gt;      dictionary(includes_all(tray) and max_length(7))&lt;br /&gt;    val all_or_min_10 = &lt;br /&gt;      dictionary(includes_all(tray) or  max_length(7))&lt;br /&gt;    print(all_max_7, all_or_min_10)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    // more things (use of Dictionary.filter, &lt;br /&gt;    // starts_with, ends_with, max_length, min_length)&lt;br /&gt;    val xin_or_max_4 = &lt;br /&gt;      dictionary search (starts_with("xin") or max_length(4))&lt;br /&gt;    val van_or_min_4 = &lt;br /&gt;      dictionary search (ends_with("van") and min_length(4))&lt;br /&gt;    print(xin_or_max_4, max_4_or_van)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    &lt;br /&gt;    // more complex query&lt;br /&gt;    val complexQuery =&lt;br /&gt;      (&lt;br /&gt;        (starts_with("d") and ends_with("ing")) or&lt;br /&gt;        (starts_with("b") and ends_with("ed"))&lt;br /&gt;      ) and max_length(7) and min_length(4)&lt;br /&gt;&lt;br /&gt;    var result = dictionary find complexQuery&lt;br /&gt;    print(result)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    // hmmm, but i didnt like my result...&lt;br /&gt;    // how about i modify my query...&lt;br /&gt;    val complexQueryWithoutAs = complexQuery and includes_none("a")&lt;br /&gt;    result = dictionary find complexQueryWithoutAs&lt;br /&gt;    print(result)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def print[T](lists: List[T]*) = lists foreach println&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author dood&lt;br /&gt; * Date: Dec 21, 2008&lt;br /&gt; * Time: 10:09:24 PM&lt;br /&gt; */&lt;br /&gt;object Criteria{&lt;br /&gt;  implicit def funcToCriteria[T](f: Function1[T, Boolean]) = &lt;br /&gt;    new Criteria(f) &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Criteria[T](val f: Function1[T, Boolean]) {&lt;br /&gt;  def apply(t: T) = f(t)&lt;br /&gt;  def and (c: Criteria[T]): Criteria[T] = (t: T) =&gt; f(t) &amp;&amp; c.f(t)&lt;br /&gt;  def or  (c: Criteria[T]): Criteria[T] = (t: T) =&gt; f(t) || c.f(t)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author dood&lt;br /&gt; * Date: Dec 21, 2008&lt;br /&gt; * Time: 11:24:22 AM&lt;br /&gt; */&lt;br /&gt;case class Dictionary( words: List[String] ) {&lt;br /&gt;  def apply(criteria: Criteria[String]) = words.filter(criteria(_))&lt;br /&gt;  def find = apply _; def filter = apply _; def search = apply _;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * @author dood&lt;br /&gt; * Date: Dec 22, 2008&lt;br /&gt; * Time: 3:12:35 PM&lt;br /&gt; */&lt;br /&gt;object WordMatchers{&lt;br /&gt;  def includes_only(s: String) = (t: String) =&gt; &lt;br /&gt;    inverse(s).foldLeft(true)((b,c) =&gt; b &amp;&amp; (! (t contains c)))&lt;br /&gt;  def includes_none(s: String) = (t: String) =&gt; &lt;br /&gt;    s.foldLeft(true)((b,c)  =&gt; b &amp;&amp; (! (t contains c)))&lt;br /&gt;  def includes_all(s: String)  = (t: String) =&gt; &lt;br /&gt;    s.foldLeft(true)((b,c)  =&gt; b &amp;&amp; (t contains c))&lt;br /&gt;  def includes_any(s: String)  = (t: String) =&gt; &lt;br /&gt;    s.foldLeft(false)((b,c) =&gt; b || (t contains c))&lt;br /&gt;  def starts_with(s: String)   = (t: String) =&gt; t startsWith s&lt;br /&gt;  def ends_with(s: String)     = (t: String) =&gt; t endsWith  s&lt;br /&gt;  def max_length(max: Int)     = (s: String) =&gt; s.trim.length &lt;= max&lt;br /&gt;  def min_length(min: Int)     = (s: String) =&gt; s.trim.length &gt;= min&lt;br /&gt;  def inverse( s: String )     = &lt;br /&gt;    "abcdefghijklmnopqrstuvwxyz".filter(! s.contains(_) )&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;&lt;br /&gt;&lt;a name="one"&gt;&lt;/a&gt;&lt;font size="small"&gt;(1) - I hate the NYSE for keeping me in an intellectual prison for so long, and hate myself for not leaving sooner.&lt;br /&gt;&lt;br /&gt;&lt;a name="two"&gt;&lt;/a&gt;(2) - However, this is an internal DSL, and so you are free to build up more and more primitives, which makes them seem not really like primitives at all...&lt;/font&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6648779017242530887?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6648779017242530887/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/fun-dsl-query-language-for-scala.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6648779017242530887'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6648779017242530887'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/fun-dsl-query-language-for-scala.html' title='Fun DSL Query Language for Scala'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2522550187058050667</id><published>2008-12-21T08:51:00.001-08:00</published><updated>2008-12-21T22:47:43.716-08:00</updated><title type='text'>Using Scala First Class Functions By Name</title><content type='html'>WARNING: Today I changed this code all around, and I'll be reposting it soon. This post is still cool, and nothing is wrong with it, but, now the code is &lt;span style="font-style:italic;"&gt;wicked awesome!!!&lt;/span&gt; So, look for it to be refreshed soon!&lt;br /&gt;&lt;br /&gt;It occurred to me that while I knew really well how to pass anonymous functions around in Scala, I had very little experience passing around functions by name. I'm not sure why this is, but I think there isn't all that much out there written about it. It's important to understand that anywhere you could use an anonymous function, you could also use an existing function. Passing functions by name really helps clarify the intent of your code, and for DSL's in general. I'm going to try to demonstrate how to do so, for those who might be in the same boat as me.&lt;br /&gt;&lt;br /&gt;I wrote a little app that searches through /usr/dict/words to find words matching the letters that I have in my Scrabble tray. Yes, I could have easily done this with "cat /usr/dict/words | grep someRegEx", but, the point was to learn more about functions.&lt;br /&gt;&lt;br /&gt;(quick note...this post is really really long, but i think its full of good information)&lt;br /&gt;&lt;br /&gt;First, I needed to be able to determine the following information about a word:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Does the word contain ALL the letters in my tray? (but maybe some other letters)&lt;/li&gt;&lt;li&gt;Does the word contain ONLY the letters in my tray? (no other letters allowed)&lt;/li&gt;&lt;li&gt;Does the word contain ANY of the letters in my tray?&lt;/li&gt;&lt;li&gt;Does the word contain NONE of the letters in my tray?&lt;/li&gt;&lt;li&gt;Lastly, does the word contain ALL of the letters in my tray, and ONLY the letters in my tray?&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;To do this I added a function to String that takes the characters to search for, and then any number of additional criteria. The criteria are functions that I reference by name. Lets see the client code, then I'll explain in more detail. Bear with me, I know its frustrating not seeing the actual library code, but I do think it helps to understand how its used before reading it.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  class StringSearchTest {&lt;br /&gt;2   &lt;br /&gt;3   import org.testng.annotations.Test&lt;br /&gt;4   import PimpedString._&lt;br /&gt;5   import Equalizer._&lt;br /&gt;6 &lt;br /&gt;7   @Test&lt;br /&gt;8   def testSearch {&lt;br /&gt;9     var word = "ketoid"&lt;br /&gt;10    word.searchFor("ke",  word.includes_all)  mustBe true&lt;br /&gt;11    word.searchFor("ke",  word.includes_none) mustBe false&lt;br /&gt;12    word.searchFor("xzy", word.includes_none) mustBe true&lt;br /&gt;13    word.searchFor("ke",  word.includes_only) mustBe false&lt;br /&gt;14&lt;br /&gt;15    word = "keyyek"&lt;br /&gt;16    word.searchFor("key", word.includes_only) mustBe true&lt;br /&gt;17    word.searchFor("xyz", word.includes_any)  mustBe true&lt;br /&gt;18    word.searchFor("abc", word.includes_any)  mustBe false    &lt;br /&gt;19    word.searchFor("key", word.includes_only, word.includes_all)  mustBe true&lt;br /&gt;20    word.searchFor("key", word.includes_all,  word.includes_none) mustBe false&lt;br /&gt;21  }&lt;br /&gt;22}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Let's break down line a few lines:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;10    word.searchFor("ke",  word.includes_all)  mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;ul&gt;&lt;li&gt;"word" is the word we are searching.&lt;/li&gt;&lt;li&gt;"ke" is what we are searching for.&lt;/li&gt;&lt;li&gt;"word.includes_all" is the criteria. This particular criteria states that 'word' must include all the letters we are searching for. In this case, word must contain both k and e.&lt;/li&gt;&lt;li&gt;The statement itself (word.searchFor("ke",  word.includes_all)) returns a Boolean. True if the word matches the search criteria, false otherwise.&lt;/li&gt;&lt;/ul&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;11    word.searchFor("ke",  word.includes_none) mustBe false&lt;br /&gt;12    word.searchFor("xzy", word.includes_none) mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;includes_none is very much the opposite of includes all. It ensures that the word contains NONE of the things we are looking for. The statement in line 11 evaluates to false because the word does contain k (and e for that matter). Line 12 evaluates to true because they word does not contain x, y, or z.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;16    word.searchFor("key", word.includes_only) mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This is nearly the same as the line 10, but the criteria is more restrictive. includes_only states that the word must include only letters that we are searching for. If we were searching for "key" in the word "hey", this would fail, because our word contains an "h".&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;17    word.searchFor("xyz", word.includes_any)  mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Also very similar to above, but includes_any evaluates to true if the word contains ANY of the things we are searching for.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;20    word.searchFor("key", word.includes_only, word.includes_all)  mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Finally the moment of truth, line 20 is the most important of all. It states that the word must contain ONLY the letters in my tray, and ALL of the letters in my tray. This is the easiest way to find Bingo words. (It doesn't yet work perfectly, if my tray contained "key" and the word was "keyyyy", it would still evaluate to true. I need to fix this.)&lt;br /&gt;&lt;br /&gt;Finally, before we see the actual library code, lets take a second to understand what "word.includes_all" actually is. "word.includes_all" is a higher order function that takes an Array of Char, and returns a function that takes a Char and returns a Boolean. A higher order function is a function that takes a function as an argument, returns a function, or both. includes_all does both. Higher order functions have been explained by everyone and their brother since 1960, so I won't be doing that here. I'm just explaining how to pass functions by name.&lt;br /&gt;&lt;br /&gt;Ok, lets take a look at the library code and I'll explain in more detail.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  object PimpedString {&lt;br /&gt;2    implicit def pimpMyString(s: String): PimpedString = &lt;br /&gt;3         new PimpedString(s)&lt;br /&gt;4    implicit def convertToCharArray(s: String): Array[Char] = &lt;br /&gt;5         s.toCharArray&lt;br /&gt;6  }&lt;br /&gt;7 &lt;br /&gt;8  class PimpedString(s: String) {&lt;br /&gt;9  &lt;br /&gt;10   def includes_all(chars: Array[Char])  = &lt;br /&gt;11        fold(chars)(s contains _)&lt;br /&gt;12   def includes_none(chars: Array[Char]) = &lt;br /&gt;13        fold(chars)(!s.contains(_))&lt;br /&gt;14   def includes_any(chars: Array[Char])  = &lt;br /&gt;15        chars.foldLeft(false)((b,c) =&gt; b || (s contains c))&lt;br /&gt;16   def includes_only(chars: Array[Char]) = &lt;br /&gt;17        includes_none(inverse(chars))&lt;br /&gt;18&lt;br /&gt;19   private val letters = "abcdefghijklmnopqrstuvwxyz".toCharArray&lt;br /&gt;20   private def fold(chars: Array[Char])(f: Char =&gt; Boolean) = &lt;br /&gt;21        chars.foldLeft(true)(_ &amp;&amp; f(_))&lt;br /&gt;22   private def inverse( chars: Array[Char] ) = &lt;br /&gt;23        letters.filter(! chars.contains(_))&lt;br /&gt;24   def searchFor(chars: Array[Char], &lt;br /&gt;25                 criteria: Function1[Array[Char], Boolean]*): Boolean = {&lt;br /&gt;26     criteria.foldLeft(true){(b, f) =&gt; b &amp;&amp; f(chars)}&lt;br /&gt;27   }&lt;br /&gt;28 }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;(quick note: I've written about implicits &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/12/ruby-over-scala.html"&gt;here&lt;/a&gt;, and &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/using-scala-implicits-to-replace.html"&gt;here&lt;/a&gt;, and I've written about foldLeft &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/foldleft-in-scala-little-schemer-style.html"&gt;here&lt;/a&gt;, and I won't be covering them in any detail here.)&lt;br /&gt;&lt;br /&gt;Let's just skip right ahead to line 10:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;10    def includes_all(chars: Array[Char])  = fold(chars)(s contains _)&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;As advertised, includes_all is a higher order function that takes an Array of Char, and returns a function that takes a Char and returns a Boolean. Let's take a look back at the original code to see how it was used:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;10    word.searchFor("ke",  word.includes_all)  mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Now, I &lt;span style="font-style:italic;"&gt;could&lt;/span&gt; have just used an anonymous function here for my criteria. Assuming that the fold method wasn't private, it would look like this:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;10    word.searchFor("ke",  word.fold(chars)(s contains _))  mustBe true&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;The call to fold is basically saying look at each of the search characters and make sure I contain it. fold also returns a function that is executed in search. I &lt;span style="font-style:italic;"&gt;could&lt;/span&gt; do this, but since includes_all is so common, so reusable, that instead of passing it anonymously, I give it a name, and reuse it all over. And, giving it a name makes it much, much more clear as to what is going on. The second version of line 10 is almost indecipherable.&lt;br /&gt;&lt;br /&gt;That basically sums up how to reference functions by name, and pass them around. I'm going to finish the post, showing the actual Scrabble code. However, I don't think there are any ideas that I haven't already covered. Let's start by reviewing the original requirements, since its been a while:&lt;br /&gt;&lt;br /&gt;Find all possible words where:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;The word contains ALL the letters in my tray. (but maybe some other letters)&lt;/li&gt;&lt;li&gt;The word contains ONLY the letters in my tray. (no other letters allowed)&lt;/li&gt;&lt;li&gt;The word contain ANY of the letters in my tray. (other letters allowed)&lt;/li&gt;&lt;li&gt;The word contains ALL of the letters in my tray, and ONLY the letters in my tray.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Now to be consistent, lets look at the test/client code, because that's where you should always start.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  object ScrabbleTest extends Application{&lt;br /&gt;2    val tray = System.getProperty("tray").toString&lt;br /&gt;3    val scrabble = Scrabble(tray)&lt;br /&gt;4  &lt;br /&gt;5    println(scrabble.find(scrabble.all_letters_in_tray))&lt;br /&gt;6    println(scrabble.find(scrabble.only_letters_in_tray))&lt;br /&gt;7    println(scrabble.find(scrabble.any_letters_in_tray))&lt;br /&gt;8    println(scrabble.find(&lt;br /&gt;9       scrabble.only_letters_in_tray,&lt;br /&gt;10      scrabble.all_letters_in_tray))&lt;br /&gt;11 }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;I think I have to take some pride in this. The code reads very, very close to the actual requirements. So much that I'm not going to explain it, except to point out again that &lt;span style="font-style:italic;"&gt;scrabble.all_letters_in_tray&lt;/span&gt; is another example of passing a function by name. &lt;br /&gt;&lt;br /&gt;Let's just go right to the library code.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;1  case class Scrabble(tray: Array[Char]) {&lt;br /&gt;2    val lines = Source.fromFile("/usr/share/dict/words").getLines&lt;br /&gt;3    val words = lines.toList.map( _.toLowerCase )&lt;br /&gt;4&lt;br /&gt;5    def only_letters_in_tray(s: String): Function1[Array[Char], Boolean] = &lt;br /&gt;6          s.includes_only&lt;br /&gt;7    def all_letters_in_tray(s: String): Function1[Array[Char], Boolean] =&lt;br /&gt;8          s.includes_all&lt;br /&gt;9    def any_letters_in_tray(s: String): Function1[Array[Char], Boolean] = &lt;br /&gt;10         s.includes_any&lt;br /&gt;11&lt;br /&gt;12   def find(criteria: Function1[String, Function1[Array[Char], Boolean]]*) = {&lt;br /&gt;13      words.filter( word =&gt; { &lt;br /&gt;14        word.searchFor(tray, criteria.map( _(word) ):_* ) &lt;br /&gt;15     }).map(_.trim)&lt;br /&gt;16   }&lt;br /&gt;17  }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Scrabble defines its own criteria functions - &lt;span style="font-style:italic;"&gt;only_letters_in_tray, all_letters_in_tray, and any_letters_in_tray&lt;/span&gt;. But they are essentially just wrappers around the String criteria functions. This is a testament to how nice and reusable those original functions were, and why I luck out and don't have to explain them :)&lt;br /&gt;&lt;br /&gt;The find here simply takes N criteria, and passes wrapped functions onto the String searchFor method. Line 14 is pretty insane, especially &lt;span style="font-style:italic;"&gt;criteria.map( _(word) ):_*&lt;/span&gt;. It certainly takes some experience before being able to read (or write that line). Fortunately, as a user, the code is absurdly simple, so it doesn't really matter. &lt;br /&gt;&lt;br /&gt;That's all for now. I hope this helped. &lt;br /&gt;&lt;br /&gt;Anyone want to play me in Scrabble?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2522550187058050667?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2522550187058050667/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/using-scala-first-class-functions-by.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2522550187058050667'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2522550187058050667'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/using-scala-first-class-functions-by.html' title='Using Scala First Class Functions By Name'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4277902763198349944</id><published>2008-12-20T12:55:00.000-08:00</published><updated>2009-01-31T17:22:57.857-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ruby'/><category scheme='http://www.blogger.com/atom/ns#' term='pimp my library'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Ruby over Scala</title><content type='html'>As promised, here is where I'll be maintaining the things I like about Ruby better than Scala. In general, I do think I prefer programming in Scala, but certainly some of the things I can do in Ruby are much easier. If you're looking the other post, its here: &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/12/scala-over-ruby.html"&gt;Scala over Ruby&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;This list is my no means complete and as with the other list, I'll be appending to it here as I learn more.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Pimp My Library&lt;/h3&gt;&lt;br /&gt;I'll dive into some general theory about this first, but for those who just want to see the code, just scroll down. &lt;br /&gt;&lt;br /&gt;There's been so many times when I've needed to add methods to classes, for good reasons. Well, I suppose I didn't "need" to, but the main good reason of course is readability. Having your data and operations on that data in one place is nice. Calling those operations consistently is very important. &lt;br /&gt;&lt;br /&gt;Let's use an example in Scala. I couldn't find a "compact" method on List. It like seems it should be there. It's certainly useful. I could just create a method called compact, which takes a List, like so:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  def compact[T]( list: List[T] ) = l.filter( _ != null )&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;But as I just said, calling operations on your data consistently is important for readability. Having this method forces me to call my operations differently. It's confusing calling some methods as infix, and some as prefix. Sometimes I say myList.whatever, and other times I say whatever(myList). The situation is even worse if that method takes arguments. myList.whatever(x), or whatever(myList, x). Inconsistent, confusing, ugly.&lt;br /&gt;&lt;br /&gt;One solution is to simply add that method to the class you're operating on. Scala and Ruby both provide mechanisms for doing so, but they differ greatly. In Scala, I have to provide an implicit conversion from the class I'm operating on to a class that has a the method that I want to call. Here is the code:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  class Compactable[T](l: List[T]){&lt;br /&gt;    def compact = l.filter( _ != null )&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  implicit def compactableList[T]( l: List[T] ) = new Compactable(l)&lt;br /&gt;&lt;br /&gt;  val list = List( 1, null, 2, null, 3, null )&lt;br /&gt;  &lt;br /&gt;  println(list) // prints all values including the nulls&lt;br /&gt;  println(l.compact) // prints just the values 1, 2, and 3&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This isn't terrible, but it really clouds my actual intent: I just want to add a compact method to List. Why should I have to convert it to something else, only to have the compiler figure out what I really wanted? While there are some other great uses for implicit conversions, in this particular case something that should be very simple has been made overly complex. Maybe there is a better way of doing this in Scala but I haven't seen it. In addition, I've seen this pattern so many times in Scala code written by other people, so I don't think there is a different way. This code is really just boilerplate. &lt;br /&gt;&lt;br /&gt;In Ruby things are much more straight forward. &lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  module Enumerable&lt;br /&gt;    def collect_with_index&lt;br /&gt;      idx = -1&lt;br /&gt;      collect{|elm| idx = idx + 1; yield(idx, elm)}&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;(Note: I've used a different method because the compact method already exists. I couldn't find a collect_with_index method.)&lt;br /&gt;&lt;br /&gt;Here, I essentially just open up Enumerable and add the method to it.  Done. The intent is preserved. Everything is clear, and simple. So simple in fact, that I don't even think I need to explain it. &lt;br /&gt;&lt;br /&gt;I could imagine something very similar existing in Scala. &lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;  extend trait List[T]{&lt;br /&gt;    def compact = filter( _ != null )&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;This doesn't violate encapsulation because I'm not accessing any internals of List that aren't available to me otherwise. This could just be syntactic sugar for the Scala code above. Maybe someday.&lt;br /&gt;&lt;br /&gt;Also, I think C# has similar mechanisms, but I'm admitting my inexperience. I'd love to see replies on how this is done in other languages.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Classes are Objects&lt;/h3&gt;&lt;br /&gt;In Scala, and Java, classes aren't really objects, at least the way they should be. Ruby (and I'm sure Smalltalk, and other languages) gets this right. &lt;br /&gt;&lt;br /&gt;I had a discussion with my friend the other day and he asked, "what do you mean? I can call getClass on an object, and call methods on that class...". Eh, you can, but its still a weird fabrication. To a Rubyist, its laughable. So, without further ado, here's an example for Java programmers (in Java because Scala doesn't have static methods)&lt;br /&gt;&lt;br /&gt;Let's say I have a simple little interface for a factory that creates Connection objects, and an implementation.&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;interface ConnectionFactory{&lt;br /&gt;  Connection createConnection( String user, String pass );&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class ConnectionFactoryImpl implements ConnectionFactory{&lt;br /&gt;  Connection createConnection( String user, String pass ){&lt;br /&gt;    return new WhateverConnection( user, pass );&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Then I have a client that uses a ConnectionFactory:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;class ConnectionFactoryClient{&lt;br /&gt;&lt;br /&gt;  ConnectionFactory factory;&lt;br /&gt;&lt;br /&gt;  ConnectionFactoryClient( ConnectionFactory factory ){&lt;br /&gt;    this.factory = factory;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  void doIt(){&lt;br /&gt;    Connection c = factory.createConnection( "dood", "secret" );&lt;br /&gt;    c.connect();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Now, imagine I had a class that had createConnection as a static method like so:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;class ConnectionFactoryClass{&lt;br /&gt;  static Connection createConnection( String user, String pass ){&lt;br /&gt;    return new OtherConnection( user, pass )&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;You can see that the class itself seems like an object that implements the ConnectionFactory interface. If classes were really first class objects, and the class objects themselves could implement interfaces, then I could pass this class into the client like so:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;new ConnectionFactoryClient( ConnectionFactoryClass )&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;You can do this easily in Ruby. This is because classes in Ruby are objects that respond to messages. They aren't really much different than the instances they create, just that the instances respond to a different set of messages the class.&lt;br /&gt;&lt;br /&gt;I'm not advocating static methods here. This is something different entirely. Because the class is an object, and can be swapped out for a different object, you're not really statically bound to using that class the same way you would be in Java. &lt;br /&gt;&lt;br /&gt;If classes could implement interfaces, you wouldn't have to go through the pain of creating a Factory instance, and passing that in, like this:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;ConnectionFactory cf = new ConnectionFactoryImpl()&lt;br /&gt;new ConnectionFactoryClient( cf )&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;Why go through the pain of creating a new class, and a new instance of a class, when you could use the class object itself. For the most part, classes are factories anyway. &lt;br /&gt;&lt;br /&gt;Consider the following common pattern:&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;class MySQLConnection{&lt;br /&gt;  static public void createConnection( String user, String pass ){&lt;br /&gt;    new MySQLConnection( user, pass );&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private MySQLConnection( String user, String pass ){ ... }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;All the create logic is in one place, and the class is the factory. This, I think, is a good thing. &lt;br /&gt;&lt;br /&gt;How could this be done you ask? To make this work with static typing, the language would have to have some construct that allows class objects to implement interfaces. It could look something like so (purpose any syntax you wish):&lt;br /&gt;&lt;font color="#6698FF"&gt;&lt;pre&gt;&lt;br /&gt;class MySQLConnection &lt;br /&gt; (class implements ConnectionFactory) &lt;br /&gt; (instances implement Connection){&lt;br /&gt; &lt;br /&gt;  static public void createConnection( String user, String pass ){&lt;br /&gt;    new MySQLConnection( user, pass );&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private MySQLConnection( String user, String pass ){ ... }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/font&gt;&lt;br /&gt;We could probably take this even further to allow the constructors to serve as the implementations of the interface methods (maybe by giving constructors aliases). &lt;br /&gt;&lt;br /&gt;One final note, in Scala, this would eliminate the need for the top level object that gets created when you define a case class. The class itself could be the object, and it would contain the apply method. &lt;br /&gt;&lt;br /&gt;Anyway, that got long. I need to do something to structure this list a bit better.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4277902763198349944?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4277902763198349944/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/ruby-over-scala.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4277902763198349944'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4277902763198349944'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/ruby-over-scala.html' title='Ruby over Scala'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4087498930285270593</id><published>2008-12-17T09:54:00.001-08:00</published><updated>2009-04-11T19:43:40.494-07:00</updated><title type='text'>Scala over Ruby</title><content type='html'>In this post, I'll be maintaining a list of things I like more about Scala, over Ruby. I am also maintaining a similar, opposite list - &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/12/ruby-over-scala.html"&gt;Ruby over Scala&lt;/a&gt;. I plan on maintaining this list here and adding more to it over time, as opposed to several posts. I'm not exactly sure how that works with feeds and things, but oh well.&lt;br /&gt;&lt;br /&gt;Also, if at any point I'm totally wrong (which is very possible because I'm new to Ruby), please let me know! It's likely that I just didn't know I could do something in Ruby. I'm eager to learn, and for new ideas, and I'll be more than happy to update the post. Anyway, Onward...&lt;br /&gt;&lt;h3&gt;&lt;br /&gt;&lt;/h3&gt;&lt;h3&gt;1. Scala doesn't make you use the "." operator when calling methods.&lt;/h3&gt;This one I'll try to explain using some simple examples. Here is some Ruby code:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;x = 5&lt;br /&gt;y = 6&lt;br /&gt;z = x + y&lt;br /&gt;z2 = x.+y&lt;br /&gt;&lt;br /&gt;class ClassWithPlusMethod&lt;br /&gt;  def +(other)&lt;br /&gt;   # do something, doesnt matter what...&lt;br /&gt;   return "whatever"&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;x = ClassWithPlusMethod.new&lt;br /&gt;y = ClassWithPlusMethod.new&lt;br /&gt;z = x + y&lt;br /&gt;z2 = x.+y&lt;br /&gt;&lt;br /&gt;class SomeOtherClass&lt;br /&gt;  def plus(other)&lt;br /&gt;   # do something, doesnt matter what...&lt;br /&gt;   return "whatever"&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;x = SomeOtherClass.new&lt;br /&gt;y = SomeOtherClass.new&lt;br /&gt;z = x plus y&lt;br /&gt;&lt;br /&gt;(irb):25: warning: parenthesize argument(s) for future version&lt;br /&gt;NoMethodError: undefined method `plus' for main:Object&lt;br /&gt;from (irb):25&lt;br /&gt;&lt;br /&gt;z2 = x.plus y # this is ok!&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As you can see, Ruby has magic handling of + mathematical "operator" (and others). "+" is a simple method call, but since it's name is +, Ruby doesn't require the dot, its interpreter handles it differently. This magic is built into the language, and does not extend to methods with regular names, as shown above with "plus".&lt;br /&gt;&lt;br /&gt;In Scala, the . operator is not mandatory on any method call. This may seem trivial, but it is not. It helps in creating cleaner DSL's. Take for example, my post on &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/equalizer.html"&gt;Equalizer&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;In Scala, I was able to add the mustBe method to Any, and call it very nicely. But, in Ruby, I had to put in the dot. Contrast these examples:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;x mustBe 5&lt;br /&gt;&lt;br /&gt;vs&lt;br /&gt;&lt;br /&gt;x.must_be 5&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;2. Method overloading is good.&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;I use method overloading a lot. An awful lot. I love it. I don't think I need to explain it however. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;3. Scala's apply method.&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Scala's apply method is something that I'm pretty sure just doesn't exist at all in Ruby, and I'm not sure it can be done easily. For those who don't know what it is, I'll explain, and maybe some Rubyists can show some similar examples. Given that I'm still not a Ruby expert, I could be totally wrong. If so, I would like to know.&lt;br /&gt;&lt;br /&gt;For any method called apply, ".apply" can be omitted from the method call. For example given the following definition of the class Array:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Array{&lt;br /&gt;  def get(index:Int) = { ...some code to get from the array... }  &lt;br /&gt;  def apply(index:Int) = get(index)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And an instance of that class:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val a = new Array(whatever)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Then the following calls are essentially equivalent:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;a.get(7) // though only because apply calls get&lt;br /&gt;a.apply(7)&lt;br /&gt;a(7)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is really useful in cleaning up syntax. However, the real beauty of it is hidden below the surface, and will be the subject of a future post. &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;4. Ruby faking keyword parameters to methods&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Calling methods with keyword params is nice for client code readability. For example:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;c = httpConnection( :host =&gt; "google.com", :port =&gt; 80 )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;However, in Ruby the niceness ends at the client code. The library code to support this is abysmal. The reason being, for the method using those parameters, its not at all obvious what the method requires. You have to dig down into the implementation to find out what it actually pulls out of params. This is not ok with me. When I look at a method signature, I should be able to understand what dependencies the method has. Example: &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def httpConnection(params)&lt;br /&gt;  ...&lt;br /&gt;  ...&lt;br /&gt;  port = params[:port]&lt;br /&gt;  ...&lt;br /&gt;  ...&lt;br /&gt;  host = params[:host]&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;5. 1 vs. 3 line method defs.&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;I run into this one a lot, and find that Ruby code ends up being a lot larger than Scala code for this reason. In Ruby, I can't define a method on one line without it looking simply terrible. Example:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def add7(x)&lt;br /&gt;  x + 7&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;or&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def add7(x); x + 7; end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The first version is 3 lines when it doesn't need to be. The second version is one line littered with noise. &lt;br /&gt;&lt;br /&gt;Here's the much simpler Scala version:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def add7(x:Int) = x + 7&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;While this entire point might sound trivial, its not. Functional style encourages us to write many small methods. Ruby code grows larger than Scala code quickly. The problem also becomes bad when using nested functions. Ruby:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def add7(x)&lt;br /&gt;  def add3&lt;br /&gt;    x + 3&lt;br /&gt;  end&lt;br /&gt;  add3 + 4&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Scala:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def add7(x:Int) = {&lt;br /&gt;  def add3 = x + 3&lt;br /&gt;  add3 + 4&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All of this might seem rather trivial, but in practice it definitely adds up.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4087498930285270593?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4087498930285270593/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/scala-over-ruby.html#comment-form' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4087498930285270593'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4087498930285270593'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/scala-over-ruby.html' title='Scala over Ruby'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2165763662407453385</id><published>2008-12-16T19:35:00.000-08:00</published><updated>2008-12-20T14:21:28.360-08:00</updated><title type='text'>Coming Soon</title><content type='html'>For people that care (probably just myself, but I hold out hope), I'm going to spew out a list of the things I'm working on, posts that can be expected in the near future, and other random crap.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;The project I was working on was indeed cancelled, as &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/back.html"&gt;predicted&lt;/a&gt;. In hindsight, I'm coming out looking pretty smart. I expect to write some more of my true feelings on this situation. One sad thing of course is that my good friends and old coworkers may soon have to look for new jobs. I hope not.&lt;/li&gt;&lt;li&gt;Ruby is nice. I won't say that it's not as nice as Scala, as I may be attacked by the very vocal Ruby community. But I will say that I enjoy writing Scala much more (I do plan to expand on why, but this isn't the right time). However, some of the dynamic things you can do with Ruby are fascinating.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Rails is nice as well, though I think it has its flaws. I hope to learn &lt;a href="http://liftweb.net/"&gt;Lift&lt;/a&gt; very soon and do a nice comparison. We'll see if I have enough time.&lt;/li&gt;&lt;li&gt;Today I started reading about building Facebook apps in Rails. This is something I'll likely dedicate a lot of time to.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Yesterday I learned a bunch about iPhone development. I haven't written anything yet, just had a big walk-through of a pretty popular application. At first glance it seemed fantastic as Apple has made creating views quite simple. This is great because I'm terrible at any visual stuff. Anyway, this is the thing that I will probably end up dedicating the most time to; mostly because I still hold out hope for entrepreneurship.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;I am loving my new job. Leaving NYSE has turned out to be a fantastic decision. My new team is great. I'm re-energized. I'm challenged. I'm actually learning at work, instead of just at home. Learning is encouraged, not shunned. I love it. &lt;br /&gt;&lt;/li&gt;&lt;li&gt;Lastly, I told myself about a year ago that I wouldn't be getting back into web development. This has changed for a few reasons:&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;I will still never ever ever try to make things look nice.&lt;/li&gt;&lt;li&gt;It seems like the frameworks available today eliminate most of the rest of the crap that I didn't want to do before.&lt;/li&gt;&lt;li&gt;Having immediate access to millions of users on Facebook seems really exciting, eliminating more crap that I was never any good at - getting people to come to my site.&lt;/li&gt;&lt;li&gt;Most importantly, I have an opportunity to learn new languages, and obviously that's what I really care about&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2165763662407453385?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2165763662407453385/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/coming-soon.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2165763662407453385'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2165763662407453385'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/12/coming-soon.html' title='Coming Soon'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-9013350604538095988</id><published>2008-11-28T21:37:00.000-08:00</published><updated>2008-12-25T23:55:37.267-08:00</updated><title type='text'>foldLeft in Scala, Little Schemer style</title><content type='html'>I'm going to write up a Scala version of foldLeft in the style of &lt;a href="http://www.ccs.neu.edu/home/matthias/BTLS/"&gt;The Little Schemer&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;What is 0 + (1 + 2 + 3)?&lt;br /&gt;&lt;br /&gt;&gt;6&lt;br /&gt;&lt;br /&gt;What is 0 + (1 + 2 + 3)?&lt;br /&gt;&lt;br /&gt;&gt;0 + 1 + (2 + 3)&lt;br /&gt;&lt;br /&gt;What is 0 + 1?&lt;br /&gt;&lt;br /&gt;&gt;1&lt;br /&gt;&lt;br /&gt;What is 1 + (2 + 3) ?&lt;br /&gt;&lt;br /&gt;&gt;1 + 2 + (3)&lt;br /&gt;&lt;br /&gt;What is 1 + 2? &lt;br /&gt;&lt;br /&gt;&gt;3&lt;br /&gt;&lt;br /&gt;What is 3 + (3)?&lt;br /&gt;&lt;br /&gt;&gt;3 + 3&lt;br /&gt;&lt;br /&gt;What is 3 + 3?&lt;br /&gt;&lt;br /&gt;&gt;6&lt;br /&gt;&lt;br /&gt;Are we done? &lt;br /&gt;&lt;br /&gt;&gt;No, we still haven't found out what foldLeft is.&lt;br /&gt;&lt;br /&gt;What is foldLeft?&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def foldLeft[A, B](as: List[A], z: B)(f: (B, A) =&gt; B): B = {&lt;br /&gt;    as match {&lt;br /&gt;      case Nil =&gt; z&lt;br /&gt;      case x :: xs =&gt; foldLeft( xs, f(z, x) )( f )&lt;br /&gt;    }&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;But that doesn't tell us much does it? Let's walk through an example.&lt;br /&gt;&lt;br /&gt;What is List( 1, 2, 3 )?&lt;br /&gt;&lt;br /&gt;&gt;List( 1, 2, 3 )&lt;br /&gt;&lt;br /&gt;What is foldLeft(a, 0){ (x,y) =&gt; x + y } when a is List( 1, 2, 3 )&lt;br /&gt;&lt;br /&gt;&gt;6 ... but why? Let's step through it together.&lt;br /&gt;&lt;br /&gt;What is the first question foldLeft asks about the list?&lt;br /&gt;&lt;br /&gt;&gt;case Nil &lt;br /&gt;&lt;br /&gt;Is a Nil?&lt;br /&gt;&lt;br /&gt;&gt;No, it's List( 1, 2, 3 ), so we ask the next question.&lt;br /&gt;&lt;br /&gt;What is the next question?&lt;br /&gt;&lt;br /&gt;&gt;case x :: xs&lt;br /&gt;&lt;br /&gt;What is the value of case x :: xs?&lt;br /&gt;&lt;br /&gt;&gt;true, because the list is not Nil, it contains one element x which is 1, followed by a list xs which is List(2,3).&lt;br /&gt;&lt;br /&gt;So what is the next step?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( xs, f(z, x) )( f )&lt;br /&gt;&lt;br /&gt;What is f( z, x )?&lt;br /&gt;&lt;br /&gt;&gt; Well, remember, we called foldLeft like so: foldLeft(a, 0){ (x,y) =&gt; x + y } &lt;br /&gt;&lt;br /&gt;And what is f?&lt;br /&gt;&lt;br /&gt;&gt; { (x,y) =&gt; x + y } &lt;br /&gt;&lt;br /&gt;Again, what is f( z, x )?&lt;br /&gt;&lt;br /&gt;&gt; f( 0, 1 )&lt;br /&gt;&gt; (0,1) =&gt; 0 + 1&lt;br /&gt;&gt; 1&lt;br /&gt;&lt;br /&gt;So what has foldLeft( xs, f(z, x) )( f ) become?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( List(2,3), 1 )( f )&lt;br /&gt;&lt;br /&gt;Now we recur into foldLeft. What is the first question foldLeft asks about the list?&lt;br /&gt;&lt;br /&gt;&gt;case Nil &lt;br /&gt;&lt;br /&gt;Is a Nil?&lt;br /&gt;&lt;br /&gt;&gt;No, it's List( 2, 3 ), so we ask the next question.&lt;br /&gt;&lt;br /&gt;What is the next question?&lt;br /&gt;&lt;br /&gt;&gt;case x :: xs&lt;br /&gt;&lt;br /&gt;What is the value of case x :: xs?&lt;br /&gt;&lt;br /&gt;&gt;true, because the list is not Nil, it contains one element x which is 2, followed by a list xs which is List(3).&lt;br /&gt;&lt;br /&gt;So what is the next step?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( xs, f(z, x) )( f )&lt;br /&gt;&lt;br /&gt;What is f( z, x )? Remember that z is now 1.&lt;br /&gt;&lt;br /&gt;&gt; f( 1, 2 )&lt;br /&gt;&gt; (1,2) =&gt; 1 + 3&lt;br /&gt;&gt; 3&lt;br /&gt;&lt;br /&gt;So what has foldLeft( xs, f(z, x) )( f ) become?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( List(3), 3 )( f )&lt;br /&gt;&lt;br /&gt;Now we recur into foldLeft. What is the first question foldLeft asks about the list?&lt;br /&gt;&lt;br /&gt;&gt;case Nil &lt;br /&gt;&lt;br /&gt;Is a Nil?&lt;br /&gt;&lt;br /&gt;&gt;No, it's List(3), so we ask the next question.&lt;br /&gt;&lt;br /&gt;What is the next question?&lt;br /&gt;&lt;br /&gt;&gt;case x :: xs&lt;br /&gt;&lt;br /&gt;What is the value of case x :: xs?&lt;br /&gt;&lt;br /&gt;&gt;true, because the list is not Nil, it contains one element x which is 3, followed by a list xs which is Nil.&lt;br /&gt;&lt;br /&gt;So what is the next step?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( xs, f(z, x) )( f )&lt;br /&gt;&lt;br /&gt;What is f( z, x )? Remember that z is now 3.&lt;br /&gt;&lt;br /&gt;&gt; f( 3, 3 )&lt;br /&gt;&gt; (3,3) =&gt; 3 + 3&lt;br /&gt;&gt; 6&lt;br /&gt;&lt;br /&gt;So what has foldLeft( xs, f(z, x) )( f ) become?&lt;br /&gt;&lt;br /&gt;&gt; foldLeft( Nil, 6 )( f )&lt;br /&gt;&lt;br /&gt;Now we recur into foldLeft. What is the first question foldLeft asks about the list?&lt;br /&gt;&lt;br /&gt;&gt;case Nil &lt;br /&gt;&lt;br /&gt;Is a Nil?&lt;br /&gt;&lt;br /&gt;&gt;Yes &lt;br /&gt;&lt;br /&gt;So what do we do?&lt;br /&gt;&lt;br /&gt;&gt; case Nil =&gt; z&lt;br /&gt;&lt;br /&gt;And what is z?&lt;br /&gt;&lt;br /&gt;6!&lt;br /&gt;&lt;br /&gt;So what is foldLeft(a, 0){ (x,y) =&gt; x + y } when a is List( 1, 2, 3 )&lt;br /&gt;&lt;br /&gt;6!&lt;br /&gt;&lt;br /&gt;Are we done?&lt;br /&gt;&lt;br /&gt;Yes! Now foldLeft a taco right into your mouth.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-9013350604538095988?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/9013350604538095988/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/foldleft-in-scala-little-schemer-style.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9013350604538095988'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9013350604538095988'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/foldleft-in-scala-little-schemer-style.html' title='foldLeft in Scala, Little Schemer style'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1020414523510129827</id><published>2008-11-24T23:01:00.000-08:00</published><updated>2008-11-28T22:22:38.715-08:00</updated><title type='text'>Refactoring Imperative Code To Functional Code</title><content type='html'>I've been refactoring Scala literally for days. It's fantastic how much I've learned over the last year. I knew a little bit about functional programming from doing Lisp in college, but a year and a half ago I couldn't have given you the definition of it. &lt;br /&gt;&lt;br /&gt;I decided to tackle some of the most obvious (and ugly) imperative/procedural code in my CPU simulator and turn it into an elegant, functional style. &lt;br /&gt;&lt;br /&gt;I'll paste the original code here, then explain it a bit, then show the refactorings one step at a time. In explaining, I will assume that you know at least a bit about how anonymous functions work in Scala. &lt;br /&gt;&lt;b&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class EightBitAdder( a: EightBitNumber, &lt;br /&gt;                     b: EightBitNumber, &lt;br /&gt;                     carryIn: PowerSource ) {&lt;br /&gt;&lt;br /&gt;  private val fullAdders: Array[FullAdder] = createFullAdders( a, b, carryIn )&lt;br /&gt;  private val output: EightBitNumber = createOutput()&lt;br /&gt;  &lt;br /&gt;  def getOutput: EightBitNumber = output&lt;br /&gt;  def getCarryOut: PowerSource = fullAdders(7).getCarryOut&lt;br /&gt;  &lt;br /&gt;  &lt;br /&gt;  private def createFullAdders( a: EightBitNumber, &lt;br /&gt;                                b: EightBitNumber, &lt;br /&gt;                                carryIn: PowerSource ): Array[FullAdder] = {&lt;br /&gt;    val fullAdders = new Array[FullAdder](8)&lt;br /&gt;    fullAdders(0) = new FullAdder( a(0), b(0), carryIn );&lt;br /&gt;    for( i &lt;- 1 until 8 ){&lt;br /&gt;      fullAdders(i) = new FullAdder(a(i),b(i), fullAdders(i-1).getCarryOut);&lt;br /&gt;    }&lt;br /&gt;    fullAdders&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  private def createOutput(): EightBitNumber = {&lt;br /&gt;    val out = new Array[PowerSource](8)&lt;br /&gt;    &lt;br /&gt;    var count = 0;&lt;br /&gt;    fullAdders.foreach( p =&gt; {  &lt;br /&gt;      out(count) = p.getSumOut &lt;br /&gt;      count = count + 1&lt;br /&gt;      } &lt;br /&gt;    )&lt;br /&gt;    new EightBitNumber(out)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt; &lt;br /&gt;&lt;/b&gt;&lt;br /&gt;This code was designed to build an 8 bit adder out of two 8 bit numbers (numbers in this particular case aren't much more than arrays of bits) and a carry in bit. This is your typical, ordinary, everyday 8 bit adder that you much have seen in 1950. The adders job is simple, output the result of the two input numbers added up. As with any 8 bit adder, there are 9 outputs, 8 standard output bits, and the carry out/overflow bit.&lt;br /&gt;&lt;br /&gt;The adder accomplishes addition in a standard fashion, by chaining 8 full adders (one bit adders) together. The first full adder in the chain uses the given carry in bit as its carry in bit, and subsequent adders in the chain use the carry out of the previous full adder as the carry in. The carry out of the entire adder is simply the carry out of the last full adder in the chain. Here is a picture of one:&lt;br /&gt;&lt;br /&gt;&lt;img src="http://www.electrion.ro/documentatii/lessons-in-electric-circuits/Digital/04459.png"/&gt;&lt;br /&gt;&lt;br /&gt;Now that we have all the background out of the way, I'll start the refactorings. I'm actually going to go a little bit in reverse order, refactoring the createOutput() method first, because it is substantially easier to refactor than the createFullAdders method.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Simple Refactoring&lt;/h2&gt;&lt;br /&gt;Lets take another look at createOutput:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;  private def createOutput(): EightBitNumber = {&lt;br /&gt;    val out = new Array[PowerSource](8)&lt;br /&gt;    &lt;br /&gt;    var count = 0;&lt;br /&gt;    fullAdders.foreach( p =&gt; {  &lt;br /&gt;      out(count) = p.getSumOut &lt;br /&gt;      count = count + 1&lt;br /&gt;      } &lt;br /&gt;    )&lt;br /&gt;    new EightBitNumber(out)&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;This method is returning an EightBitNumber, which is really just an array holding the 8 output bits. The code is terribly imperative, and terribly terrible. The sad thing is, I actually wrote this code, and I'm not just making up a bad example :(  Anyway, its overall strategy is pretty clear. &lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Create an empty, length 8 array&lt;br /&gt;&lt;li&gt;Create a counter object for indexing into the array&lt;br /&gt;&lt;li&gt;Loop over all the full adders (those are already create by the time this method gets called, and well see that in a bit)&lt;br /&gt;&lt;li&gt;For each adder: Put each full adders sum out into the array, and increment the counter.&lt;br /&gt;&lt;li&gt;Finally, create an 8 bit number object using the array.&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;The first 4 steps above are there simply to create the array to pass to the EightBitNumber object. Now lets take a look at the refactored code:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;private val output = new EightBitNumber(fullAdders.map(fa =&gt; fa.getSumOut))&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;Wow! That looks a lot easier - 12 lines down to 1! But...some people might not know what it does, so I'll do my best to explain. The map method, which is a method on all Seq objects (short for Sequence; Array is a subclass), "Returns the list resulting from applying the given function &lt;code&gt;f&lt;/code&gt; to each element of this list." An example should help.&lt;br /&gt;&lt;br /&gt;Given a=List(1,2,3,4,5) then a.map( i =&gt; i * 10 ) returns List(10,20,30,40,50). i * 10 was applied to each element "i" in the list.&lt;br /&gt;&lt;br /&gt;In the cpu simulator code above, the call to map has built an Array containing the sumOut of each full adder using the function fa =&gt; fa.getSumOut. &lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Slightly More Difficult Refactoring&lt;/h2&gt;&lt;br /&gt;With the easier part out of the way, I tackled the more difficult createFullAdders. Let's review the original implementation again.&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;  private def createFullAdders( a: EightBitNumber, &lt;br /&gt;                                b: EightBitNumber, &lt;br /&gt;                                carryIn: PowerSource ): Array[FullAdder] = {&lt;br /&gt;    val fullAdders = new Array[FullAdder](8)&lt;br /&gt;    fullAdders(0) = new FullAdder( a(0), b(0), carryIn );&lt;br /&gt;    for( i &lt;- 1 until 8 ){&lt;br /&gt;      fullAdders(i) = new FullAdder(a(i),b(i), fullAdders(i-1).getCarryOut);&lt;br /&gt;    }&lt;br /&gt;    fullAdders&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt; &lt;br /&gt;This method is responsible for creating all the full adders, and chaining them together. The  createOutputs method was only responsible for getting all the outputs off of the full adders created here. &lt;br /&gt;&lt;br /&gt;Similar to the last method, this method uses an imperative style, creating an array, populating it, and finally returning it. It's quite a bit trickier though because of the chaining. You can't simply use the map function because there's no context in map. Here, each new full adder needs to know about the preceding full adder. This guy is going to be a bear to explain, but let me just go ahead and dump the code on you:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;val (fullAdders, carryOut) =&lt;br /&gt;    (as zip bs).foldLeft((List[FullAdder](),carryIn)){&lt;br /&gt;      case ((current, carry), (a, b)) =&gt;&lt;br /&gt;        val adder = new FullAdder(a, b, carry)&lt;br /&gt;        (current ::: List(adder),adder.carryOut)&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt; &lt;br /&gt;With James Iry's help, we've made this code about as simple as possible. With the first pass, I wasn't sure if the functional code was more readable than the imperative, but after he helped me clean it up, I'm positive. Now, if you aren't familiar with some of the concepts contained in that code, you might be thinking, "What are you $%^&amp;ing nuts?" But, I'm convinced that after you get used to reading this, it's so much easier to read, and so much less error prone, and so much more natural, that you'll never go back. Honestly, after leaving this project alone for almost a year and coming back to it and finding the imperative code, I almost threw up in my mouth a little.&lt;br /&gt;&lt;br /&gt;Okay, now I'll try to explain these concepts, and most likely fail miserably. &lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;First, and simplest, is zip. This one is pretty easy. Taken right from the Scaladoc - zip: &lt;p&gt;"Returns a list formed from this list and the specified list 'that' by associating each element of the former with the element at the same position in the latter. If one of the two lists is longer than the other, its remaining elements are ignored."&lt;/p&gt;&lt;br /&gt;I think a few examples will explain perfectly. &lt;br /&gt;&lt;br /&gt;Given a=List(1,2,3) and b=List(a,b,c) then a.zip(b) will return List((1,a), (2,b), (3,c)). &lt;br /&gt;Given a=List(1,2,3) and b=List(a,b,c,x,y,x) then a.zip(b) will return List((1,a), (2,b), (3,c)), as the remaining elements in b are ignored.&lt;br /&gt;&lt;br /&gt;The code in the cpu simulator zips as and bs, which associates the appropriate input bits together. Take a quick look back at the picture to see that this returns ((a0,b0),(a1,b1),(a2,b2),(a3,b3),(a4,b4),(a5,b5),(a6,b6),(a7,b7)).&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Next is foldLeft, which is a bit more complicated. Once again, from the Scaladoc - foldLeft:&lt;br /&gt;&lt;p&gt;Combines the elements of this list together using the binary function &lt;code&gt;f&lt;/code&gt;, from left to right, and starting with the value &lt;code&gt;z&lt;/code&gt;.&lt;/p&gt; &lt;br /&gt;&lt;br /&gt;This one I've written up separately, because it was so long. You can find it at &lt;a href="http://jackcoughonsoftware.blogspot.com/2008/11/foldleft-in-scala-little-schemer-style.html"&gt;http://jackcoughonsoftware.blogspot.com/2008/11/foldleft-in-scala-little-schemer-style.html&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;Next is pattern matching, but I have to go to bed again! At least I've made some progress :)&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Revised Code&lt;/h2&gt;&lt;br /&gt;Here is the finshed product, which no longer uses 8, but instead creates adder chains of N, depending on the length of the inputs. Overall, I think it's a vast improvement over the original. &lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;class AdderChain(as: Number, bs: Number, carryIn: PowerSource) {&lt;br /&gt;&lt;br /&gt;  if( as.size != bs.size ) error("numbers must be the same size")&lt;br /&gt;  &lt;br /&gt;  val (fullAdders, carryOut) =&lt;br /&gt;    (as zip bs).foldLeft((List[FullAdder](),carryIn)){&lt;br /&gt;      case ((current, carry), (a, b)) =&gt;&lt;br /&gt;        val adder = new FullAdder(a, b, carry)&lt;br /&gt;        (current ::: List(adder),adder.carryOut)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;  val output = new Number(fullAdders.map(fa =&gt; fa.sumOut))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1020414523510129827?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1020414523510129827/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/refactoring-imperative-code-to.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1020414523510129827'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1020414523510129827'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/refactoring-imperative-code-to.html' title='Refactoring Imperative Code To Functional Code'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8092172131265363690</id><published>2008-11-24T15:39:00.000-08:00</published><updated>2008-11-24T16:51:00.556-08:00</updated><title type='text'>Using Scala Implicits to Replace Mindless Delegation</title><content type='html'>I'm still refactoring my Scala CPU Simulator code, as I keep finding ways to just lop off piles of unneeded code. In this latest example, I was using pretty standard Java style delegation - having my class implement an interface, having a member variable of that interface, and delegating all method calls on that interface to the member variable.&lt;br /&gt;&lt;br /&gt;There are several problems with this:&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;The main problem: if I add a method to the interface I then have to add it to everyone implementing the interface. But, what If I'm not actually writing the implementation of the interface? Client code won't compile. Adding an implicit doesn't remove this problem entirely, but it certainly works for plain old delegates.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;It's error prone. Maybe the method was a void, and my IDE added the signature for the method, so the code compiles, but I forgot to actually delegate to the member. &lt;br /&gt;&lt;li&gt;It's just plain wordy and ugly. &lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;To remove the boilerplate, all I needed to do was add an implicit conversion from my class to the interface, using the member variable. I'll show this below.&lt;br /&gt;&lt;br /&gt;First, here is an example of the old, more wordy style:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;trait PowerSource{&lt;br /&gt;  def connect( p: PowerSource ): Unit&lt;br /&gt;  def disconnect( p: PowerSource ): Unit&lt;br /&gt;  def reconnect( p: PowerSource ): Unit&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class DelegateToPowerSource( in: PowerSource ) extends PowerSource {&lt;br /&gt;  def connect( p: PowerSource ) = in connect p&lt;br /&gt;  def disconnect( p: PowerSource ) = in disconnect p&lt;br /&gt;  def reconnect( p: PowerSource ) = in reconnect p&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;DelegateToPowerSource has a member, "p", and implements the PowerSource interface by delegating to that member for each of the methods on the PowerSource interface. The more methods that PowerSource has, the longer DelegateToPowerSource gets, and yet the code is just boilerplate. Even if the IDE does this for you, its still wordy and potentially error prone. &lt;br /&gt;&lt;br /&gt;Now for the new version:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;trait PowerSource{&lt;br /&gt;  def connect( p: PowerSource ): Unit&lt;br /&gt;  def disconnect( p: PowerSource ): Unit&lt;br /&gt;  def reconnect( p: PowerSource ): Unit&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object DelegateToPowerSource{&lt;br /&gt;  implicit def delegateToPowerSource( d: DelegateToPowerSource ) = d.p&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class DelegateToPowerSource( p: PowerSource )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;That's it. Now, any time I add a method to the PowerSource interface (I should probably start calling it trait), DelegateToPowerSource simply has that method; via the conversion. I never have to change DelegateToPowerSource because of a change to PowerSource. DelegateToPowerSource can simply have whatever code in it that it was originally intended to have, obviously augmenting PowerSource in some way. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;For completeness, I'll post the actual code where I did exactly this. But, it's pretty much the same, so if you get the point, no need to keep reading. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;trait LogicGate extends PowerSource{&lt;br /&gt;  val inputA: PowerSource&lt;br /&gt;  val inputB: PowerSource&lt;br /&gt;  val output: PowerSource&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;abstract class BaseLogicGate(val inputA: PowerSource, inputB: PowerSource) extends LogicGate {&lt;br /&gt;&lt;br /&gt;  def state = output.state&lt;br /&gt;  &lt;br /&gt;  def --&gt;( p: PowerSource ): PowerSource = output --&gt; p &lt;br /&gt;  def &lt;--( p: PowerSource ): PowerSource = output &lt;-- p &lt;br /&gt;  &lt;br /&gt;  def disconnectFrom( p: PowerSource ): PowerSource = output disconnectFrom p &lt;br /&gt;  def disconnectedFrom( p: PowerSource ): PowerSource = output disconnectedFrom p &lt;br /&gt;&lt;br /&gt;  def handleStateChanged( p: PowerSource ) = {}&lt;br /&gt;  def notifyConnections = {} &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class AndGate(a: PowerSource, b: PowerSource) &lt;br /&gt;  extends BaseLogicGate(a: PowerSource, b: PowerSource){&lt;br /&gt;  val output = new Relay(a, new Relay(b))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Of course there were several other LogicGates (or, nor, nand, etc). All of this was condensed down to:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object LogicGate{&lt;br /&gt;  implicit def logicGateToPowerSource( lg: LogicGate ): PowerSource = lg.output&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;trait LogicGate{&lt;br /&gt;  val inputA: PowerSource&lt;br /&gt;  val inputB: PowerSource&lt;br /&gt;  val output: PowerSource&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class AndGate(val inputA: PowerSource, val inputB: PowerSource) extends LogicGate{&lt;br /&gt;  val output = new Relay(inputA, new Relay(inputB))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;BaseLogicGate is now removed entirely. This is great because BaseLogicGate was really weird, it didn't even use its inputs. The only reason it was there was to decouple the delegation logic from the actual trait. &lt;br /&gt;&lt;br /&gt;Now things have become MUCH more clear. AndGate is a LogicGate with inputs A and B, and one output, made from Relays.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8092172131265363690?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8092172131265363690/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/using-scala-implicits-to-replace.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8092172131265363690'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8092172131265363690'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/using-scala-implicits-to-replace.html' title='Using Scala Implicits to Replace Mindless Delegation'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7953853479234975665</id><published>2008-11-18T21:04:00.000-08:00</published><updated>2008-11-18T21:41:13.117-08:00</updated><title type='text'>Equalizer</title><content type='html'>I wrote a cool Equalizer class in Scala that allows me to do assertions that are more readable than traditional assertions.&lt;br /&gt;&lt;br /&gt;Quick side note: (Equalizer is really an idea shamelessly stolen from Bill Venners Equalizer in ScalaTest. Hopefully we'll add my methods in as well.)&lt;br /&gt;&lt;br /&gt;My Equalizer lets me do things like:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;val x = 5&lt;br /&gt;x mustBe 5&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;This replaces the more common assertEquals( x, 5 ), and I think it does so nicely.&lt;br /&gt;&lt;br /&gt;You can also do a few more sophisticated things with it, like so:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;val x = 5&lt;br /&gt;x mustBe ( 3 or 4 or 5 )&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;I probably could have used "in" here, such as x mustBe in( 3, 4, 5 ) ... what do you think?&lt;br /&gt;&lt;br /&gt;Additionally:&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;val x = 5&lt;br /&gt;x cantBe 6&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;For whatever this one is worth (I've actually found use cases for it):&lt;br /&gt;&lt;b&gt;&lt;pre&gt;&lt;br /&gt;val x = false&lt;br /&gt;x canBeNullOr false&lt;br /&gt;&lt;br /&gt;val y = 6&lt;br /&gt;y canBeNullOr ( 5 or 6 )&lt;br /&gt;&lt;/pre&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;This works by implicitly converting Any to Equalizer, which contains the methods above. The code can be found below. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.testng.Assert._&lt;br /&gt;&lt;br /&gt;case object Equalizer {&lt;br /&gt;  implicit def anyToCompare(a: Any) = new Equalizer(a)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Equalizer(a: Any) {&lt;br /&gt;&lt;br /&gt;  def mustBe(bs: Any*): Unit = {&lt;br /&gt;    bs(0) match {&lt;br /&gt;      case x:MyTuple =&gt; x mustBe a&lt;br /&gt;      case _ =&gt; {&lt;br /&gt;        val message = "In Equalizer: expecting one of=" + bs + "\nIn Equalizer: actual  =" + a&lt;br /&gt;        println(message)&lt;br /&gt;        bs size match {&lt;br /&gt;          case 1 =&gt; assertEquals(a, bs(0), message)&lt;br /&gt;          case _ =&gt; assertTrue(bs.contains(a), message)&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def canBeNullOr(bs: Any*) = {&lt;br /&gt;    if (a != null) mustBe(bs: _*)&lt;br /&gt;    else println("In Equalizer: expecting one of=" + bs + " or null\nIn Equalizer: actual  =" + a)&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def cantBe(b: Any) = assertFalse(a == b)&lt;br /&gt;&lt;br /&gt;  def is(b: Any) = a equals b&lt;br /&gt;&lt;br /&gt;  def or(b: Any) = {&lt;br /&gt;    a match {&lt;br /&gt;      case x:MyTuple =&gt; x + b&lt;br /&gt;      case _ =&gt; MyTuple2(a, b)&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  import Equalizer._&lt;br /&gt;&lt;br /&gt;  trait MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple&lt;br /&gt;    def mustBe(a: Any): Unit&lt;br /&gt;  }&lt;br /&gt;  case class MyTuple2(y: Any, z: Any) extends MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple = MyTuple3(y, z, b)&lt;br /&gt;    def mustBe(a: Any): Unit = a mustBe (y,z)&lt;br /&gt;  }&lt;br /&gt;  case class MyTuple3(x: Any, y: Any, z: Any) extends MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple = MyTuple4(x, y, z, b)&lt;br /&gt;    def mustBe(a: Any): Unit = a mustBe (x,y,z)&lt;br /&gt;  }&lt;br /&gt;  case class MyTuple4(w: Any, x: Any, y: Any, z: Any) extends MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple = MyTuple5(w, x, y, z, b)&lt;br /&gt;    def mustBe(a: Any): Unit = a mustBe (w,x,y,z)&lt;br /&gt;  }&lt;br /&gt;  case class MyTuple5(v: Any, w: Any, x: Any, y: Any, z: Any) extends MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple = MyTuple6(v, w, x, y, z, b)&lt;br /&gt;    def mustBe(a: Any): Unit = a mustBe (v,w,x,y,z)&lt;br /&gt;  }&lt;br /&gt;  case class MyTuple6(u: Any, v: Any, w: Any, x: Any, y: Any, z: Any) extends MyTuple{&lt;br /&gt;    def +(b: Any): MyTuple = throw new IllegalArgumentException("too many ors")&lt;br /&gt;    def mustBe(a: Any): Unit = a mustBe (u,v,w,x,y,z)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Sorry about MyTuple...I wanted people to be able to use Tuples as arguments in their mustBe statements, so I had to make sure I didn't pass in a Tuple into mustBe, via the "or" method. Anyway, Tuples don't even appear to be working so....ugh... If anyone can help me clean this up, that would be awesome.&lt;br /&gt;&lt;br /&gt;Regardless, what do you think? I really like using the code in tests, even if the Equalizer class itself is a bit hairy.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7953853479234975665?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7953853479234975665/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/equalizer.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7953853479234975665'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7953853479234975665'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/equalizer.html' title='Equalizer'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8788800589737679838</id><published>2008-11-17T21:55:00.000-08:00</published><updated>2008-11-17T22:07:50.216-08:00</updated><title type='text'>Refactoring Scala: My CPU Simulator Revisited</title><content type='html'>I'm preparing to learn Ruby (though I've already tinkered with it some), and to do so, I'm going to revisit my CPU Simulator project that helped me learn Scala so well. I'm going to write it again in Ruby.&lt;br /&gt;&lt;br /&gt;So today, I took up revisiting it, with the goal in mind of writing some Ruby. Turned out that didn't actually happen. What did happen was a lot of refactoring of the original Scala code. I hadn't touched that code in several months, and in between then and now I've written a LOT of Scala. Here's some of the things I've learned (and refactored).&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;I used to use way too much redundant type information. This was a natural habit from writing Java for so long (in fact, pretty much all my bad habits stem from too much Java). I rigorously removed ALL the obviously redundant type declarations. I did find that in some cases it helped to have it there, that the code wasn't exactly clear without it, and so I left it. I'm very interested to see what happens here when I slide over to Ruby.&lt;/li&gt;&lt;li&gt;Out of habit, I used a lot of unneeded semi-colons. I removed all of them. I hate semi-colons. It's official.&lt;/li&gt;&lt;li&gt;I got a lot better at functional programming. There were a lot of areas where I should have used functions, and I refactored the code to do so. My line of code cound is down considerably.&lt;/li&gt;&lt;li&gt;Finally, I removed all the Hamcrest matchers. This one I'll explain in more detail in my post tomorrow. I'm basically using my own assert library that allows me to say things like: x mustBe 5   I prefer this style to any other assertions I've come across.&lt;br /&gt;&lt;/li&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8788800589737679838?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8788800589737679838/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/refactoring-scala-my-cpu-simulator.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8788800589737679838'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8788800589737679838'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/refactoring-scala-my-cpu-simulator.html' title='Refactoring Scala: My CPU Simulator Revisited'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5734918986234342922</id><published>2008-11-16T22:05:00.000-08:00</published><updated>2008-11-16T22:18:31.980-08:00</updated><title type='text'>Back</title><content type='html'>For the past several months I've been giving my life to a cause that I now believe will fail miserably. I've decided to leave the NYSE. I wasn't being challenged technically, and management was simply not up to snuff. They actually asked me to, "just drink the kool-aid". I swear.  &lt;br /&gt;&lt;br /&gt;I haven't been writing, and I haven't even been coding much, all to work on this Death March project. Basically, its been terrible, and I feel like I went into a coma and I've just come out. I'm going to start writing again passionately. &lt;br /&gt;&lt;br /&gt;I've accepted a new position where I'll be writing IPhone applications, Facebook apps with Rails, other web work with Rails, etc. I'm very excited about it. I get to learn two languages that I have little experience with (Ruby and Objective C). I get to work with a team that is much more in line with my way of thinking - adopting new technology, open-minded, agile, lots of tests, curious. It feels like a giant weight has been lifted off of my back. I'm very excited.&lt;br /&gt;&lt;br /&gt;Additionally, I won't have to work in Java anymore. I'm convinced at this point that java is a dying language. I heard Neal Gafter left Google to work on languages at Microsoft. &lt;br /&gt;&lt;br /&gt;I feel his situation parallels mine. He worked tirelessly on closures for Java 7, which he truly believed (as do many) were right for the language. But, the JCP is so damned conservative, that not only will his closures probably not make it into Java 7, but come on...will Java 7 ever actually come out?&lt;br /&gt;&lt;br /&gt;I worked tirelessly for NYSE, trying to introduce new technology and exciting ideas. I tried to bring in Scala, and was shot down. I tried to bring in a test first attitude and stress that we really needed time to work on the testing framework there in general, only to be shot down at every suggestion. I felt the same as I imagine Neal felt, "This is impossible". &lt;br /&gt;&lt;br /&gt;I believe NYSE ATS software projects will continue to fail until management is replaced. &lt;br /&gt;&lt;br /&gt;This was a bit of a rant, but it was a long time coming.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5734918986234342922?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5734918986234342922/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/back.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5734918986234342922'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5734918986234342922'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/11/back.html' title='Back'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6812599274010372015</id><published>2008-09-13T16:53:00.000-07:00</published><updated>2008-09-13T17:15:44.858-07:00</updated><title type='text'>Language Feature Request</title><content type='html'>Maybe this feature exists in some language, I'm not sure. My inexperience is letting me down. :( Here is what I want, as demonstrated in Scala.&lt;br /&gt;&lt;br /&gt;I want to be able to use the name of my variable programmatically.  So, instead of having to give my objects names like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class Server( name: String )&lt;br /&gt;val server = Server("Altair")&lt;br /&gt;println(server)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which yields: Server("Altair")&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;or like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Server( name: String ){ override def toString = name }&lt;br /&gt;val server = new Server("Altair")&lt;br /&gt;println(server)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which yields simply: Altair&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I would like something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case class Server extends VariableName&lt;br /&gt;val Altair = new Server&lt;br /&gt;println(Altair)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which yields simply: Altair&lt;br /&gt;&lt;br /&gt;That example shows it as simply a library. It probably can't be done as a library, so it seems like it would have to be a language feature. Something like this.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;varname case class Server&lt;br /&gt;val Altair = new Server&lt;br /&gt;println(Altair)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which yields simply: Altair&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Does anything like this exist? Would it be terribly difficult to build into a compiler? Things would probably be tricky if you said something like...&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;varname case class Server&lt;br /&gt;val Altair = new Server&lt;br /&gt;val Moxy = Altair&lt;br /&gt;println(Moxy)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Would you want to get Altair, or Moxy?&lt;br /&gt;&lt;br /&gt;Can anyone give any opinions on this at all?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6812599274010372015?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6812599274010372015/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/09/language-feature-request.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6812599274010372015'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6812599274010372015'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/09/language-feature-request.html' title='Language Feature Request'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7995364222112114225</id><published>2008-07-06T15:47:00.000-07:00</published><updated>2008-07-06T18:39:46.240-07:00</updated><title type='text'>Using Scala Actors</title><content type='html'>I'm assuming (maybe incorrectly) that most of the Actors that will be written will simply want to react to messages, forever. Something like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val reactor = new Actor(){ &lt;br /&gt;  def act() { &lt;br /&gt;    loop{ &lt;br /&gt;      react{&lt;br /&gt;        case msg =&gt; ...&lt;br /&gt;      } &lt;br /&gt;    } &lt;br /&gt;  } &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Given that assumption, it seems like it would be nice just to define whats in the react portion of the code. The rest is redundant. This is pretty simple. First, I created a simple little factory called Actors. &lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object Actors{&lt;br /&gt;  def newReactor( f: PartialFunction[Any,Unit] ): Actor = { &lt;br /&gt;    new Actor(){ def act() { loop{ react(f) } } }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;and then I simply used it:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val reactor = Actors.newReactor {&lt;br /&gt;  case msg =&gt; println( "Got something: " + msg )&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This consolidated the code outside the actual reaction from 4 lines (and 4 right brackets) to a single line (and a single right bracket). &lt;br /&gt;&lt;br /&gt;You can also do some other interesting which allow you to keep your reaction code separate from the actual actors (you can do this using the original approach as well). You can define partial functions, and pass them into the newReactor method like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def normalReaction : PartialFunction[Any,Unit] = {&lt;br /&gt;  case x: int =&gt; println( "Got int: " + x )&lt;br /&gt;  case msg =&gt; println( "Got something else: " + msg )&lt;br /&gt;}&lt;br /&gt;  &lt;br /&gt;def abnormalReaction : PartialFunction[Any,Unit] = {&lt;br /&gt;  case msg =&gt; println("eruhewiurhqweihu!!!!")&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;val normalReactor = Actors.newReactor { normalReaction } &lt;br /&gt;val abnormalReactor = Actors.newReactor { abnormalReaction } &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I know this is all rather simple and trivial, but I'm crazy about reducing redundancy and improving readability.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7995364222112114225?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7995364222112114225/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/07/using-scala-actors.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7995364222112114225'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7995364222112114225'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/07/using-scala-actors.html' title='Using Scala Actors'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-3666938135056300236</id><published>2008-06-15T21:45:00.000-07:00</published><updated>2008-06-16T19:46:28.515-07:00</updated><title type='text'>Scala and Enums</title><content type='html'>Scala doesn't have language level support for enumerations, but I think its fairly easy to argue that its a good thing. First, something isn't quite right about Java enums. Sometime soon I'll post more about that. Scala is such a nice language that you can do things cleanly without needing built in support for extra things like enum. Extra features in a language clutter it up. &lt;br /&gt;&lt;br /&gt;As an example, I lovingly ripped off the Planets example from the Java tutorial itself, and implemented it in Scala. Here is the Scala code.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;case object MERCURY extends Planet(3.303e+23, 2.4397e6)&lt;br /&gt;case object VENUS extends Planet(4.869e+24, 6.0518e6)&lt;br /&gt;case object EARTH extends Planet(5.976e+24, 6.37814e6)&lt;br /&gt;case object MARS extends Planet(6.421e+23, 3.3972e6)&lt;br /&gt;case object JUPITER extends Planet(1.9e+27,   7.1492e7)&lt;br /&gt;case object SATURN extends Planet(5.688e+26, 6.0268e7)&lt;br /&gt;case object URANUS extends Planet(8.686e+25, 2.5559e7)&lt;br /&gt;case object NEPTUNE extends Planet(1.024e+26, 2.4746e7)&lt;br /&gt;case object PLUTO extends Planet(1.27e+22,  1.137e6)&lt;br /&gt;&lt;br /&gt;// mass in kilograms, radius in meters&lt;br /&gt;sealed case class Planet( mass: double, radius: double ){&lt;br /&gt;    // universal gravitational constant  (m3 kg-1 s-2)&lt;br /&gt;    val G = 6.67300E-11      &lt;br /&gt;    def surfaceGravity = G * mass / (radius * radius)&lt;br /&gt;    def surfaceWeight(otherMass: double) = otherMass * surfaceGravity&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And here is the original Java code.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public enum Planet {&lt;br /&gt;    MERCURY (3.303e+23, 2.4397e6),&lt;br /&gt;    VENUS   (4.869e+24, 6.0518e6),&lt;br /&gt;    EARTH   (5.976e+24, 6.37814e6),&lt;br /&gt;    MARS    (6.421e+23, 3.3972e6),&lt;br /&gt;    JUPITER (1.9e+27,   7.1492e7),&lt;br /&gt;    SATURN  (5.688e+26, 6.0268e7),&lt;br /&gt;    URANUS  (8.686e+25, 2.5559e7),&lt;br /&gt;    NEPTUNE (1.024e+26, 2.4746e7),&lt;br /&gt;    PLUTO   (1.27e+22,  1.137e6);&lt;br /&gt;&lt;br /&gt;    private final double mass;   // in kilograms&lt;br /&gt;    private final double radius; // in meters&lt;br /&gt;    Planet(double mass, double radius) {&lt;br /&gt;        this.mass = mass;&lt;br /&gt;        this.radius = radius;&lt;br /&gt;    }&lt;br /&gt;    public double mass()   { return mass; }&lt;br /&gt;    public double radius() { return radius; }&lt;br /&gt;&lt;br /&gt;    // universal gravitational constant  (m3 kg-1 s-2)&lt;br /&gt;    public static final double G = 6.67300E-11;&lt;br /&gt;&lt;br /&gt;    public double surfaceGravity() {&lt;br /&gt;        return G * mass / (radius * radius);&lt;br /&gt;    }&lt;br /&gt;    public double surfaceWeight(double otherMass) {&lt;br /&gt;        return otherMass * surfaceGravity();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The Scala code is nicer, though its unfortunate that you have to say "extends Planet" for each Planet. Each planet is defined as a Scala "object" which is really nothing more than a singleton, which is what enum values are in Java. &lt;br /&gt;&lt;br /&gt;I could and should go into more detail on all of this, but I'm mostly posting it for my own reference.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-3666938135056300236?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/3666938135056300236/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/06/scala-and-enums.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3666938135056300236'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3666938135056300236'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/06/scala-and-enums.html' title='Scala and Enums'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-8566249493634399295</id><published>2008-05-17T08:50:00.000-07:00</published><updated>2008-05-17T20:27:56.702-07:00</updated><title type='text'>When To Call a Constructor Part 1</title><content type='html'>I've it said before (and people a lot smarter than me like Gilad Bracha), and I'll say it again: Constructors are Evil. Unfortunately, in most common situations, they are impossible to avoid. Rather than beating a dead horse, I'm going to take a slightly different approach. In this post  I'll focus on &lt;span style="font-style: italic;"&gt;when&lt;/span&gt; it &lt;span style="font-style: italic; font-weight: bold;"&gt;is&lt;/span&gt; ok to call a constructor, and &lt;span style="font-style: italic;"&gt;how&lt;/span&gt; to do so effectively. This information can be applied to any number of OO languages.&lt;br /&gt;&lt;br /&gt;(Note: It is of course sometimes possible to get away from calling constructors by using a DIF like Guice. Sometimes its just not possible. For example, you have a legacy code base that you are maintaining/extending. It may be possible to switch it over to a DIF, but its unlikely to happen all at once and you probably don't want to end up with a code base that is somewhere halfway between. That can make code even more difficult to reason about. Regardless, even if you are using a DIF you still want to call new sometimes, which I'll explain later.)&lt;br /&gt;&lt;br /&gt;I'll start with a simple example.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class PersonCache {&lt;br /&gt;&lt;br /&gt;  private final Map&amp;lt;Name, Person&amp;gt; storage;&lt;br /&gt;  &lt;br /&gt;  public PersonCache(){&lt;br /&gt;    storage = new HashMap&amp;lt;Name, Person&amp;gt;();&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void addPerson(Person p){&lt;br /&gt;    storage.put(p.getName(), p);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public Person getPerson(Name name) {&lt;br /&gt;    return storage.get(name);&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void removePerson(Person p){&lt;br /&gt;    storage.remove(p.getName());&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This class looks reasonable, and in fact it is. But as you'll see later, simple classes like this lull developers into a false sense of security with the "new" statement. Here, calling new on HashMap is ok because:&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;It is a trusted/tested class&lt;/li&gt;&lt;li&gt;It has no significant dependencies&lt;/li&gt;&lt;ol&gt;&lt;li&gt;It doesn't reference any static state&lt;/li&gt;&lt;li&gt;It doesn't do any IO&lt;/li&gt;&lt;/ol&gt;&lt;/ol&gt;&lt;br /&gt;Theres a bit of a theme here. If you are going to call a constructor, you need to have a solid understanding of the class you're instantiating. Because it's so well documented, we know HashMap is safe to instantiate. Unfortunately, most code isn't so well documented. Most developers don't understand each class they instantiate.&lt;br /&gt;&lt;br /&gt;So why isn't it ok to instantiate an unknown, untrusted class, or a class with dependencies?&lt;br /&gt;&lt;br /&gt;To answer that lets first briefly look at the design forces. There are at least four (and probably more) design forces at play here.&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Encapsulation&lt;/li&gt;&lt;li&gt;Readability&lt;/li&gt;&lt;li&gt;Static Dependencies&lt;/li&gt;&lt;li&gt;Testability&lt;/li&gt;&lt;/ul&gt;The forces certainly push and pull on each other a bit. As encapsulation goes up so do readability and static dependencies, while and testability goes down. While we can't always have the best of each, it's important to understand when to choose one over the other.&lt;br /&gt;&lt;br /&gt;Consider the following example.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class PersonCacheWithDatabase {&lt;br /&gt;&lt;br /&gt;  private final Database storage;&lt;br /&gt;  &lt;br /&gt;  public PersonCacheWithDatabase(){&lt;br /&gt;    storage = new Database();&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void addPerson(Person p){&lt;br /&gt;    storage.put(p.getName(), p);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public Person getPerson(Name name) {&lt;br /&gt;    return storage.get(name);&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void removePerson(Person p){&lt;br /&gt;    storage.remove(p.getName());&lt;br /&gt;  }  &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This certainly doesn't look a whole lot different than the first example. But, its infinitely worse. Doubly do because it cleverly tricks you into thinking that its ok by looking so similar.&lt;br /&gt;&lt;br /&gt;First, DatabasePersonCache may appear to be encapsulated, but in reality its not. It forces you to know about the database whether you like it or not. If you're going to call this constructor, you had better have a database set up somewhere. Otherwise, try to use it and you're going to get exceptions left and right. For the exact same reason, its difficult to read and test this code. Reading it alone is simply not enough. You need to understand the database class as well. Additionally, this class is forever statically bound to the Database class. If you somehow want to store your people in a more convenient way, well, you just can't. If you want to test a class that uses PersonCache, good luck.&lt;br /&gt;&lt;br /&gt;There is a way around this - pass in a StorageStrategy into PersonCache.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public interface StorageStrategy {&lt;br /&gt;&lt;br /&gt;  public void put(Name name, Person p);&lt;br /&gt; &lt;br /&gt;  public Person get(Name name);&lt;br /&gt; &lt;br /&gt;  public void remove(Name name);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class PersonCacheWithStorageStrategy {&lt;br /&gt;&lt;br /&gt;  private final StorageStrategy storage;&lt;br /&gt;  &lt;br /&gt;  public PersonCacheWithStorageStrategy(StorageStrategy storage){&lt;br /&gt;    this.storage = storage;&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void addPerson(Person p){&lt;br /&gt;    storage.put(p.getName(), p);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public Person getPerson(Name name) {&lt;br /&gt;    return storage.get(name);&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  public void removePerson(Person p){&lt;br /&gt;    storage.remove(p.getName());&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;PersonCacheWithStorageStrategy is much better than the PersonCacheWithDatabase. As long as StorageStrategy is an interface, PersonCache is now nice and reusable, it can be used with a HashMap, a Database, anything. It isn't statically bound to any implementation. It's definitely more readable as you are safe assume that the StorageStrategy passed in works fine. It's far more testable on the whole - you don't have to set up a database to test it.&lt;br /&gt;&lt;br /&gt;However, even though its better than the second example, it does suffer problems that the original PersonCacheWithHashMap does not suffer - poor encapsulation. You have to know something about StorageStrategy in order to use it. What if you only ever want to use this as a quick in-memory helper object? The first example would be far better. What if you only ever needed the in-memory storage capability while using PersonCache? A client is still forced to create a StorageStrategy. Ick.&lt;br /&gt;&lt;br /&gt;This is the point where it would be really nice to have a forth example and say &lt;span style="font-style: italic;"&gt;this&lt;/span&gt; is how to do it. Unfortunately there isn't one magic scenario that solves every problem. Developers need to understand the design forces and the code objects they are clients of in order to make reasonable decisions about their code. If its not entirely safe to call new, based on the rules above, then you must pass your dependencies in. You trade some encapsulation for another design force: sanity.&lt;br /&gt;&lt;br /&gt;Now, you may be thinking, well great, in the example 3 you just deflected the problem of calling new upward, but that doesn't help me much, since I still have to call new in the clients of PersonCache. You would be correct. I haven't addressed that issue just yet. But for that you'll have to stay tuned for part two of this mini series.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-8566249493634399295?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/8566249493634399295/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/05/when-to-call-constructor-part-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8566249493634399295'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/8566249493634399295'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/05/when-to-call-constructor-part-1.html' title='When To Call a Constructor Part 1'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6777613262425597819</id><published>2008-05-17T05:35:00.000-07:00</published><updated>2008-05-17T19:23:42.666-07:00</updated><title type='text'>My First Scala Presentation</title><content type='html'>I gave my first talk on Scala today, to my team at NYSE. It was an entirely informal, BYOL (Bring your own lunch) talk that I hadn't prepared for at all (I was hoping someone else would speak, but since no one else ever does, its always me, prepared or not). Anyway, there are some lessons learned from the talk.&lt;br /&gt;&lt;br /&gt;The talk didn't really go over that well, and mostly because I didn't hit them hard with a great example up front. Next time I will. I finally won them over when I showed a List example, which I'll show here.&lt;br /&gt;&lt;br /&gt;Say you want to create a List of integers containing the elements 1, 2, and 3. In Java there are a few ways to go about it, none of them very easy. I'll start with the most common example.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;List&amp;lt;Integer&amp;gt; ints = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;ints.add(1);&lt;br /&gt;ints.add(2);&lt;br /&gt;ints.add(3);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Like I said, there may be easier ways to do this, but I don't think many people will argue that this would be by far the most commonly used approach. There are several things wrong with it.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;It's about a billion characters long.&lt;/li&gt;&lt;li&gt;The redundant type information in the first line is so frustrating.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;The next three lines of code are almost identical.&lt;/li&gt;&lt;li&gt;The semi colons are pretty much pointless.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Here's how you do the same thing in Scala.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val ints = List(1,2,3)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Thats it.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Its 20 characters total (not including the unneeded spaces).  20 characters vs. A Billion! I pick 20.&lt;/li&gt;&lt;li&gt;There is no need whatsoever to put an absurd amount of type information. The compiler is perfectly capable of figuring that out thank you. As are humans; any second year college student could tell that thats a list of integers. Heck, any 7 year old could too.&lt;/li&gt;&lt;li&gt;There is absolutely no redundant code here.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;There are no semi colons.&lt;/li&gt;&lt;/ul&gt;This example has probably been posted on the internet about a million times by now, and its not the point of this post. The point is this: &lt;span style="font-style: italic;"&gt;If you want to give a talk on a language, hit the audience hard with a solid example &lt;span style="font-weight: bold;"&gt;immediately&lt;/span&gt;&lt;/span&gt;. Don't dilly-dally and give examples that are only slightly different than their current language and then give them the good stuff. You'll meet too much opposition up front. I thought I was doing them a favor by easing them into Scala but what really happened was quite the opposite. For some terrible reason Java developers are quite territorial. I was providing fuel for them to say, "I'll stick with Java."&lt;br /&gt;&lt;br /&gt;Next time, I give the good example up front, then transition to the easy stuff once I've peaked their interest, and then make sure to finish up with a solid example too. And of course next time I'll be quite a bit more prepared.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Ok. Thats the gist of what I was wanting to talk about, now some sideline commentary.&lt;br /&gt;&lt;br /&gt;One particularly odd complaint IMO was that most of this was just syntactic sugar. First off, I whole-heartedly disagree, but I can see why some people could incorrectly think that way. My colleague happily responded:&lt;br /&gt;&lt;br /&gt;&lt;blockquote style="font-style: italic;"&gt;If you think it's just syntactic sugar, then I have a perfect language for you. It only contains 2 characters, 1, and 0. Using anything else, well thats just syntactic sugar.&lt;br /&gt;&lt;/blockquote&gt;Of course anyone can think that higher level languages are just prettier syntax, but they would be entirely missing the point. The point is to not have our primitive human minds bombarded with useless information so that we can better and more easily understand the meaning of each line of code. Thats not sugar, thats evolution, baby.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6777613262425597819?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6777613262425597819/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/05/my-first-scala-presentation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6777613262425597819'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6777613262425597819'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/05/my-first-scala-presentation.html' title='My First Scala Presentation'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1189050557234305732</id><published>2008-04-04T09:36:00.000-07:00</published><updated>2008-04-06T21:08:24.874-07:00</updated><title type='text'>ScalaTest and TestNG</title><content type='html'>THIS IS AN INCOMPLETE DRAFT, POSTED FOR REVIEW. I UNDERSTAND SOME SECTIONS NEED WORK AND SOME SECTIONS ARE EMPTY OR MISSING ENTIRELY, AND THAT THE FORMAT MIGHT BE MESSED UP.&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;ScalaTest has two important goals.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Allow tests to be written in Scala easily, and concisely.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Allow Java developers to transition to ScalaTest with minimal effort.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;With these two goals in mind I'm happy to announce ScalaTest's integration with TestNG. This integration offers two features that meet the goals of ScalaTest.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;TestNG tests can be written in Scala, and run in both ScalaTest and TestNG runners.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Existing TestNG tests can be run in ScalaTest.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;By being able to write new TestNG tests in Scala, a developer doesn't have the overhead of learning a new test framework &lt;span style="font-style: italic;"&gt;and &lt;/span&gt;a new language at once. And more importantly, by being able to run existing test suites in ScalaTest  developers can feel confident that all their code is working without the overhead of running two test frameworks at once.&lt;br /&gt;&lt;br /&gt;This article will show you how to use ScalaTest to do both, with the help of an example (available for &lt;a href="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/ScalaTest-TestNG-Example.zip?rev=208"&gt;download&lt;/a&gt; from the ScalaTest Subversion repository). The example has been tested against &lt;a href="http://www.scala-lang.org/downloads/"&gt;Scala 2.7.0&lt;/a&gt;, and &lt;a href="http://testng.org/testng-5.7.zip"&gt;TestNG 5.7&lt;/a&gt;. To use the example you'll also need to download the latest version of &lt;a href="https://scalatest.dev.java.net/source/browse/scalatest/trunk/"&gt;ScalaTest&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;After downloading everything, you'll need to place the jars into the lib directories of the example. Place the TestNG jar into the java/lib, and place the Scala related jars into the scala/lib folder. You should end up with the following directory structure (as shown here in Eclipse).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;img src="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/images/example-contents.bmp?rev=208" /&gt;&lt;/div&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;About the Example&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;The example contains what we'll refer to as "existing" code (Java), and "new" code (Scala).  The thinking here is that you are working on an existing project in Java, you have a Java code base complete with unit tests (you do have unit tests, don't you?), and that you're interested in exploring Scala. If you're Java code isn't covered with tests the content here is still relevant; you can learn how to write TestNG tests in Scala.&lt;br /&gt;&lt;br /&gt;The existing code lives in the java folder where you'll find:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;VolumeKnob.java - An interface for volume knobs&lt;/li&gt;&lt;li&gt;BoringVolumeKnob.java - A boring implementation of VolumeKnob&lt;/li&gt;&lt;li&gt;BoringVolumeKnobTest.java - A boring test for BoringVolumeKnob&lt;/li&gt;&lt;li&gt;volume-tests.xml - A TestNG XML suite to run BoringVolumeKnobTest&lt;/li&gt;&lt;li&gt;build.xml - Ant file that builds the code and runs the tests&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;The new code is in the scala folder, and it builds upon the existing Java code. In the scala folder you'll find:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;AwesomeVolumeKnob.java - A totally awesome implementation of VolumeKnob&lt;/li&gt;&lt;li&gt;AwesomeVolumeKnobTest.java - An awesome test for AwesomeVolumeKnob&lt;/li&gt;&lt;li&gt;build.xml - Ant file that builds the code and has targets to&lt;br /&gt;&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Run just the existing Java tests in ScalaTest&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Run just the Scala tests in ScalaTest&lt;/li&gt;&lt;li&gt;Run both the Java and Scala tests in ScalaTest&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Quick Look At What Needs To Be Tested&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;In the next section we're going to learn how to write TestNG tests in ScalaTest. But before we do, lets take a quick look at what we're going to test. Recall in the java folder the interface &lt;span style="font-family:courier new;"&gt;VolumeKnob&lt;/span&gt;. It's very simple:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public interface VolumeKnob {&lt;br /&gt;    public abstract int currentVolume();&lt;br /&gt;    public abstract int maxVolume();&lt;br /&gt;    public abstract void turnUp();&lt;br /&gt;    public abstract void turnDown();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;VolumeKnob &lt;/span&gt;has two implementations that need testing. The first is a rather boring Java implementation - &lt;span style="font-family:courier new;"&gt;BoringVolumeKnob&lt;/span&gt;. It's too boring to show here, and it can't be turned up beyond 10. It has a corresponding TestNG test class also written in Java - BoringVolumeKnobTest. That won't be shown here either, since we'll assume you know TestNG.&lt;br /&gt;&lt;br /&gt;There is also a Scala implementation of that interface, &lt;span style="font-family:courier new;"&gt;AwesomeVolumeKnob&lt;/span&gt;. &lt;span style="font-family:courier new;"&gt;AwesomeVolumeKnob&lt;/span&gt;'s have three amazing qualities:&lt;br /&gt;&lt;ul&gt;&lt;li&gt; They &lt;span style="font-weight: bold;"&gt;&lt;span style="font-style: italic;"&gt;always&lt;/span&gt;&lt;/span&gt; go to at least 11 (of course)&lt;/li&gt;&lt;li&gt;They can &lt;span style="font-weight: bold;"&gt;&lt;span style="font-style: italic;"&gt;never&lt;/span&gt;&lt;/span&gt; be turned down&lt;/li&gt;&lt;li&gt;They can &lt;span style="font-weight: bold;"&gt;&lt;span style="font-style: italic;"&gt;always&lt;/span&gt;&lt;/span&gt; be turned up, &lt;span&gt;regardless&lt;/span&gt;&lt;span style="font-weight: bold;"&gt; &lt;/span&gt;of the max volume.&lt;/li&gt;&lt;/ul&gt;&lt;span style="font-size:180%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.scalatest.legacy.VolumeKnob&lt;br /&gt;&lt;br /&gt;class AwesomeVolumeKnob( val maxVolume: int ) extends VolumeKnob {&lt;br /&gt;  if( maxVolume &lt; 11 ) &lt;br /&gt;    throw new IllegalArgumentException("...These go to eleven.");&lt;br /&gt;  &lt;br /&gt;  var currentVolume = maxVolume;&lt;br /&gt;  &lt;br /&gt;  def turnDown = &lt;br /&gt;    throw new IllegalAccessError("AwesomeVolumeKnobs cannot be turned down");&lt;br /&gt;  &lt;br /&gt;  // AwesomeVolumeKnobs don't care about max volume&lt;br /&gt;  def turnUp = currentVolume = currentVolume + 1;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;AwesomeVolumeKnob is accompanied by AwesomeVolumeKnobTest, which is a TestNG test written in Scala. We'll cover that next.&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Writing TestNG tests in ScalaTest&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Because Scala allows you to use Java's annotations, TestNG tests can be written in Scala at least as easily as they can in Java. Here is a quick example:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.scalatest.legacy.VolumeKnob&lt;br /&gt;&lt;br /&gt;class AwesomeVolumeKnobTest{&lt;br /&gt;  @Test&lt;br /&gt;  def awesomeVolumeKnobsCanBeTurnedUpReallyHigh(){&lt;br /&gt;    val v = new AwesomeVolumeKnob(10000)&lt;br /&gt;    for( i &lt;- 1 to 1000 ) v.turnUp&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;There's really nothing to it. This class can be compiled by the Scala compiler and run in any TestNG runner. &lt;br /&gt;&lt;br /&gt;To enable your test to be run in ScalaTest, simply extend the ScalaTest trait org.scalatest.testng.TestNGSuite. That's it. Here is the full implementation of AwesomeVolumeKnobTest in all its glory.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.scalatest.testng.TestNGSuite&lt;br /&gt;import org.testng.annotations._&lt;br /&gt;&lt;br /&gt;class AwesomeVolumeKnobTest extends TestNGSuite{&lt;br /&gt;&lt;br /&gt;  @Test{ val description=&lt;br /&gt;         "create AVK's with max volume &lt; 11 and ensure IllegalArg is thrown" &lt;br /&gt;         val dataProvider="low volumes", &lt;br /&gt;         val expectedExceptions = Array( classOf[IllegalArgumentException] )}&lt;br /&gt;  def awesomeVolumeKnobsAlwaysGoToAtLeastEleven(maxVolume: int){&lt;br /&gt;    new AwesomeVolumeKnob(maxVolume);  &lt;br /&gt;  }  &lt;br /&gt;  &lt;br /&gt;  @Test{ val description=&lt;br /&gt;         "try to turn down some AVK's and ensure IllegalAccess is thrown"&lt;br /&gt;         val dataProvider="high volumes", &lt;br /&gt;         val expectedExceptions = Array( classOf[IllegalAccessError] )}&lt;br /&gt;  def awesomeVolumeKnobsCanNeverBeTurnedDown(maxVolume: int){&lt;br /&gt;    new AwesomeVolumeKnob(maxVolume).turnDown();&lt;br /&gt;  } &lt;br /&gt;  &lt;br /&gt;  @Test{ val description="crank it up" }&lt;br /&gt;  def awesomeVolumeKnobsCanBeTurnedUpReallyHigh(){&lt;br /&gt;    val v = new AwesomeVolumeKnob(10000)&lt;br /&gt;    for( i &lt;- 1 to 1000 ) v.turnUp&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  @DataProvider{val name="high volumes"}&lt;br /&gt;  def goodVolumes = &lt;br /&gt;    Array(v(11), v(20),v(30),v(40),v(50),v(60),v(70),v(80),v(90),v(100))&lt;br /&gt;  &lt;br /&gt;  @DataProvider{val name="low volumes"}&lt;br /&gt;  def lowVolumes = &lt;br /&gt;    Array(v(1), v(2),v(3),v(4),v(5),v(6),v(7),v(8),v(9),v(10))&lt;br /&gt;  &lt;br /&gt;  def v( i: Integer ) = Array(i)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There are a few things to notice with this implementation.&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Running Scala TestNG Tests in ScalaTest&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Running TestNGSuite's in ScalaTest is no different than running any other ScalaTest Suite - simply use the Ant task. In scala/build.xml in the example, you'll find a target called "test-scala-only":&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; &amp;lt;target name="test-scala-only" depends="compile"&amp;gt;&lt;br /&gt;  &amp;lt;taskdef name="scalatest" classname="org.scalatest.tools.ScalaTestTask" &lt;br /&gt;   classpathref="test.classpath"/&amp;gt;&lt;br /&gt;  &lt;br /&gt;  &amp;lt;scalatest&amp;gt;&lt;br /&gt;   &amp;lt;runpath&amp;gt;&lt;br /&gt;    &amp;lt;pathelement path="test.classpath"/&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${test.jar.file}"/&amp;gt;&lt;br /&gt;   &amp;lt;/runpath&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;suite classname="org.scalatest.testng.AwesomeVolumeKnobTest"/&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;reporter type="stdout" /&amp;gt;&lt;br /&gt;   &amp;lt;reporter type="graphic" /&amp;gt;&lt;br /&gt;   &lt;br /&gt;  &amp;lt;/scalatest&amp;gt;&lt;br /&gt; &amp;lt;/target&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In this case we have just one Suite to run:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&amp;lt;suite classname="org.scalatest.testng.AwesomeVolumeKnobTest"/&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Running this task brings up the ScalaTest UI:&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;img src="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/images/example-scalatest-scala-only.bmp?rev=208" /&gt;&lt;/div&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Running the Java Tests&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;If you're a TestNG user, you're likely to be familiar with running test suites from the IDE. There are a couple of different ways to do it, and whichever you choose, you're sure to end up like something like this (as shown in Eclipse):&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;img src="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/images/example-testng-testrun.bmp?rev=208" /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;While this is great, and familiar, and comfortable, it would be a pain to have to run your Java tests through TestNG's UI and then have to switch over to ScalaTests UI to run your Scala tests.&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Running Java Tests in ScalaTest&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: left;"&gt;&lt;span style="font-size:100%;"&gt;ScalaTest provides a simple way to run TestNG xml suites in its Ant task. In scala/build.xml in the example, you'll find a target called "test-java-only":&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; &amp;lt;target name="test-java-only" depends="compile"&amp;gt;&lt;br /&gt;  &amp;lt;taskdef name="scalatest" classname="org.scalatest.tools.ScalaTestTask" &lt;br /&gt;   classpathref="test.classpath"/&amp;gt;&lt;br /&gt;  &lt;br /&gt;  &amp;lt;scalatest&amp;gt;&lt;br /&gt;   &amp;lt;runpath&amp;gt;&lt;br /&gt;    &amp;lt;pathelement path="test.classpath"/&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${test.jar.file}"/&amp;gt;&lt;br /&gt;   &amp;lt;/runpath&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;testNGSuites&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${java.dir}/src/test/volume-tests.xml"/&amp;gt;&lt;br /&gt;   &amp;lt;/testNGSuites&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;reporter type="stdout" /&amp;gt;&lt;br /&gt;   &amp;lt;reporter type="graphic" /&amp;gt;&lt;br /&gt;   &lt;br /&gt;  &amp;lt;/scalatest&amp;gt;&lt;br /&gt; &amp;lt;/target&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Inside the testNGSuites block, simply put the location of the xml suite.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  &amp;lt;testNGSuites&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${java.dir}/src/test/volume-tests.xml"/&amp;gt;&lt;br /&gt;  &amp;lt;/testNGSuites&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;While in this case there's one xml suite only, ScalaTest supports multiple xml suites. All suites get run in the same TestNG instance. Running ScalaTest via Ant with the graphic reporter option brings up the ScalaTest UI:&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;img src="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/images/example-testng-testrun-in-scalatest.bmp?rev=208" /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;As you can see, ScalaTest reported the exact same results as the TestNG Eclipse plugin. (But...notice that our green bar is much brighter!)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Running All The Tests Together&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Finally, for the moment of truth...though being so easy, it's likely a bit of a letdown. To run all the tests together, simply use both options in the Ant task, as in the "test" target in scala/build.xml.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; &amp;lt;target name="test-java-only" depends="compile"&amp;gt;&lt;br /&gt;  &amp;lt;taskdef name="scalatest" classname="org.scalatest.tools.ScalaTestTask" &lt;br /&gt;   classpathref="test.classpath"/&amp;gt;&lt;br /&gt;  &lt;br /&gt;  &amp;lt;scalatest&amp;gt;&lt;br /&gt;   &amp;lt;runpath&amp;gt;&lt;br /&gt;    &amp;lt;pathelement path="test.classpath"/&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${test.jar.file}"/&amp;gt;&lt;br /&gt;   &amp;lt;/runpath&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;suite classname="org.scalatest.testng.AwesomeVolumeKnobTest"/&amp;gt;&lt;br /&gt;&lt;br /&gt;   &amp;lt;testNGSuites&amp;gt;&lt;br /&gt;    &amp;lt;pathelement location="${java.dir}/src/test/volume-tests.xml"/&amp;gt;&lt;br /&gt;   &amp;lt;/testNGSuites&amp;gt;&lt;br /&gt;   &lt;br /&gt;   &amp;lt;reporter type="stdout" /&amp;gt;&lt;br /&gt;   &amp;lt;reporter type="graphic" /&amp;gt;&lt;br /&gt;   &lt;br /&gt;  &amp;lt;/scalatest&amp;gt;&lt;br /&gt; &amp;lt;/target&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Running this task brings up the ScalaTest UI:&lt;br /&gt;&lt;br /&gt;&lt;div style="text-align: center;"&gt;&lt;img src="https://scalatest.dev.java.net/source/browse/*checkout*/scalatest/branches/josh-7/examples/testng/images/example-all-tests.bmp?rev=208" /&gt;&lt;/div&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Problems&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="font-size:180%;"&gt;Summary&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1189050557234305732?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1189050557234305732/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/04/scalatest-and-testng.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1189050557234305732'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1189050557234305732'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/04/scalatest-and-testng.html' title='ScalaTest and TestNG'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7387823645498091320</id><published>2008-02-14T09:53:00.000-08:00</published><updated>2008-02-14T10:04:11.423-08:00</updated><title type='text'>ScalaTest and Mocking</title><content type='html'>I've added in some mocking into ScalaTest thanks to &lt;a href="http://code.google.com/p/specs/"&gt;specs&lt;/a&gt; integration. I've done it in a BDD style, kind of like rspec's given/when/then. &lt;a href="http://rspec.info/"&gt;rspec&lt;/a&gt; is much further along and I still need to learn a lot more about it, but thats okay. I'm hoping just to get some peoples opinions on readability and such.  Here are a couple very quick examples. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt; mockTest( "Report should be generated for each invocation" ){&lt;br /&gt;       &lt;br /&gt;   val reporter = mock(classOf[Reporter])&lt;br /&gt;&lt;br /&gt;   expecting( "reporter gets 10 passing reports because invocationCount=10" ) {&lt;br /&gt;     nTestsToPass( 10, reporter )&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   when ( "run the suite with method that has invocationCount=10" ){&lt;br /&gt;     new TestNGSuiteWithInvocationCount().runTestNG(reporter)&lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;     &lt;br /&gt; mockTest( "Reporter should be notified when test is skipped" ){&lt;br /&gt;       &lt;br /&gt;   val reporter = mock(classOf[Reporter])&lt;br /&gt;&lt;br /&gt;   expecting ( "a single test should fail, followed by a single test being skipped" ){ &lt;br /&gt;     one(reporter).runStarting(0) &lt;br /&gt;     one(reporter).testStarting(any(classOf[Report])) &lt;br /&gt;     one(reporter).testFailed(any(classOf[Report])) &lt;br /&gt;     one(reporter).testIgnored(any(classOf[Report]))&lt;br /&gt;     one(reporter).runCompleted()&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   when ( "run the suite with a test that should fail and a test that should be skipped" ){&lt;br /&gt;     new SuiteWithSkippedTest().runTestNG(reporter)&lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As you can see, I've added expecting and when blocks, which optionally take a String (that is currently just used for readability). The simple idea here is that I have grouped chunks of my test into places that make sense, hopefully making it easier for someone reading the test. Do you like it? Do you hate it? Any other opinions that could help?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7387823645498091320?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7387823645498091320/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/02/scalatest-and-mocking.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7387823645498091320'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7387823645498091320'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/02/scalatest-and-mocking.html' title='ScalaTest and Mocking'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4842040535096743851</id><published>2008-01-31T19:02:00.000-08:00</published><updated>2008-02-01T06:05:58.118-08:00</updated><title type='text'>Which Style Is More Readable?</title><content type='html'>I've been writing ScalaTest tests for the ScalaTest TestNG integration (say that five times fast). I used a couple of different styles and I was hoping to get some input on which style people thought was more readable, more clear. Both styles are functional, one merely masks it a bit while the other  flaunts it. &lt;br /&gt;&lt;br /&gt;The first style I'll show is the discrete style. Here I call a test method which takes a function and executes it. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;     test( "Reporter Should Be Notified When Test Passes" ){&lt;br /&gt;    &lt;br /&gt;       val testReporter = new TestReporter&lt;br /&gt;&lt;br /&gt;       // when&lt;br /&gt;       new SuccessTestNGSuite().runTestNG(testReporter)&lt;br /&gt;&lt;br /&gt;       // then&lt;br /&gt;       assert( testReporter.successCount === 1 )&lt;br /&gt;     }&lt;br /&gt;  &lt;br /&gt;&lt;br /&gt;     test( "Reporter Should Be Notified When Test Fails" ){&lt;br /&gt;    &lt;br /&gt;       val testReporter = new TestReporter&lt;br /&gt;&lt;br /&gt;       // when&lt;br /&gt;       new FailureTestNGSuite().runTestNG(testReporter)&lt;br /&gt;&lt;br /&gt;       // then&lt;br /&gt;       assert( testReporter.failureCount === 1 )&lt;br /&gt;     }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The I'm showing only two examples of calling the test function but in actuality I have many more tests. Notice that in each test the first line is always the same:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;       val testReporter = new TestReporter&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There are benefits to this. All the code is right there and you can read the test method without looking anywhere else. There are also some negatives as well. I have the same line of code in several places. &lt;br /&gt;&lt;br /&gt;Now I'll show the even more functional style. It takes a little more explaining. Here I declare a withFixture method that accepts a function that takes a TestReporter as its input. The withFixture method creates the TestReporter (so each test call doesn't have to) and calls the input function passing it the TestReporter. To create tests I call the testWithFixture function which takes a function and passes it to the withFixture function I just wrote.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;     override def withFixture(f: (TestReporter) =&gt; Unit): Unit = {&lt;br /&gt;       f(new TestReporter) &lt;br /&gt;     }&lt;br /&gt;     &lt;br /&gt;     &lt;br /&gt;     testWithFixture( "Reporter Should Be Notified When Test Passes" ){ &lt;br /&gt;       t: TestReporter =&gt;&lt;br /&gt;&lt;br /&gt;       // when&lt;br /&gt;       new SuccessTestNGSuite().runTestNG(t)&lt;br /&gt;       // then&lt;br /&gt;       assertThat( t.successCount, is(1) )&lt;br /&gt;     }&lt;br /&gt;  &lt;br /&gt;&lt;br /&gt;     testWithFixture( "Reporter Should Be Notified When Test Fails" ){ &lt;br /&gt;       t: TestReporter =&gt;&lt;br /&gt;&lt;br /&gt;       // when&lt;br /&gt;       new FailureTestNGSuite().runTestNG(t)&lt;br /&gt;       // then&lt;br /&gt;       assert( t.failureCount === 1 )&lt;br /&gt;     }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I'm realizing as I'm writing this that all the extra explaining I had to do is because the code is more complicated. There are definite negatives here. Code is being passed around to other code, you might now be sure how things are actually running, you might not be sure where the TestReporter object is coming from. On the upside the methods are slightly shorter and I've removed the most obvious duplication by moving it to the withFixture function. There's still plenty of duplication (in each example) that could be removed but you can definitely push duplication removal too far. Especially in tests, you must balance duplication and indirection. They are in direct opposition. &lt;br /&gt;&lt;br /&gt;Does this code push it too far?&lt;br /&gt;&lt;br /&gt;Is this just a setup method in disguise? I'm of the opinion that setup methods are bad, but at least here everything is immutable.&lt;br /&gt;&lt;br /&gt;If people were to get used to this style would it become more readable in the long run?&lt;br /&gt;&lt;br /&gt;Please please let me know your thoughts.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4842040535096743851?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4842040535096743851/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/which-style-is-more-readable.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4842040535096743851'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4842040535096743851'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/which-style-is-more-readable.html' title='Which Style Is More Readable?'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-1862654426398419346</id><published>2008-01-23T19:36:00.000-08:00</published><updated>2008-01-24T20:35:19.317-08:00</updated><title type='text'>Scala and TestNG in Far Greater Detail</title><content type='html'>I wrote before on running TestNG in Scala and due to popular demand I'm going to go into much greater detail. My goal is to show that running TestNG in Scala is as easy as it is in Java. I've thrown in Hamcrest to show that that integrates seamlessly as well. Hopefully along the way you'll learn a couple of Scala nuggets too. And, be warned I'm assuming you know a bit about TestNG so I'm not going to explain it much. If you don't...&lt;a href="http://www.testng.org/"&gt;www.testng.org&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I created a new Scala class for testing my &lt;a href="http://cpusimulator.googlecode.com/svn/trunk/src/main/scala/com/joshcough/cpu/gates/AndGate.scala"&gt;AndGate&lt;/a&gt; class. The idea is that I want to make sure that my AndGate is on or off according to the standard And boolean logic table:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;x y | output&lt;br /&gt;------------&lt;br /&gt;0 0 |   0&lt;br /&gt;0 1 |   0&lt;br /&gt;1 0 |   0&lt;br /&gt;1 1 |   1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The testing class is called ScalaTestNGExampleTest, and it looks like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import org.testng.annotations._&lt;br /&gt;import org.hamcrest.MatcherAssert._&lt;br /&gt;import org.hamcrest.Matchers._;&lt;br /&gt;import org.testng.annotations.DataProvider;&lt;br /&gt;import com.joshcough.cpu.gates._&lt;br /&gt;&lt;br /&gt;class ScalaTestNGExample {&lt;br /&gt;  &lt;br /&gt;  @DataProvider{val name="generators"}&lt;br /&gt;  def createGenerators = { &lt;br /&gt;    val gens = Array(off, on)&lt;br /&gt;    for( x &lt;- gens; y &lt;- gens ) yield Array(x,y)&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  private def on = new Generator(true)&lt;br /&gt;  private def off = new Generator(false)&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;  @Test{ val dataProvider="generators" }&lt;br /&gt;  def testAndGateStates(genA: Generator, genB: Generator){&lt;br /&gt;    val and: AndGate = new AndGate(genA, genB);&lt;br /&gt;    val whatItShouldBe = genA.on &amp;&amp; genB.on&lt;br /&gt;    assertThat( and.on, is(whatItShouldBe) );&lt;br /&gt;    println( and.on + "==" + genA.on + "&amp;&amp;" + genB.on )&lt;br /&gt;  }  &lt;br /&gt;  &lt;br /&gt;  @BeforeMethod def printLineBefore = println("------entering test------")&lt;br /&gt;  @AfterMethod  def printLineAfter  = println("------exiting  test------")&lt;br /&gt;  &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If you aren't familiar with Scala that might look a bit like magic, so I'll explain one step at a time.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Data Provider&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The first thing I did was set up a data provider for my logic table:&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;The annotation declaration is obviously different than in Java. Instead of parentheses, you have to use curly brackets. Instead of simply name/value pairs, you have to declare vars. I could explain why, but instead you could just go to &lt;a href="http://www.scala-lang.org/intro/annotations.html"&gt;http://www.scala-lang.org/intro/annotations.html.&lt;br /&gt;&lt;/a&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;DataProvider methods are supposed to return Object[][], but...what the heck is this one returning? Well, before I explain what that funky for statement is actually doing I'll just announce that this method is actually returning Array[Array[Generator]].  I could have made it more explicit by saying def createGenerators(): Array[Array[Generator]] but Scala's type inference lets me get away with leaving it off. Does leaving it off hamper readability?  In most leaving it off is just eliminating some redundancy. Maybe in this case I should have left it on, but I wanted to show type inference a little bit.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Wait a second...Array[Array[Generator]] isn't Object[][]...or is it? Actually, yes. Scala's typed array class (Array[T]) actually compiles down to Java arrays. In this case, Array[Array[Generator]] compiles down to Generator[][] in Java.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;What is Array(on, off)? The type of Array(on, off) is Array[Generator] and it contains two elements,  Generator(true) and Generator(false) which are returned from the on and off methods respectively. It may be confusing for a Java programmer to see simply "on" with no parens. In most cases (for reasons far beyond the scope of this post) Scala doesn't force you to use parens on method calls with no arguments.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Ok finally, what is that funky for loop looking thing doing? Rather than explain, why don't I just give the equivalent code in Java for the createGenerators method?&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public Generator[][] createGenerators() {&lt;br /&gt;&lt;br /&gt;Generator[] onAndOff = new Generator[]{ on(), off() };&lt;br /&gt;&lt;br /&gt;Generator[][] gensToReturn = new Generator[4][2];&lt;br /&gt;for( int i = 0; i&amp;lt;onAndOff.length; i++ ){&lt;br /&gt;for( int j = 0; i&amp;lt;onAndOff.length; j++ ){&lt;br /&gt; gensToReturn[i+j] = new Generator[]{ onAndOff[i], onAndOff[j] };&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;return gensToReturn;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Honestly? Those three lines of code are doing all of that...? Yes. Honestly.  Rather than me trying to explain it though, James Iry does an excellent job in part 2 of his four part series on monads called &lt;a href="http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-2.html"&gt;Monads are Elephants&lt;/a&gt;. That is the link to part two, but I recommend reading all four.&lt;br /&gt;&lt;br /&gt;So now we have a data provider and we have a reasonable idea how it works. But quickly before I move on, heres another way I could have done it which is arguably more readable but not nearly as much fun. Once again, the idea here is that this data provider is essentially creating the And logic table for us.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;def createGenerators = {&lt;br /&gt;Array(Array(on, on),Array(on, off),Array(off, on),Array(off, off))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Test Method&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;At this point I think everything else is really straight forward. Despite that, I'll go over the test method in detail.&lt;br /&gt;&lt;ol&gt;&lt;li&gt;The @Test annotation is defined in the same fashion as I described above for @DataProvider. In this case I define which data provider to use. Done.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The method takes two Generator parameters which come from createGenerators method.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The first line simply instantiates an AndGate object using the two Generator parameters.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The second and third lines simply assert that the AndGate is what it should be! It should be on only when both generators are on, according to the logic table. The third line uses Hamcrest matchers for asserting. I'm not going to bother explaining them here.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Finally I throw in a print statement.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;BeforeMethod And AfterMethod Annotations&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Before each test method is called, TestNG will call any methods annotated with @BeforeMethod. In my case before each method I just print a nice message. The same goes for @AfterMethod, but after each test method, of course.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Results&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Here is my output from the console:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; [testng] -----------entering test-----------&lt;br /&gt; [testng] true==true&amp;amp;&amp;amp;true&lt;br /&gt; [testng] -----------exiting  test-----------&lt;br /&gt; [testng] -----------entering test-----------&lt;br /&gt; [testng] false==true&amp;amp;&amp;amp;false&lt;br /&gt; [testng] -----------exiting  test-----------&lt;br /&gt; [testng] -----------entering test-----------&lt;br /&gt; [testng] false==false&amp;amp;&amp;amp;true&lt;br /&gt; [testng] -----------exiting  test-----------&lt;br /&gt; [testng] -----------entering test-----------&lt;br /&gt; [testng] false==false&amp;amp;&amp;amp;false&lt;br /&gt; [testng] -----------exiting  test-----------&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Problems&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I did run into a few problems.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;FIXED: &lt;del&gt;Unfortunately, I couldn't use @Test{expectedExceptions = {SomeException.class}} because Scala doesn't you say Anything.class.&lt;/del&gt;&lt;/li&gt;&lt;li&gt;Running the tests through Eclipse is not as easy as it is in Java, and needs some work. I ended up mostly running through Ant, but sometimes through Eclipse.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I hope I've convinced you that running TestNG in Scala is simple. I didn't test all the features, but most of what I have tested works great. I plan to use it for most of my Scala development. I personally think its pretty far ahead of the pack, but if you want to see for yourself they are: &lt;a href="ScalaTest"&gt;ScalaTest&lt;/a&gt;, &lt;a href="http://www.scunit.org/"&gt;ScUnit&lt;/a&gt;, &lt;a href="http://rehersal.sourceforge.net/"&gt;Rehersal&lt;/a&gt;, &lt;a href="http://www.junit.org/"&gt;JUnit&lt;/a&gt;, and &lt;a href="http://code.google.com/p/specs"&gt;specs&lt;/a&gt;. I've tried the last four, and of those I thought specs was really nice. It seems like a reasonable alternative.&lt;br /&gt;&lt;br /&gt;I am very open to hear ideas on why I should switch to an xUnit test framework built in Scala. Are there any advantages? What are they?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-1862654426398419346?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/1862654426398419346/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/scala-and-testng-in-far-greater-detail.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1862654426398419346'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/1862654426398419346'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/scala-and-testng-in-far-greater-detail.html' title='Scala and TestNG in Far Greater Detail'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7458571340683428979</id><published>2008-01-20T20:39:00.000-08:00</published><updated>2008-01-20T20:43:14.575-08:00</updated><title type='text'>My Small Problem with the Scala Actor Model</title><content type='html'>Something seems wrong to with the whole send/! idea. The Scala guys say ! apparently means "send", but it really means "add message to actors mailbox", or "put". Take this example:&lt;br /&gt;&lt;br /&gt;actor ! message&lt;br /&gt;actor send message&lt;br /&gt;&lt;br /&gt;If ! means "send", then it certainly seems like the actor is sending the message. Of course, you have no idea who its sending it to, so by that logic it must be getting the message, but it still just seems confusing. I think the API might be more readable if it used one of the following:&lt;br /&gt;&lt;br /&gt;actor &lt;-- message &lt;br /&gt;message --&gt; actor&lt;br /&gt;&lt;br /&gt;I've demonstrated that you can use --&gt; and &lt;-- as method names already, so, why not use them here?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7458571340683428979?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7458571340683428979/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/my-small-problem-with-scala-actor-model.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7458571340683428979'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7458571340683428979'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/my-small-problem-with-scala-actor-model.html' title='My Small Problem with the Scala Actor Model'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7420920870721181766</id><published>2008-01-20T19:16:00.000-08:00</published><updated>2008-01-20T19:29:16.680-08:00</updated><title type='text'>Scala: Fold Left Question</title><content type='html'>I recently realized that I could make a piece of code I posted in a recent blog much cleaner using foldLeft. I have a bit of a problem however, the code is in a very performance sensitive area and I should break out of the fold whenever I encounter a certain condition. To the best of my knowledge foldLeft has no way to break out. It just folds all the way and you get your result at the finish. This is a bit unfortunate. Is there a way to break out and still keep the code clean?&lt;br /&gt;&lt;br /&gt;Here is my example, old code first. A PowerSource is on if any of its incoming power sources are on. &lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; private def updateOnOff = {&lt;br /&gt;   def calculateOnOff: boolean = {&lt;br /&gt;     incomingPowerSources.foreach( p =&gt; {if( p.isOn ) return true; })&lt;br /&gt;     return false;&lt;br /&gt;   }&lt;br /&gt;   val newOnOff = calculateOnOff&lt;br /&gt;   if( cachedOnOffBoolean != newOnOff ){&lt;br /&gt;     cachedOnOffBoolean = newOnOff&lt;br /&gt;     notifyConnections;&lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here is the new code using foldLeft.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  private def updateOnOff = {&lt;br /&gt;    &lt;b&gt;val newOnOff = incomingPowerSources.foldLeft( false )(_||_.isOn);&lt;/b&gt;&lt;br /&gt;    if( cachedOnOffBoolean != newOnOff ){&lt;br /&gt;      cachedOnOffBoolean = newOnOff&lt;br /&gt;      notifyConnections;&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The new code is far nicer than the old code. I've decided I'm going to go with it. In most cases PowerSources have only one direct input. Some have two, like OrGate, but for now I'm going to see what kind of performance hit I get.&lt;br /&gt;&lt;br /&gt;Now, if only I had a performance testing framework in Scala. Does anyone know of one?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7420920870721181766?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7420920870721181766/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/scala-fold-left-question.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7420920870721181766'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7420920870721181766'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2008/01/scala-fold-left-question.html' title='Scala: Fold Left Question'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-3762014169792704008</id><published>2007-12-30T16:12:00.000-08:00</published><updated>2008-01-01T07:41:08.047-08:00</updated><title type='text'>Closures Non Local Return - Scala And Java</title><content type='html'>I've heard a lot of people bickering about Java Closures. One of the many reasons they are fighting with each other is that in the BGGA proposal changes the semantics of &lt;span style="font-weight: bold;"&gt;return&lt;/span&gt;. In BGGA there can be local and non local returns (I'll explain those in a second). Bloch says it going to be too prone to bugs. Gafter says we need to do it before the language becomes a dinosaur. I tend to go with Neal on this one, maybe thats because I'm more adventurous and not quite as worried about bugs since I do extensive unit testing.&lt;br /&gt;&lt;br /&gt;Anyway, I wanted to demonstrate the problem in Scala. It did bite me today a little bit. I caught it quickly in my tests. The following two bits of code have different meanings:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;private def updateOnOff = {&lt;br /&gt; def calculateOnOff: boolean = {&lt;br /&gt;   incomingPowerSources.foreach( p =&gt; {if( p.isOn ) &lt;span style="color: rgb(0, 0, 0); font-weight: bold;"&gt;true;&lt;/span&gt; })&lt;br /&gt;   return false;&lt;br /&gt; }&lt;br /&gt; cachedOnOffBoolean = calculateOnOff;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private def updateOnOff = {&lt;br /&gt; def calculateOnOff: boolean = {&lt;br /&gt;   incomingPowerSources.foreach( p =&gt; {if( p.isOn ) &lt;span style="font-weight: bold;"&gt;return true;&lt;/span&gt; })&lt;br /&gt;   return false;&lt;br /&gt; }&lt;br /&gt; cachedOnOffBoolean = calculateOnOff;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The purpose of the updateOnOff function is to simply set the cachedOnOffBoolean to true if any incoming power sources are on. If none of them are on, the boolean is set to false. The inner function, calculateOnOff is responsible for looping through the incoming power sources to see if any are on. If one is on the function should return true to the outer function which sets the boolean.&lt;br /&gt;&lt;br /&gt;To be honest, I'm not sure which one is the local and which one isn't. I'm in the process of trying to figure it out. It seems natural to me though to assume that the first one is the local return. If anyone knows better, please let me know.&lt;br /&gt;&lt;br /&gt;The first example is an example of local return. Local return returns from the most local block of code, and in this case its the closure function itself, not the calculateOnOff function. The closure here is what's inside the foreach call:  &lt;span style="font-family:monospace;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;( p =&gt; {if( p.isOn )&lt;span style="font-weight: bold;"&gt; &lt;/span&gt;&lt;span style="color: rgb(0, 0, 0);"&gt;&lt;span style="color: rgb(0, 0, 0);"&gt;true;&lt;/span&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 0);"&gt; &lt;/span&gt;} )&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This is the function that will be returned from. It simply returns back to the loop, which goes on to the next item. Finally, when the loop is finshed, false is returned. So, in the first example false will &lt;span style="font-style: italic;"&gt;always &lt;/span&gt;be returned! This is certainly not correct.&lt;br /&gt;&lt;br /&gt;The second example is and example of non local return.  Specifying "return" before false means that you intend to return from the enclosing method, not just the closure itself. You intend to break out of the loop. You've found what you were looking for, and you were done. The return returns true from the calculateOnOff, and the boolean is set to true, just as you wanted.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Its pretty straight forward when you know it but I'm sure Bloch is right, there are going to be lots of bugs. Developers who don't use unit testing religiously are going to get it. A simply copy past from a refactoring, and boom.&lt;br /&gt;&lt;br /&gt;So what does this tell us? Well, at the least it says be careful, and write lots of unit tests. At the most it might mean that lots of idiots just stay in Java and the cool kids move on to Scala, and thats all right now baby, yeah.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-3762014169792704008?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/3762014169792704008/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/closures-non-local-return-scala-and.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3762014169792704008'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/3762014169792704008'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/closures-non-local-return-scala-and.html' title='Closures Non Local Return - Scala And Java'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4234440765327571491</id><published>2007-12-30T10:56:00.001-08:00</published><updated>2007-12-30T19:15:04.171-08:00</updated><title type='text'>Coolest Code I've Ever Written</title><content type='html'>Because Scala lets you name methods pretty much whatever you want, I got the chain wires together like this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt; @Test&lt;br /&gt; def lastPowerSourceInChainShouldBeNotifiedWhenFirstInChainIsTurnedOff() = {&lt;br /&gt;   //given&lt;br /&gt;   val first = new Generator&lt;br /&gt;   val secondToLast = new Wire&lt;br /&gt;  &lt;br /&gt;   &lt;span style="font-weight: bold;"&gt;first--&gt;new Wire--&gt;new Wire--&gt;new Wire--&gt;secondToLast&lt;/span&gt;&lt;br /&gt;  &lt;br /&gt;   val last = createMockWithConnectionTo(secondToLast)&lt;br /&gt;  &lt;br /&gt;   // when&lt;br /&gt;   first.turnOff&lt;br /&gt;  &lt;br /&gt;   // then&lt;br /&gt;   verify(Array(last))&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private def createMockWithConnectionTo( p: PowerSource ): PowerSource = {&lt;br /&gt;   val mockPowerSource: PowerSource = createStrictMock(classOf[PowerSource]).asInstanceOf[PowerSource];&lt;br /&gt;   expect( mockPowerSource &lt;-- p ).andReturn( p )     expect( mockPowerSource.handleStateChanged( p ) )     replay(Array(mockPowerSource))     p --&gt; mockPowerSource&lt;br /&gt;   mockPowerSource&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The --&gt;'s are actually methods on any PowerSource that connects the two together. So, the code can actually look like a chain of wires connected together. This is totally the coolest thing ever.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4234440765327571491?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4234440765327571491/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/coolest-code-ive-ever-written.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4234440765327571491'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4234440765327571491'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/coolest-code-ive-ever-written.html' title='Coolest Code I&apos;ve Ever Written'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5853469261041136291</id><published>2007-12-28T17:09:00.001-08:00</published><updated>2007-12-29T08:36:17.610-08:00</updated><title type='text'>Using TestNG in Scala: By Example</title><content type='html'>Here is a very, very simple example of some TestNG stuff that I wrote the other day in Scala (it can also be found &lt;a href="http://cpusimulator.googlecode.com/svn/trunk/src/test/scala/com/joshcough/cpu/electric/GeneratorTest.scala"&gt;here&lt;/a&gt;):&lt;br /&gt;&lt;br /&gt;package com.joshcough.cpu.electric;&lt;br /&gt;&lt;br /&gt;import org.testng.annotations._&lt;br /&gt;import org.testng.Assert_&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;package com.joshcough.cpu.electric;&lt;br /&gt;&lt;br /&gt;import org.testng.annotations._&lt;br /&gt;import org.testng.Assert._&lt;br /&gt;&lt;br /&gt;class GeneratorTest {&lt;br /&gt;&lt;br /&gt;  @Test&lt;br /&gt;  def expectNewGeneratorToBeOn() = {&lt;br /&gt;     val gen: Generator = new Generator&lt;br /&gt;        assertTrue(gen.isOn);&lt;br /&gt;    }&lt;br /&gt;  &lt;br /&gt;  @Test&lt;br /&gt;  def expectTurnedOffGeneratorIsOff() = {&lt;br /&gt;        val gen: Generator = new Generator&lt;br /&gt;        gen.turnOff&lt;br /&gt;        assertTrue(gen.isOff);&lt;br /&gt;    }  &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This might not be the prettiest code in the world, but:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;It works (which is more than I could accomplish with others)&lt;/li&gt;&lt;li&gt;I can run it in my IDE&lt;/li&gt;&lt;li&gt;I can run it in Ant&lt;/li&gt;&lt;li&gt;I only have to do exactly what I ever did with Java&lt;/li&gt;&lt;li&gt;Its still way better than JUnit&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;There were a few things I had to do to make this work:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;When compiling in Ant, I had to add this to my scalac call:&lt;br /&gt;&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;scalac style="font-weight: bold;"&gt;target="jvm-1.5" ...&lt;/scalac&gt;&lt;/li&gt;&lt;/ul&gt;&lt;li&gt;When compiling in Eclipse I had to do this:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;Project -&gt; Properties -&gt; Scala Compiler Properties -&gt; target = jvm-1.5&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;br /&gt;I could give a more detailed example, but I haven't tried it yet. I'm pretty sure that things like @BeforeMethod, @AfterClass, @DataProvider and what not all just work the same. I'll try to come up with a better example though.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5853469261041136291?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5853469261041136291/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/using-testng-in-scala-by-example.html#comment-form' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5853469261041136291'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5853469261041136291'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/using-testng-in-scala-by-example.html' title='Using TestNG in Scala: By Example'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-98786068184744928</id><published>2007-12-28T05:34:00.000-08:00</published><updated>2007-12-28T17:35:35.557-08:00</updated><title type='text'>Reading Scala</title><content type='html'>After working a bunch in Scala the other day, and continuing to obsess over it, I've realized something.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Reading the code Scala language source code is perfect code reading material.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;/span&gt;I had said that I needed some good code to read. Scala is perfect for this. Here are the reasons its good for me.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;It's really good code&lt;/li&gt;&lt;li&gt;Its easy to read (I guess these two go together nomally)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;It has a really nice mix of OO and Functional Programming (which I need to get better at anyway)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Its got a compiler written in Scala compiling to Java bytecode.   :)&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Its a langauge for god sakes, and I want to do language design so I should look at more language implementations&lt;/li&gt;&lt;/ul&gt;But, are those the same reasons its good for someone else to read? Maybe not, but I think Scala is still great for other people to read, beginners, professionals, and Ph.d's alike.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;The first two points hold true: Its really good code, and its easy to read.&lt;/li&gt;&lt;li&gt;Beginners could easily read the data structures code in Scala collections. They could learn their data structures, learn FP, and learn OOP better all at once.&lt;/li&gt;&lt;li&gt;Theres a wealth of stuff for more advanced people to read.&lt;br /&gt;&lt;/li&gt;&lt;ul&gt;&lt;li&gt;The Actor Model for instance, which is Scalas concurrency stuff built on top of Doug Lea's fork join.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;Langauge Designers could read it and learn a bit.&lt;/li&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;Compiler writers could read it and learn a bit.&lt;/li&gt;&lt;li&gt;Software Engineers could read it, and read the examples to learn a few things:&lt;/li&gt;&lt;ul&gt;&lt;li&gt;How to do things better in their own language&lt;/li&gt;&lt;li&gt;What they are missing stuck in an ancient language.&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;br /&gt;As I said before, It's probably helpful to read java.util.concurrent and the java collections stuff, and I'm sure theres a whole lot of other code thats great to read too. But, I'm getting worn out when it comes to Java. I'm ready to move on. Scala is new and fresh and exciting, &lt;span style="font-style: italic;"&gt;and, &lt;/span&gt;I'll learn more by doing it.&lt;span style="font-weight: bold;"&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-98786068184744928?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/98786068184744928/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/reading-scala.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/98786068184744928'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/98786068184744928'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/reading-scala.html' title='Reading Scala'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6753583927911236184</id><published>2007-12-26T20:02:00.000-08:00</published><updated>2007-12-29T09:26:08.764-08:00</updated><title type='text'>Unit Testing in Scala and in IDE's in General</title><content type='html'>I reviewed a few Scala unit testing frameworks today: &lt;a href="http://www.scunit.org/"&gt;SCUnit&lt;/a&gt;, and &lt;a href="http://rehersal.sourceforge.net/"&gt;Rehersal&lt;/a&gt;. When all was said and done I determined something that I found rather remarkable &lt;span style="font-weight: bold;"&gt;- &lt;/span&gt;TestNG is the best unit testing framework for Scala. For an example &lt;a href="http://jackcoughonsoftware.blogspot.com/2007/12/using-testng-in-scala-by-example.html"&gt;click here&lt;/a&gt;. To listen to my mind numbing justification of that radical statement, read on...&lt;br /&gt;&lt;span style="font-size:100%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;Why aren't new Unit Testing frameworks up to snuff?&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;The problem with any new unit testing framework in a new language is that it doesn't have IDE support. This is a huge pain in the ass for someone who relies on their IDE for everything (like me). TestNG already has IDE support, and you can use Java Annotations in Scala, so you can use TestNG just fine in Scala as well.&lt;br /&gt;&lt;br /&gt;Does that mean the test frameworks themselves are bad? No, they are fine. But to be entirely honest, its probably not all that worthwhile for someone to build a xUnit framework in Scala other than the fact that its probably really fun. And I say all this knowing full well that could be horse shit - I don't enough about Scala. There may be some nice syntactic stuff that makes testing in Scala just better, more readable, easier to write - I'm not sure.  Its my gut feeling. Anyway...&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;There is still a fundamental underlying problem here.&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;The main problem with this whole thing is (well there actually might be a couple, but one at a time) that if you want to write an xUnit framework for a language you have write the IDE support for it too. You shouldn't have to do this.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;So what can we do to fix this?&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;IDE's should provide xUnit framework plugin points. All you have to do is plug in your particular framework, and boom instant IDE suppport for your xUnit framework. I've been saying this for a while about languages themselves. All you need to do is plug-in the compiler and boom, you have everything. Maybe thats too much to bite off...but I don't think plugging in your own xUnit is.&lt;br /&gt;&lt;br /&gt;The JUnit and TestNG Eclipse plug-ins are nearly identical. They both look damn near the same as the test runner for NUnit. The patterns are clearly obvious. I haven't looked at the implementations at all, so I don't yet have any concrete ideas on how to make this happen, but its so worth it. Someone should do it. It could be me.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Finally...&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;This could be the first step towards instant IDE support for new languages. Maybe we identify several areas like this that are similar across languages and provide plug-in points for each. What would those features be? I'm not sure I still need to think. And, maybe more languages should just use the support of Java like Scala does.&lt;br /&gt;&lt;br /&gt;But, I have to say this was a great day. In my opinion realizing this was a real breakthrough in what I know about well, everything. Additionally, I think I am finally saying things that I haven't really heard other people saying. Maybe they are and I haven't read it, but I feel like I might actually be making some progress.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6753583927911236184?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6753583927911236184/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/unit-testing-in-scala-and-in-ides-in.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6753583927911236184'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6753583927911236184'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/unit-testing-in-scala-and-in-ides-in.html' title='Unit Testing in Scala and in IDE&apos;s in General'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-9117352292337018751</id><published>2007-12-26T19:52:00.000-08:00</published><updated>2007-12-28T05:54:13.620-08:00</updated><title type='text'>Things are coming together (and Scala is awesome)</title><content type='html'>I did a &lt;span style="font-style: italic;"&gt;ton&lt;/span&gt; of reading on Scala today, and I did a &lt;span style="font-style: italic;"&gt;lot&lt;/span&gt; of writing code and using Scala today. This makes me really happy. The best idea that I had today was to throw out any Java code on the CPU Simulator project, and do it all again in Scala. Why? Because if I write it in Java I won't learn as much. So, that is started, and a bunch of the new code is checked in.&lt;br /&gt;&lt;br /&gt;Oh man I have a lot to talk about with Scala. I wonder if I should break it into many posts... I think I will.&lt;br /&gt;&lt;br /&gt;But let me just say that I what I did today ties together everything I've been working on over the last four months. Doing the CPU Simulator in Scala helps me with languages, language design, IDE's, unit testing, compilers, reading code, preparing to teach classes, everything...&lt;br /&gt;&lt;br /&gt;I was sick today, yet able to do work. I didn't have much energy, but sitting here was fine. Mostly I didn't want to get other people sick so I didn't go to work. Anyway, I did some of my best work today, and I was able to come up with a lot of really good ideas and I want to write them down before they are gone forever.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-9117352292337018751?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/9117352292337018751/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/things-are-coming-together-and-scala-is.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9117352292337018751'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9117352292337018751'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/things-are-coming-together-and-scala-is.html' title='Things are coming together (and Scala is awesome)'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4464879361866576973</id><published>2007-12-12T17:59:00.000-08:00</published><updated>2007-12-12T18:20:57.256-08:00</updated><title type='text'>More on Reading Code</title><content type='html'>Let's revisit reading code and bring in some extra twists.  (Hint: Debuggers are WRONG)&lt;br /&gt;&lt;br /&gt;First, I know for a fact that I've read a lot of really really awful code. So based on what I said the other day, does this mean that I'm going to write really awful code? I like to think not. I'd like to think that it helps me understand what bad code is, how to read it and how NOT to write it.&lt;br /&gt;&lt;br /&gt;Does this help me write great code? Most definitely not. To do that you need to read great code.&lt;br /&gt;&lt;br /&gt;But, let's go back to that point about understanding the bad code. I can read bad code pretty well. I've been doing it for years. Sometimes I can actually get into the head of the developer (believe it or not, I used to write some pretty bad stuff, haven't we all?).  Anyway, since I can read it well, this is just another reason I don't need to use the debugger.&lt;br /&gt;&lt;br /&gt;By actually &lt;span style="font-style: italic;"&gt;reading the damn code&lt;/span&gt; I can figure out whats going on.  A well placed assertion in a unit test can confirm my beliefs. Sure, I could have used a well place break statement, but then I might be tempted to start stepping though code and wasting hours. Well thought out assertions in unit tests not only make the debugger basically useless to me, but give me regression testing going forward.&lt;br /&gt;&lt;br /&gt;This would all be for naught if I couldn't read bad code. I read it, I understand it, I don't need the damn debugger to tell me what I already know, I write tests, I improve code.&lt;br /&gt;&lt;br /&gt;I'm betting this:  &lt;span style="font-weight: bold;"&gt;people spending hours using the debugger just need to learn how to read code better.&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4464879361866576973?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4464879361866576973/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/more-on-reading-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4464879361866576973'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4464879361866576973'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/more-on-reading-code.html' title='More on Reading Code'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-769630687993477339</id><published>2007-12-09T19:04:00.000-08:00</published><updated>2007-12-09T19:15:54.069-08:00</updated><title type='text'>CPU Simulator on Google Code</title><content type='html'>No one might actually contribute, except myself, but I put my CPU Simulator project up on &lt;a href="http://code.google.com/p/cpusimulator/"&gt;http://code.google.com/p/cpusimulator&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;This wasn't just for the purpose of generating interest in this project, which is likely uninteresting to most people, but it was my first venture into creating/hosting my own project somewhere in the world. This is something that any self respecting developer should do at some point.&lt;br /&gt;&lt;br /&gt;Overall I think Google Code is fabulous. I had my project up in minutes, with my code in Subversion. You get a wiki,  downloads, administration, and a number of other things automatically.&lt;br /&gt;&lt;br /&gt;Also, and awesomely, this helps me solve a major problem. I've been bitching that I have no way to easily link to code that I've written. Well, now, see this: &lt;a href="http://cpusimulator.googlecode.com/svn/trunk/src/main/com/joshcough/cpu/gates/NorGate.java"&gt;http://cpusimulator.googlecode.com/svn/trunk/src/main/com/joshcough/cpu/gates/NorGate.java&lt;/a&gt;. Totally awesome.&lt;br /&gt;&lt;br /&gt;I was disappointed that you only get 10 projects lifetime, but I guess I'll have to choose them wisely. Maybe if I get to be a teacher, and I'm using several projects for teaching, they will lift that limit.&lt;br /&gt;&lt;br /&gt;Anyway, I'm really happy. Great day.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-769630687993477339?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/769630687993477339/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/cpu-simulator-on-google-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/769630687993477339'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/769630687993477339'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/cpu-simulator-on-google-code.html' title='CPU Simulator on Google Code'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-6779477397317617933</id><published>2007-12-08T19:43:00.000-08:00</published><updated>2007-12-08T20:28:49.162-08:00</updated><title type='text'>Reading Code</title><content type='html'>I haven't written and songs in a while. Way too long. Like, maybe a year. Terrible. It dawned on me just now (though I'm sure I knew it a long time ago) - I write more songs, and better songs, when I'm playing other peoples music. This is especially true when the music is difficult for me to play in some way (maybe the guitar part is hard, maybe the vocals are hard, maybe the rhythm is weird).&lt;br /&gt;&lt;br /&gt;Notice I said "playing" other peoples music and not "listening" to. However, when I'm listening to more music, I still write more than I do when I'm not. Its just that playing is even better.&lt;br /&gt;&lt;br /&gt;I not sure if I tie playing and listening to music to two different actions in code reading. I might try here, but the real point is that I need to read more code. And, it has to be good code of course.&lt;span style="font-weight: bold;"&gt; I need to read good code, and a lot of it.&lt;/span&gt; If I do my, code will become better and better.&lt;br /&gt;&lt;br /&gt;I suppose listening to music is like glancing over code once. You want to see it to know what it does, but you don't really care to understand the thought process behind it. I guess you don't &lt;span style="font-style: italic;"&gt;have&lt;/span&gt; to do that when you are playing someone else's song, but I usually do. So playing someone else's music is like, reading code really hard. Getting into the head of the coder, like getting into the head of the song writer. You can just glance at code, and just listen to a song. But, if you want to get better, you have to really concentrate on it. The better the song, the better the code, the more work put in, the better the results.&lt;br /&gt;&lt;br /&gt;At Oswego I don't think they did enough to say that we should always be reading good code. I think most schools probably don't stress this enough unfortunately. And, even more unfortunately, most of my professional career has been filled with &lt;span style="font-weight: bold;"&gt;terrible &lt;/span&gt;code. Because of those two things, I didn't read much code that was any good. I didn't even know that I should.&lt;br /&gt;&lt;br /&gt;When I struggled for a few years after college, it wasn't really obvious what the problem was. I was far and away the most talented guy in my class (I'm not even ashamed to act arrogant about this anymore, its just plain true), yet it didn't seem to translate to professional success. Finally I started reading books. Not so much reading code, but lots and lots of books. Things started looking up.&lt;br /&gt;&lt;br /&gt;I still haven't read good code though. Well, not that much of it. I need to read more. I'm certain that when I do my code will improve, maybe even dramatically. So, I plan to attempt to find some books on code reading, potentially this one: &lt;a href="http://www.spinellis.gr/codereading/"&gt;http://www.spinellis.gr/codereading/&lt;/a&gt;. But, thats obviously not enough. I need choose some good code to read.&lt;br /&gt;&lt;br /&gt;What are some good OSS projects to start reading? I read through CruiseControl Java a bit, and it was ok. But it was a little bit boring. I suppose it helps to pick something I'm familiar with. I think the java.util.concurrent that Dr. Lea wrote is the best place to start. It might be Java, which I'm getting sick of, but I'm certain its some of the most well written code there is.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;But here is something else important. &lt;/span&gt;I'd like to attempt to put together a bunch of code, somehow ordered by increasing difficulty. Why? So I could develop my own college course in code reading. It would be so fun to have a bunch of stuff in a bunch of different languages that gets more and more difficult to read, and have the students have to tell you what it does. And, add features to it. Oh man, what a good course. Its so practical too, thats what most of my development has been (though I wish it wasn't that way). Its been mostly - here is this code base, and I need you to add this feature to it.&lt;br /&gt;&lt;br /&gt;I think this is an essential class probably missing from most CS or SE programs. Maybe I'm wrong and just talking out of my ass, but I know it was missing at Oswego, and I consider Oswego to be one of the finest CS schools.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-6779477397317617933?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/6779477397317617933/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/reading-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6779477397317617933'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/6779477397317617933'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/12/reading-code.html' title='Reading Code'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-7585119353809156910</id><published>2007-11-21T08:16:00.000-08:00</published><updated>2007-11-21T09:32:37.388-08:00</updated><title type='text'>Testability vs. Encapsulation</title><content type='html'>I'm always on the side of Testability, but I'd like to hear some other peoples opinions on the subject. I think (in &lt;span style="font-style: italic;"&gt;most &lt;/span&gt;situations) its totally OK to relax encapsulation in favor of testability, but some people at my work do not. Let me give a rather long example of something I came across that bothered me a bit.&lt;br /&gt;&lt;br /&gt;I was trying to test a class - well call it G, with a Logger  - LOG , which was declared like this:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;static final Logger LOG = Logger.instance();&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Later on in G, I found a method shutdown, which called LOG.logAndExit() and logAndExit was final and called System.exit().&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;G:&lt;br /&gt;public void shutdown(){ LOG.logAndExit( "shutting down" ); }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;Logger:&lt;br /&gt;public final void logAndExit( String message ){&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    System.out.println(message);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    System.exit(0);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;If my tests wanted to test the shutdown method on G, the entire JVM would shutdown which simply shutdown my tests. Brilliant. I had to find some way to Mock or override the LOG variable. But there were several problems with that.&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;It was private&lt;br /&gt;&lt;/li&gt;&lt;li&gt;It was final&lt;/li&gt;&lt;li&gt;It was static&lt;br /&gt;&lt;/li&gt;&lt;li&gt;The logAndExit method was final&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;All of these things make difficult testing. I tried to get around the "private" by writing my &lt;a href="http://jackcoughonsoftware.blogspot.com/2007/11/privatefieldhelper-class.html"&gt;PrivateFieldHelper Class&lt;/a&gt;. But, as it turns out, you cannot change the accessibility of static final variables at Runtime. It only works for instance fields of all types, and non final static variables. So I was stuck with the LOG object that I had.&lt;br /&gt;&lt;br /&gt;Unless of course I relaxed encapsulation and removed the final from LOG. Then I could use my PrivateFieldHelper to set it to a new Logger of some kind. BUT...I still had a problem.&lt;br /&gt;The logAndExit method was final. So even if I extended our Logger class and tried to override logAndExit so that it wouldn't call System.exit(), I still could not do so. Even when I created a Mock Logger object using JMock I had the same problem. It appears that even mock objects can't override final methods.&lt;br /&gt;&lt;br /&gt;So once again I decided it was best to relax encapsulation. I removed the final keyword from Logger logAndExit, and created a new class - SafeLog - that overrode the logAndExit method. I used my PrivateFieldHelper to set the (now only static private) LOG field on G, and I was able to safely call the shutdown method from my test code.&lt;br /&gt;&lt;br /&gt;What a pain.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I understand that you can go way too far on this. Some people say you should never relax encapsulation for testability, because in doing so you relax intent and readability which later creates more of a maintenance problem. In some ways I do agree with this. On public API's and Libraries you most certainly will have higher maintenance costs. But, I do think removing a final here and a final there is ok, especially if its documented. I also think removing private in favor of default (package private) is ok.&lt;br /&gt;&lt;br /&gt;What do you think? Does anyone know of any good articles or books explaining the trade-offs?&lt;br /&gt;&lt;br /&gt;God this post is about to get long....&lt;br /&gt;&lt;br /&gt;Some say you shouldn't relax private for package private, and all testing should be done through public methods. This is another one I just don't agree with. Lets say you have a reasonably complicated class that only exposes one public method. People reading the class later on might not know what inputs are valid for and what outputs are expected for each of the private methods in the class.  You certainly can, and should get 100% code coverage through testing public methods, but it still might not be immediately obvious to someone reading the code later on what those private methods are doing.&lt;br /&gt;&lt;br /&gt;Testing private (or package private) methods extensively should make it immediately obvious. Once again, What do you think? Does anyone know of any good articles or books explaining the trade-offs?&lt;br /&gt;&lt;br /&gt;I think there can and should be things built into the languages themselves to expose hidden members to testing. Something &lt;span style="font-style: italic;"&gt;like &lt;/span&gt;a test keyword. Or like JSR 294, superpackages, which define what classes in a package are accessible, and to whom. If it things like this were built right into the language, exposing members to testing, then we wouldn't even be having these debates.&lt;br /&gt;&lt;br /&gt;How would it work? Maybe a lot like Generics. All the type information is removed at compile time, and so could any test availability information. You could turn this off. You could say, produce a jar for testing, and produce a jar for delivery. Its not that hard. Just ideas...You have any?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-7585119353809156910?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/7585119353809156910/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/testability-vs-encapsulation.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7585119353809156910'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/7585119353809156910'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/testability-vs-encapsulation.html' title='Testability vs. Encapsulation'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-9211340822109355153</id><published>2007-11-16T19:22:00.000-08:00</published><updated>2007-11-17T07:37:00.699-08:00</updated><title type='text'>CPU Simulator Library in Progress</title><content type='html'>I've been working on a lot of stuff lately and not writing. For that I apologize. I want to keep everyone updated on what I'm doing, but mostly I want to keep myself update for tracking progress and what not.&lt;br /&gt;&lt;br /&gt;I'm still wanting to design languages, write compilers, write IDE thingies, and all of that.  If you recall, I decided that in order to do that I should become a compiler master. In reading a lot about compilers I decided I should take yet another step back to refresh my memory on Computer Architecture.&lt;br /&gt;&lt;br /&gt;So I've been reading about that a LOT. Really low level, as low as possible. When I say as low as possible I even mean Quantum Physics. But, I don't intend to become a master in Quantum Physics. Its so fascinating but it also really almost drove me to insanity about 6 years ago. A simple refresher was all I needed.&lt;br /&gt;&lt;br /&gt;After that I read a bunch about the history of computers, mixed in with some history of philosophy, and mathematics. All really great stuff. Once again I don't intend to become an expert in it but I want solid foundations in all this stuff, which I feel I don't quite have. I'm close.&lt;br /&gt;&lt;br /&gt;So heres where the fun part begins. I started writing this cool little CPU simulator in Java. I don't have much yet but I'll keep the world informed. What I plan to do is - write classes that represent pretty much everything you'll find in a computer hardware. So far I have a MemoryModule class and things like that. You can imagine this pretty easily.&lt;br /&gt;&lt;br /&gt;We can start with a Computer class which has CPU, Memory, IO, and a Bus. We can then break the CPU down into ControlUnit, ALU, Registers, and maybe Connections. The ControlUnit can be broken down further into SequencingLogic, Registers, Decoders, ControlMemory, etc...&lt;br /&gt;&lt;br /&gt;This process of drilling down can probably go down to the atomic level. I'm not sure how low I'd go, where I'd draw the line. But the point is by doing all this, by actually writing the code, ensures that I understand each part. I could take some parts down further than others, and in doing so I'd learn more about that component. This is fine. I probably don't need to know things down to the atomic level on say, video. But going down to FullAdders and HalfAdders in the ALU, or even down to LogicGates is probably a useful thing to do. &lt;br /&gt;&lt;br /&gt;Maybe I can invent my own instruction set for my "Hardware", or reuse an existing one. Either way, once all of this is done it would be nice to write a little OperatingSystem class that makes use of that instruction set. I would learn a lot in doing so I imagine. Then once my OperatingSystem is in a reasonable state (I don't have any idea what that would look like yet), I could attempt to write a little compiler that compiles some random language down to an Assembly Language that runs on my hardware. &lt;br /&gt;&lt;br /&gt;This is a long way off but I think its a damn good goal. Yes its reproducing things that people have done 50 years ago in a way that most certainly won't be reusable, but whatever, it &lt;span style="font-style:italic;"&gt;will&lt;/span&gt; get me towards my goal of language writing.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-9211340822109355153?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/9211340822109355153/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/cpu-simulator-library-in-progress.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9211340822109355153'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/9211340822109355153'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/cpu-simulator-library-in-progress.html' title='CPU Simulator Library in Progress'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2793647422724856945</id><published>2007-11-16T17:00:00.000-08:00</published><updated>2007-11-17T07:31:24.385-08:00</updated><title type='text'>PrivateFieldHelper Class</title><content type='html'>Heres a little class I wrote to set private fields. I plan to use it a little for testing, but only when I'm backed into a corner, and can't change code otherwise.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;/**&lt;br /&gt; * &lt;br /&gt; * @author Josh Cough&lt;br /&gt; * &lt;br /&gt; */&lt;br /&gt;public class PrivateFieldHelperImpl implements PrivateFieldHelper {&lt;br /&gt;&lt;br /&gt; Class&lt;?&gt; clazz;&lt;br /&gt;&lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param c&lt;br /&gt;  */&lt;br /&gt; public PrivateFieldHelperImpl(Class&lt;?&gt; c) { this.clazz = c; }&lt;br /&gt;&lt;br /&gt; /*&lt;br /&gt;  * (non-Javadoc)&lt;br /&gt;  * @see com.joshcough.reflect.PrivateFieldHelper#setStaticFieldValue(java.lang.String, java.lang.Object)&lt;br /&gt;  */&lt;br /&gt; public void setStaticFieldValue(String fieldName, Object newValue)&lt;br /&gt;   throws IllegalArgumentException, NoSuchFieldException {&lt;br /&gt;  setPrivateFieldValue(findPrivateStaticField(fieldName), null, newValue);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /*&lt;br /&gt;  * (non-Javadoc)&lt;br /&gt;  * @see com.joshcough.reflect.PrivateFieldHelper#getStaticFieldValue(java.lang.String)&lt;br /&gt;  */&lt;br /&gt; public Object getStaticFieldValue(String fieldName) &lt;br /&gt;  throws NoSuchFieldException, IllegalArgumentException  {&lt;br /&gt;  return getPrivateFieldValue(null, findPrivateStaticField(fieldName));&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /*&lt;br /&gt;  * (non-Javadoc)&lt;br /&gt;  * @see com.joshcough.reflect.PrivateFieldHelper#getInstanceFieldValue(java.lang.Object, java.lang.String)&lt;br /&gt;  */&lt;br /&gt; public Object getInstanceFieldValue(Object instance, String fieldName) &lt;br /&gt;  throws NoSuchFieldException, IllegalArgumentException  {&lt;br /&gt;  return getPrivateFieldValue(instance, findPrivateInstanceField(fieldName));&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; /*&lt;br /&gt;  * (non-Javadoc)&lt;br /&gt;  * @see com.joshcough.reflect.PrivateFieldHelper#setInstanceFieldValue(java.lang.Object, java.lang.String, java.lang.Object)&lt;br /&gt;  */&lt;br /&gt; public void setInstanceFieldValue(Object instance, String fieldName, Object newValue)&lt;br /&gt;   throws IllegalArgumentException, NoSuchFieldException {&lt;br /&gt;  setPrivateFieldValue(findPrivateInstanceField(fieldName), instance, newValue);&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param f&lt;br /&gt;  * @return&lt;br /&gt;  * @throws &lt;br /&gt;  */&lt;br /&gt; private Object getPrivateFieldValue(Object instance, Field f) {&lt;br /&gt;  f.setAccessible(true);&lt;br /&gt;  Object o;&lt;br /&gt;  try {&lt;br /&gt;   o = f.get(instance);&lt;br /&gt;  }  catch (IllegalAccessException e) {&lt;br /&gt;   throw new PrivateFieldException(e);&lt;br /&gt;  }&lt;br /&gt;  f.setAccessible(false);&lt;br /&gt;  return o;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param f&lt;br /&gt;  * @param newValue&lt;br /&gt;  * @throws &lt;br /&gt;  */&lt;br /&gt; private void setPrivateFieldValue(Field f, Object instance, Object newValue){&lt;br /&gt;  f.setAccessible(true);&lt;br /&gt;  try {&lt;br /&gt;   f.set(instance, newValue);&lt;br /&gt;  } catch (IllegalAccessException e) {&lt;br /&gt;   throw new PrivateFieldException(e);&lt;br /&gt;  }&lt;br /&gt;  f.setAccessible(false);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param fieldName&lt;br /&gt;  * @return&lt;br /&gt;  * @throws NoSuchFieldException&lt;br /&gt;  */&lt;br /&gt; private Field findPrivateStaticField(String fieldName) throws NoSuchFieldException {&lt;br /&gt;  for (Field f : clazz.getDeclaredFields()) {&lt;br /&gt;   if (f.getName().equals(fieldName)) {&lt;br /&gt;    if (Modifier.isStatic(f.getModifiers()))&lt;br /&gt;     return f;&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt;  throw new NoSuchFieldException();&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; /**&lt;br /&gt;  * &lt;br /&gt;  * @param fieldName&lt;br /&gt;  * @return&lt;br /&gt;  * @throws NoSuchFieldException&lt;br /&gt;  */&lt;br /&gt; private Field findPrivateInstanceField(String fieldName) throws NoSuchFieldException {&lt;br /&gt;  for (Field f : clazz.getDeclaredFields()) {&lt;br /&gt;   if (f.getName().equals(fieldName)) {&lt;br /&gt;    if (! Modifier.isStatic(f.getModifiers()))&lt;br /&gt;     return f;&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt;  throw new NoSuchFieldException();&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2793647422724856945?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2793647422724856945/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/privatefieldhelper-class.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2793647422724856945'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2793647422724856945'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/privatefieldhelper-class.html' title='PrivateFieldHelper Class'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2875135700515095397</id><published>2007-11-16T07:38:00.000-08:00</published><updated>2007-11-17T07:50:50.028-08:00</updated><title type='text'>Cruise Control Remote Management API</title><content type='html'>I've never contributed to an OSS project before. Why that is I'm not quite sure. Looking through the CruiseControl Java code its pretty clear to me that I have the skills. I understand the code and I understand ways that I could refactor and improve it. I understand that I probably had those skills years ago. So why I haven't is beyond me; maybe I just never had the confidence.&lt;br /&gt;&lt;br /&gt;Anyway, I've finally submitted something. I wrote a CruiseControl Remote Management library that wraps the exposed JMX attributes and operations for a server and its projects. You can do nice things like getting a reference to a server, getting all its projects, force builds on projects, set labels on projects, lots of nice stuff. Here's a simple example that forces a build on all projects:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;CruiseServer server = new Server("localhost");&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;List&lt;/span&gt;&lt;cruiseproject&gt;&lt;span style="font-family: courier new;"&gt; projects = server.getProjects();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family: courier new;"&gt;for( CruiseProject p: projects ){&lt;/span&gt;&lt;span style="font-family: courier new;"&gt; p.forceBuild();&lt;/span&gt;&lt;span style="font-family: courier new;"&gt; }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You could do nice things with Build Pipelining like trigger builds in other CruiseControl instances on different servers after a project on your server builds. Indeed, thats actually what I've done.&lt;br /&gt;&lt;br /&gt;I think that this code could be used to clean up a lot of the code in their current tree. Maybe I'm wrong, or maybe they already have something like this, but I didn't see it.&lt;br /&gt;&lt;br /&gt;Hopefully they will take this and add it in. Maybe they will ask me to add it in. Maybe I'll get to refactor a bunch of their Dashboard code. I'm almost certain it would be cleaner using this.&lt;br /&gt;&lt;br /&gt;We'll see what happens.&lt;br /&gt;&lt;br /&gt;&lt;/cruiseproject&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2875135700515095397?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2875135700515095397/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/cruise-control-remote-management-api.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2875135700515095397'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2875135700515095397'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/11/cruise-control-remote-management-api.html' title='Cruise Control Remote Management API'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2054243427484154</id><published>2007-10-30T19:58:00.000-07:00</published><updated>2007-10-30T20:07:46.485-07:00</updated><title type='text'>Closures</title><content type='html'>Can anyone tell me how closures are implemented?&lt;br /&gt;&lt;br /&gt;Scala has closures, and it compiles to Java bytecode, but, Java doesn't have closures. This is not to say that it can't be done, of course. I'm sure the implementation is probably not that hard. I'm just really curious to know how its done...  I &lt;span style="font-style: italic;"&gt;could &lt;/span&gt;go look at the source code for the Scala compiler of course. But I have been working on a number of other things.&lt;br /&gt;&lt;br /&gt;I wrote a library for remote management of CruiseControl that seems to be much easier to use than the one they are using in the new Dashboard. I'm going to try to get that submitted here shortly. I'm starting to feel pretty confident in my development skills. Finally. I'm also starting to feel confident in my code reading skills too. I was able to look through the CC Java code with ease. Of course it helps that its mostly nice clean code, but still, I'm doing well.&lt;br /&gt;&lt;br /&gt;Well enough, I suppose, that I could figure out how closures are implemented. &lt;span style="font-style: italic;"&gt;And, &lt;/span&gt;since no one reads my blog anyway, I think I'm on my own.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2054243427484154?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2054243427484154/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/closures.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2054243427484154'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2054243427484154'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/closures.html' title='Closures'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4412253667059067218</id><published>2007-10-18T18:24:00.000-07:00</published><updated>2007-10-18T19:27:04.489-07:00</updated><title type='text'>But Thats How It Was When I Got Here</title><content type='html'>&lt;span style="font-size:100%;"&gt;&lt;span style="font-style: italic; font-weight: bold;"&gt;Companies typically let their build system go to shit.&lt;br /&gt;&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;br /&gt;Why is that? Does anyone have an answer to this? The first thing I ever do on new projects is make sure I have a consistent build process. ThoughtWorks was the same way. The first thing I look at when joining a new company is the build process, and how to fix it. Why don't most companies do this themselves? I have some ideas, here they are:&lt;br /&gt;&lt;/span&gt;&lt;ul&gt;&lt;li&gt;&lt;span style="font-size:100%;"&gt;They don't know how.&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-size:100%;"&gt;They somehow (wrongly) think its not as valuable as developing the next features&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-size:100%;"&gt;They get comfortable with the fact that it takes an hour to build, because it works&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style="font-size:100%;"&gt;They suffer from "But Thats How It Was When I Got Here" syndrome&lt;br /&gt;&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;span style="font-size:100%;"&gt;All of these are BAD BAD BAD reasons, and all make me very offended. Those might not be the only reasons, and they might not be the best reasons, but regardless, I'm going to tear them apart. My intention is not to make my coworkers feel bad, but to wake them up to the reality that theres a lot of new technology out there that they need to be learning and leveraging.&lt;br /&gt;&lt;/span&gt;&lt;span style="font-size:100%;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;They don't know how.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;If you don't know how to do something entirely modern, then you need to start learning. Everyone knows this, but so few people do it. Why? (Topic for a whole new blog posting). If you don't do it you're going to be passed by. This will occur first on the individual level, people will start to pass you making more money and you'll wonder why. Well, knowledge is why.&lt;br /&gt;&lt;br /&gt;Worse though, if this is somehow your corporate culture, not learning new technology, eventually your whole company is going to stagnate. I refuse to let this happen at my group. Fortunately we have some great people who are eager to learn.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-size:100%;"&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;They somehow (wrongly) think its not as valuable as developing the next features&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;If you think its not valuable, you're dead wrong. If you don't have a repeatable build process someone will end up making a mistake and you'll deliver something broken to a client. Maybe that never happens, but you WILL end up slowly adding to your awful build process until you get something that is a total pile of nonsense. With this pile, any change takes days or weeks to figure out. You have to figure out all the side effects, you have to somehow verify that a updated build process produces the same results as the old process.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-size:100%;"&gt;&lt;span style="font-weight: bold;"&gt;They get comfortable with the fact that it takes an hour to build, because it works&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Believe it or not, if you are comfortable with your build process this is actually a sign that something might be wrong. I am &lt;span style="font-weight: bold;"&gt;never &lt;/span&gt;comfortable with my build process. I'm always tweaking it, trying to make it run faster, trying to remove duplication from it, trying this trying that...I think a good build should be less than 5 minutes. Some people say ten. I don't agree. If you have an hour build, you're likely doing a bunch of manual steps and will run into the problems I pointed out in the last step. If you have an hour long build and its completely automated then you have other issues that aren't quite as serious, but are still very bad.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-size:100%;"&gt;&lt;span style="font-weight: bold;"&gt;But Thats How It Was When I Got Here&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:100%;"&gt;This one is troublesome to me. I HATE legacy software. I feel like. I don't know, some kind of Vigilante on a mission to KILL it. Unfortunately, even I find myself saying, "But thats how it was when I got here" from time to time. This is not a good excuse. If you're saying that now, you'll probably go on saying this until you end up in a situation like the last two items. This is almost an excuse for all the other items rolled up into one. Its like saying, "Yeah I know its bad, but what can you do?" And on top of that, its like, a way out, a way of saying, "I'm not going to deal with that problem." Well, guess what? You are going to deal with it, the hard way.&lt;/span&gt;&lt;span style="font-weight: bold;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;So is this all avoidable? Of course. "But how?" One simple way, READ. DAMN YOU. READ MORE. Thats it. Really. Just read what people are writing and you'll learn how to do things right. Now, if only we could get everyone to read. I smell a post.&lt;br /&gt;&lt;span style="font-style: italic; font-weight: bold;"&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4412253667059067218?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4412253667059067218/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/but-thats-how-it-was-when-i-got-here.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4412253667059067218'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4412253667059067218'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/but-thats-how-it-was-when-i-got-here.html' title='But Thats How It Was When I Got Here'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-5739906072561965244</id><published>2007-10-18T06:13:00.000-07:00</published><updated>2007-10-19T06:12:57.222-07:00</updated><title type='text'>Agitar Examples</title><content type='html'>I finally have a chance to post some examples of code generated by Agitar. I promised them in comments to the original post, but it turns out this is easier. First, I'll give a little background on the code that I wanted to test, and then I'll show the tests generated by Agitar. This example is designed to show the readability of Agitar. If a test fails after a change and its difficult to read, what approach should a developer take - read the test and see why it failed, or regenerate the test?&lt;br /&gt;&lt;br /&gt;I wrote a simple interface for returning all the files under a directory:&lt;br /&gt;&lt;br /&gt;(By the way I lost all my formatting and I apologize. Formatting on Blogger is a PITA.)&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public interface ListFilesStrategy {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    public List&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt; listFiles(File dir);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I have a two classes implementing this interface, RecursiveListFilesStrategy and NonRecursiveListFilesStrategy, which both extend AbstractListFilesStrategy.Here are the listings for AbstractListFilesStrategy and NonRecursiveListFilesStrategy:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public abstract class AbstractListFilesStrategy {&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    public void assertFileIsDirectory(File dir) {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        if( dir == null )&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;            throw new IllegalArgumentException("directory is null");&lt;/span&gt;&lt;br /&gt; &lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        if( ! dir.isDirectory() )&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;            throw new IllegalArgumentException("file is not directory");&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public class NonRecursiveListFilesStrategy extends AbstractListFilesStrategy&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    implements ListFilesStrategy{&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    public List&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt; listFiles(File dir){&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        assertFileIsDirectory(dir);&lt;/span&gt;&lt;br /&gt; &lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        List&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt; files = new ArrayList&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt;();&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        List&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt; directories = new ArrayList&lt;/span&gt;&lt;file&gt;&lt;span style="font-family:courier new;"&gt;();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        directories.add(dir);&lt;/span&gt;&lt;br /&gt; &lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        while(! directories.isEmpty()){&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;            File currentDir = directories.remove(0);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;            for( File f: currentDir.listFiles()){&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;                if (f.isFile()) files.add(f);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;                else directories.add(f);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;            }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        return files;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Now the test Agitar generated that was difficult to read. This test tested the listFiles method on my NonRecursiveListFilesStrategy:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public void testListFilesWithAggressiveMocks1() throws Throwable {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        NonRecursiveListFilesStrategy nonRecursiveListFilesStrategy = new NonRecursiveListFilesStrategy();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File file = (File) Mockingbird.getProxyObject(File.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File file2 = (File) Mockingbird.getProxyObject(File.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File[] files = new File[0];&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File file3 = (File) Mockingbird.getProxyObject(File.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File[] files2 = new File[2];&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File file4 = (File) Mockingbird.getProxyObject(File.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        File file5 = (File) Mockingbird.getProxyObject(File.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        files2[0] = file4;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        files2[1] = file5;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.enterRecordingMode();&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Boolean boolean2 = Boolean.TRUE;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, file, "isDirectory", "()boolean", new Object[] {}, boolean2, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        ArrayList arrayList = (ArrayList) Mockingbird.getProxyObject(ArrayList.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.replaceObjectForRecording(ArrayList.class, "&lt;/span&gt;&lt;init&gt;&lt;span style="font-family:courier new;"&gt;()", arrayList);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        ArrayList arrayList2 = (ArrayList) Mockingbird.getProxyObject(ArrayList.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.replaceObjectForRecording(ArrayList.class, "&lt;/span&gt;&lt;init&gt;&lt;span style="font-family:courier new;"&gt;()", arrayList2);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Boolean boolean3 = Boolean.FALSE;&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, arrayList2, "add", "(java.lang.Object)boolean", new Object[] {file}, boolean3, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(arrayList2.isEmpty(), false);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(arrayList2.remove(0), file2);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, file2, "listFiles", "()java.io.File[]", new Object[] {}, files, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(arrayList2.isEmpty(), false);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(arrayList2.remove(0), file3);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, file3, "listFiles", "()java.io.File[]", new Object[] {}, files2, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, file4, "isFile", "()boolean", boolean2, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, arrayList, "add", "(java.lang.Object)boolean", boolean3, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, file5, "isFile", "()boolean", boolean3, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(false, arrayList2, "add", "(java.lang.Object)boolean", boolean3, 1);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.setReturnValue(arrayList2.isEmpty(), true);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        Mockingbird.enterTestMode(NonRecursiveListFilesStrategy.class);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        List result = nonRecursiveListFilesStrategy.listFiles(file);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        assertNotNull("result", result);&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    }&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;This is certainly difficult to read. I'm pretty sure I could explain what its doing, but I'm more well read in testing and mocks than most developers. There are a few things they could do to clean it up however. They could try to be more in line with Behavior Driven Development and they have a few options in doing so. The method doesn't have an intent revealing name, I know what method its testing, but I don't know exactly what its doing. They could put in "given, when, then comments". The could use the extract method refactoring to seperate out the setup, the action, and the assertions, but maybe at least the setup portion.&lt;br /&gt;&lt;br /&gt;All these things could be done, but even so there is a lot of setup happening here, and Most developers aren't ready, or aren't willing to read through it, and will likely start to ignore Agitar errors.&lt;br /&gt;&lt;br /&gt;Now, I was told by Barry at Agitar that I could put in a test helper class, which would basically provide the setup portion of the test, and then it would generate more meaningful results. Here is an example:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public class FileTestHelper implements ScopedTestHelper {&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;    public static File createFile() {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;          return new File("./src/main");&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;     }&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Should result in something like this …&lt;br /&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;public void testListFiles() throws Throwable {&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        ArrayList result = (ArrayList) new NonRecursiveListFilesStrategy().listFiles(FileTestHelper.createFile());&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;        assertEquals("result.size()", 5, result.size());&lt;/span&gt;&lt;br /&gt;&lt;span style="font-family:courier new;"&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Indeed, I could do something like this. But, there is a big problem with this. We have 5000+ classes that we want to generate tests for! How do we know which tests are meaningful, which ones need test helpers, yada yada?&lt;br /&gt;&lt;br /&gt;I do promise more examples of simple methods that don't seem to be giving meaninful results. Mostly just checking to make sure methods catch NullPointerException. I do think the product will work wonderfully for green development, but will likely be ignored during legacy developement. Please let me know your thoughts.&lt;/init&gt;&lt;/init&gt;&lt;/file&gt;&lt;/file&gt;&lt;/file&gt;&lt;/file&gt;&lt;/file&gt;&lt;/file&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-5739906072561965244?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/5739906072561965244/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/agitar-examples.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5739906072561965244'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/5739906072561965244'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/agitar-examples.html' title='Agitar Examples'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2372439017401391194</id><published>2007-10-14T17:42:00.000-07:00</published><updated>2007-10-14T17:55:28.062-07:00</updated><title type='text'>IDE's vs vi</title><content type='html'>I just told my friend that instant IDE support for new languages is the place to be (I truly believe this can happen). In response he told me, "I love vi."&lt;br /&gt;&lt;br /&gt;I know vi, and I can get around in it OK, but I'm not a hardcore vi guy. I know there are some things you can do in vi that are really nice and allow you to do some things very quickly and powerfully. But, I don't know what they are. The real question here is, can vi do things that modern IDE's cant do? Can someone explain to me this?&lt;br /&gt;&lt;br /&gt;I do think that vi is ancient technology, and I'm sure thats old news anyway. I don't know very many people who use vi or emacs anymore. I'm sure a lot of people would look at my friend funny for that comment. But I'm a little different. I'm curious.&lt;br /&gt;&lt;br /&gt;What features do retired editors have that modern IDE's lack?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-2372439017401391194?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/2372439017401391194/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/ides-vs-vi.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2372439017401391194'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/2372439017401391194'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/ides-vs-vi.html' title='IDE&apos;s vs vi'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-4750668670042539868</id><published>2007-10-14T06:26:00.000-07:00</published><updated>2007-10-14T06:31:51.859-07:00</updated><title type='text'>Questions on Blogger</title><content type='html'>So I like the look and feel of Blogger, but I have some problems with it.&lt;br /&gt;&lt;br /&gt;I really need to be able to upload files as attachments to my blog.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Is there a way to do this?&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Is there another site that allows you to do this?&lt;/li&gt;&lt;li&gt;If I host my own site can is there on OSS blog that I can put up that allows me to upload files?&lt;/li&gt;&lt;li&gt;Should I just use a wiki?&lt;/li&gt;&lt;li&gt;Should I just host my own site and link to files from Blogger to my site?&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Whats the best way to go about all this? Seems like the easiest is to go with the last option. But, I don't want to host at home anymore. Does anyone know the easiest way to do hosting these days? I used to host at home a few years back but I'm now out of touch with hosting.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34927953-4750668670042539868?l=jackcoughonsoftware.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jackcoughonsoftware.blogspot.com/feeds/4750668670042539868/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/questions-on-blogger.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4750668670042539868'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34927953/posts/default/4750668670042539868'/><link rel='alternate' type='text/html' href='http://jackcoughonsoftware.blogspot.com/2007/10/questions-on-blogger.html' title='Questions on Blogger'/><author><name>Jack Cough</name><uri>http://www.blogger.com/profile/04509343962912103631</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34927953.post-2284521323399008186</id><published>2007-10-12T16:44:00.000-07:00</published><updated>2007-10-15T20:21:21.278-07:00</updated><title type='text'>A Day of JavaCC!</title><content type='html'>In a dream come true, I got to write a bunch of stuff using JavaCC at work today. It was fantastic. I was able to identify the fact that we needed JavaCC for a particular problem, and sell peop
