Friday, September 21, 2012

Test Buddy: Bennie

For you slow running tests... you now have a friend. His name is Bennie.

Friday, September 14, 2012

Source-Learning-Closure: Day 3

So the start of the 3rd day of digging in Clojure's source, I'm scanning through the code looking for something that I want to dig further into. I'm finding my self relatively happy with the progress I've made so far. Looking over the various functions, I'm noticing that it looks a lot less foreign now.

(cast) calls java's cast, passing in a class and a class name to cast to. (to-array) calls clojure's java wrapper to toArray(), (vector) has a bunch of overloads to constructing a vetor, and so on. Much of those and the one's like (nil?), (false?), (not), and such are really straight forward, many of which just call the java code underneath. All of these become just needing to read up on whats available for our use.

For the most part, I'm scanning the code and all is well. Then I get to the functions for (if-let) and (when-let) and I'm taken back again.

https://github.com/clojure/clojure/blob/1.3.x/src/clj/clojure/core.clj#L1666

I'm reading them a few times, and although I can follow the code, I'm not really sure what they are doing. I also notice that I'm not as comfortable with (let) as I want to be either. So I'm going to look at (let) in more detail first.

I read over the docs and some other info else where like this. I get a better feel for it. I just needed to work through some examples. I won't bore you with to many. The idea with (let) is you create a local scope that you can manipulate your data with.

As I'm digging through let I also run into the (->) function. That one apparently runs through a group of functions in order that you give them. I won't go to much into details about this one here as this post will get really long with every derail, but I figured I'd mention it in passing as I'm about to use it, and I myself didn't know what it was until just now.

user=> (let [message "rawr"] (println message))
rawr
nil

user=> (message)
java.lang.Exception: Unable to resolve symbol: message in this context (NO_SOURCE_FILE:27)
user=> (let [a 1, b 2] (+ a b))
3

user=> 
(let [age (- 2012 1979), decade 10, century 100]
  (-> (- century decade) (+ age))
)
123

That local declaration/logic peers into the future, a decade less than a century from now, to tell me how old I will be. Here's something else I noticed while looking at the examples. I really don't like it for these examples, but I'm sure there's use for it else where.

(let [a 1, b 2] (+ a b)) ; earlier example
3

(let [[a b] [1 2]] (+ a b)) ; can also be written this way
3

These two are the same call, however the second one uses a complex vector. where it maps the first values together and the second values together. In these simple cases I like the first version much beter. When I run into a reason to use the second one, I'll share.

Back on Track

(defmacro if-let
  "bindings => binding-form test

  If test is true, evaluates then with binding-form bound to the value of 
  test, if not, yields else"
  {:added "1.0"}
  ([bindings then]
   `(if-let ~bindings ~then nil))
  ([bindings then else & oldform]
   (assert-args if-let
     (and (vector? bindings) (nil? oldform)) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
     `(let [temp# ~tst]
        (if temp#
          (let [~form temp#]
            ~then)
          ~else)))))

The first thing I see that I don't know what it is, is the (assert-args) call. I can make some guesses, but I have a few so I figure its a good one to look up to make sure. After hitting the google, I quickly find out that it's a private function and not an openly accessible one, I won't be calling it with my code. But it's still good to understand for the sake of this exercise. Looking at the source for this one, I see that is runs through the arguments of the function and makes sure that the correct number of arguments were passed in based on what the function want. Seeing that I feel silly as the function was named pretty well and that could have just been implied.

  ([bindings then]
   `(if-let ~bindings ~then nil))

The next part I start looking at is the one above this. Having no idea what's going on here with the ` and the ~ symbols, I do some searching online. It turns out that this is a macro and the ~ symbol is replacing those values with the values being passed in. Lets look at this example:

user=>
(let [msg "rawr"] 
  `(println ~msg)
)
(clojure.core/println "rawr")

With my surface understanding of what's going on here, is we are creating a function that we can run at a later point. Seeing as how macros are a big chapter in a book I'm about to get back to, I'm not going to dig in past the surface for now. However our chunk of code in the if-let that we are looking at, creates a macro to call itself again putting the 'bindings' and the 'then' into place with a nil value. Which turns out is the overload call in this function, so we'll move on to that.

(let [form (bindings 0) tst (bindings 1)]
     `(let [temp# ~tst]
        (if temp#
          (let [~form temp#]
            ~then)
          ~else)))))

We see some heavy use of (let) which is ok, we know it's just setting stuff up locally for the function. then we see this guy: [form (bindings 0) tst (bindings 1)]. I do some searching online and read over the function some more then I realize how silly I was. In this function, bindings is being asserted that it's a vector (array), and you can get the value of a vector at an index by calling the vector as a function. So: ([99, 200] 1) returns 200. I attribute my lack of reading this one to the syntax highlighting. In the source, "bindings" and "assert-args" were the same color, making them stand out. "assert-args" was a private function doing stuff under the hood, I assumed "bindings" was also.

After that last puzzle piece, the whole thing becomes readable to me. Call if-let, pass in some bindings and then a then function and let it rip. As long as all the checks pass, it will bind the values and then call the 'then' function passed in.

Lets see if I'm right and try it.

user=> (if-let [is-young true] (println "young")) 
young
nil

user=> (if-let [is-young false] (println "young"))                
nil

Technically I had the right idea, but I was missing part of the idea of what if-let does. The "if-let" function allows us to streamline a "let" block and a nested "if" statement into one cleaner call. So although my code worked, you really want to pass in the actual "then" statement.

user=> (if-let [is-young false] "young" "old")
"old"

user=> (if-let [is-young true] "young" "old") 
"young"

user=> (if-let [is-young true] (println "young") (println "old"))
young
nil

user=> (if-let [is-young false] (println "young") (println "old"))
old
nil

(if-let [is-young true is-old false] (println "young") (println "old"))
java.lang.IllegalArgumentException: if-let requires exactly 2 forms in binding vector (NO_SOURCE_FILE:0)

user=> (if-let [is-young] (println "young") (println "old"))                  
java.lang.IllegalArgumentException: if-let requires exactly 2 forms in binding vector (NO_SOURCE_FILE:0)

The last few calls, I just wanted to see the exceptions we were looking at if we didn't pass in the correct number of arguments for the vector to be formed from. The author of the code went through the trouble to put them in, may as well get some use out of them. :)

Summary

We looked at the (if-let) code, gaining a better understanding of (let) in the process (which makes sense as I was missing the whole point of (if-let) in the first place), touched the surface of macros, gained a passing understanding of the (->) function, saw a way of writing more complex vectors (which I'm not a fan of yet), and found that there is such a thing as private functions in Clojure.

Better understanding Clojure recur

Just playing around with recur more. I really didn't like the example they had online. After digging around some, I got the idea behind recur, it recalls the function it directly sits under. Mostly I see it used in loops in the examples online, however the = function we were looking at yesterday didn't. It was just calling the normal function it was in.

Quick warning, the first couple of examples won't have a way to stop them. I'm running them in repl, and CTRL+C to stop them. I felt that this best explains what recur is doing.

(defn recur-test 
  [message] 
  (println message) 
  (recur message)
)

user=>(recur-test "rawr")
rawr
rawr
rawr
...
(defn recur-test 
  [message count]
  (println (format "%s: %s" message count))
  (recur message (inc count))
)

user=>(recur-test "rawr" 0)
rawr: 0
rawr: 1
rawr: 2
rawr: 3
...

Let's add the if check into the function so we don't have to keep CTRL+C our repl.

(defn recur-test 
  [message count]
  (println (format "%s: %s" message count))
  (if (< count 5)
    (recur message (inc count))
  )
)

user=> (recur-test "rawr" 0)
rawr: 0
rawr: 1
rawr: 2
rawr: 3
rawr: 4
rawr: 5
nil

It becomes pretty apparent what recur is and is doing at this point. Now when we look at the examples on recur in the docs, it makes more sense for those who haven't seen it before: recur docs

Thursday, September 13, 2012

Source-Learning-Closure: Day 2

Previously we looked at the clojure source for the + function and after looking at. Today, we're going to look through the code for the = function.

Clojure: =

Equality. Returns true if x equals y, false if not. Same as Java x.equals(y) except it also works for nil, and compares numbers and collections in a type independent manner. Clojure's immutable data structures define equals() (and thus =) as a value, not an identity, comparison.

https://github.com/clojure/clojure/blob/1.3.x/src/clj/clojure/core.clj#L718

(defn =
  "Equality. Returns true if x equals y, false if not. Same as
  Java x.equals(y) except it also works for nil, and compares
  numbers and collections in a type-independent manner.  Clojure's immutable data
  structures define equals() (and thus =) as a value, not an identity,
  comparison."
  {:inline (fn [x y] `(. clojure.lang.Util equiv ~x ~y))
   :inline-arities #{2}
   :added "1.0"}
  ([x] true)
  ([x y] (clojure.lang.Util/equiv x y))
  ([x y & more]
   (if (= x y)
     (if (next more)
       (recur y (first more) (next more))
       (= y (first more)))
     false)))

This one starts off pretty simple and much like the last one, so we do some testing with the first couple overloads to see what comes back:

user=> (= 1)
true

user=> (= "")
true

user=> (= nil)
true

The first overload is what you would expect, passing anything into it returns true. I might be looking at this wrong, but this seems kind of pointless.

user=> (= 1 1)
true

user=> (= 1 2)
false

user=> (= 1 "1")
false

user=> (= 1 :1)
false

user=> (= nil nil)
true

No surprises there. And then for the last overload:

([x y & more]
   (if (= x y)
     (if (next more)
       (recur y (first more) (next more))
       (= y (first more)))
     false)))

Off the bat we've got if statements, next/first calls and recur. The if statements are pretty straight forward in Clojure: (if test then else) if check succeeds return value else return other value.

user=> (if true "yes" "no")
"yes"

user=> (if false "yes" (if true "nested yes" "nested no"))
"nested yes"

So we have nested if statements, where either value returned can be a function call, after all functions always return. Next and First are functions to navigate through collections, next gets the next item in the collection, or "more" in this case, where first grabs the first item. Which leaves us with recur. This isn't one I'm familiar with so lets go look it up and see what can be done with it.

The more I searched through the docs, and online resources the more I realized I was assuming recur to be something other than what it is. After digging around a bit, I realized that it wasn't something to be used on it's own. It's purpose is to re-call the function that it's contained in passing in a function to apply before it's next call. The examples online mostly point to loops and such. I then realized I had no idea how to do a loop in Clojure, so I started playing around with that. After much pain I figured out what this example was doing and had a better understanding of loops and recur.

user=> (loop [x 10]
  (when (> x 1)
    (println x)
    (recur (- x 2))))
10
8
6
4
2
nil

So I wanted to put myself to the test. I wanted to create something that wasn't in clojure using a loop & recur. The first thing that jumped into my head was programming's ++ incremental call. But seeing as how that is totally yesterdays math, I want to implement a +++ function! That's right increment by 2, not 1.

As I was digging into it, I realized I had bigger issues...

user=> (defn +++ [val] 
  (loop [i 0] 
    (if (< i 2) (do 
      (+ val 1) 
      (println val)
      (recur (+ i 1))
    ))
  ))
nil
#'user/+++

user=> (+++ 1)
1
1
nil

How was I going to update the parameter passed in, incrementing it and keeping the new value? I tried setting a local variable and updating that, a global variable would probably work but I didn't want to go there, and some random exception throwing syntax goof-rounds. It hit me pretty hard, I've got a lot to learn about Clojure & functional programming in general. So I start looking for other examples online, which eventually led me to a loop that had two sets of values in the loop call: (loop [i 0 j 99]... for example. And in those cases the recur call passed in two functions to apply to the two sets in the loop. That gave me enough to put together a loop that incremented on "i" and updated a value on the second set. Here's what I came up with:

(defn +++ 
  [val] 
  (loop [i 0, return-val val] 
    (if (< i 2) 
      (do 
        (inc return-val) 
        (recur (inc i) (inc return-val))
      )
 
      return-val
    )
  )
)
#'user/+++

user=> (+++ 1)
3

user=> (+++ 99)
101

After a bunch of trial & error, troubleshooting and repl running, I created a +++ incrementing function in Clojure!

Back on Task

([x y & more]
   (if (= x y)
     (if (next more)
       (recur y (first more) (next more))
       (= y (first more)))

So now what do I think the last overload is doing in the = function of Clojure? The syntax is different than the recur & loop blocks I was playing with, but I think that's saying if the first to parameters are equal, continue checking the "more" to make sure they are equal. By which, if there is a "next" item in "more" recur call the whole function ([x y & more]) passing in y to x, the first in "more" and the next of "more" to re-fire off the check. And when it gets to the end, if there aren't any additional values in "more", check the last y we've got against the last (first in a collection of one) value to see if they are equal.

Summary

So, we've looked at the = function, and in tandem most of the other equality functions = == < &rt; and so on, as they were all pretty similar. But what I got from today's digging is that, understand the basics of loops/do/while, and can now read recur logic. We'll at least the simple recur logic I've shown here, it feels like recur has some hidden powers I don't see yet. Oh, and I extended Clojure with the much needed +++ incremental math! :)

The other thing that I'm starting to see, is the difference in functional programming as compared to object-oriented. Up until now, I had only been seeing a completely different syntax, nothing about different thought processes. Now that I'm getting to understand & read Clojure better, I'm starting to but up against the difference in programming thoughts.

Wednesday, September 12, 2012

Source-Learning-Closure: Day 1 (Update)

As I stated in the post about learning the insides of +

Previous post on Clojure +

That there were some odd calls that I didn't understand. +' instead of just + for example. To shed alittle bit of light on it, not all though, I grabbed the code from the wrong function. In the source it's declared twice. Look at the following:

(defn +'
  "Returns the sum of nums. (+) returns 0. Supports arbitrary precision.
  See also: +"
  {:inline (nary-inline 'addP)
   :inline-arities >1?
   :added "1.0"}
  ([] 0)
  ([x] (cast Number x))
  ([x y] (. clojure.lang.Numbers (addP x y)))
  ([x y & more]
   (reduce1 +' (+' x y) more)))

(defn +
  "Returns the sum of nums. (+) returns 0. Does not auto-promote
  longs, will throw on overflow. See also: +'"
  {:inline (nary-inline 'add 'unchecked_add)
   :inline-arities >1?
   :added "1.2"}
  ([] 0)
  ([x] (cast Number x))
  ([x y] (. clojure.lang.Numbers (add x y)))
  ([x y & more]
     (reduce1 + (+ x y) more)))

So in my examples and exploring, I was digging around for addP and +' and in that case should have been. The actual function + calls "add" and so on. I still don't know what +' is doing yet, but I bet it has something to do with "Supports arbitrary precision." That's another good google search and/or ask a Clojure guru.

The syntaxhighlighter is going crazy! I'm definitely going to need to update that.

Source-Learning-Clojure: Day 1

For the first post in my learning Clojure by reading it, I'm going to try to keep it as simple as possible. Like I stated before, I'm going to assume you can read the most basic syntax of the language. I also dug up the syntax to start using the syntax highlighter I used to use. Hopefully my code examples won't be as painful now, I'll update the highlighter to use actual clojure highlighting soon.

Clojure: +

Returns the sum of nums. (+) returns 0. Does not auto-promote longs, will throw on overflow. See also: +'

https://github.com/clojure/clojure/blob/1.3.x/src/clj/clojure/core.clj#L919

(defn +
  "Returns the sum of nums. (+) returns 0. Does not auto-promote
  longs, will throw on overflow. See also: +'"
  {:inline (nary-inline 'add 'unchecked_add)
   :inline-arities >1?
   :added "1.2"}
  ([] 0)
  ([x] (cast Number x))
  ([x y] (. clojure.lang.Numbers (add x y)))
  ([x y & more]
     (reduce1 + (+ x y) more)))

To get the super basics out of the way, we'll look at the description and meta-data real quick and only this one time. Well, unless something weird comes up in one of them along the way.

Description

  "Returns the sum of nums. (+) returns 0. Does not auto-promote
  longs, will throw on overflow. See also: +'"

This information comes up in the documentation and such.

Metadata

  {:inline (nary-inline 'add 'unchecked_add)
   :inline-arities >1?
   :added "1.2"}

This is more information that gets pulled up when using the docs in lein repl and such.

Digging In

Ok, with the noise out of the way one of the first things that jump out at me is that the + function is doing more than one thing. It looks like there's overloading available to us.

  ([] 0)
  ([x] (cast Number x))
  ([x y] (. clojure.lang.Numbers (add x y)))
  ([x y & more]
     (reduce1 + (+ x y) more)))

So I loaded up leiningen (lein repl) and tried out some super simple overloading.

  (defn rawr 
    ([] (println "rawr"))
    ([message] (println (format "%s. rawr!" message)))
  )

And what do you know what...

user=> (rawr)
rawr
nil

user=> (rawr "Whoa")
Whoa. rawr!
nil

...there's Overloading!

This example also tells me that I should remember that these functions always return something, so I should stop using println for testing purposes and just return what I want displayed.

Moving Along

  ([] 0)

Here we see the first overload of the function. It's parameters is an empty vector (or array coming from other languages) []. I found out earlier that is how you create a function that doesn't require any parameters. So if you call it like: (+), it will return the value of that first overload. Looking at the value returned for this, we can safely say that the default value returned from + is 0. So, I'm going to assume at this moment that 0 is the default int value.

Moving Along

  ([x] (cast Number x))

Here we are looking at the overload for passing in a single value. It's taking in that value and casting it to a number. So what happens if we don't pass in a number?

user=> (+ a)
java.lang.Exception: Unable to resolve symbol: a in this context (NO_SOURCE_FILE:1)

There was a good expectation, it throws an exception. So, what is Number? I don't recall seeing caps-first-letter in any of the clojure examples so far. So my guess is that it's hitting java with that?

user=> Number
java.lang.Number
user=> FakeyFake
java.lang.Exception: Unable to resolve symbol: FakeyFake in this context (NO_SOURCE_FILE:0)

Yup, it's a java class.

Moving Along

  ([x y] (. clojure.lang.Numbers (addP x y)))

Ok, so there's a couple of things in here I don't know. What's addP? clojure.lang.Numbers? (. ? So lots of questions for this one.

user=> addP
java.lang.Exception: Unable to resolve symbol: addP in this context (NO_SOURCE_FILE:0)

user=> (addP 1 2)
java.lang.Exception: Unable to resolve symbol: addP in this context (NO_SOURCE_FILE:22)

user=> (addP 1 2)
java.lang.Exception: Unable to resolve symbol: addP in this context (NO_SOURCE_FILE:28)

user=> (.addP 1 2)        
java.lang.IllegalArgumentException: No matching method found: addP for class java.lang.Integer (NO_SOURCE_FILE:0)

Yup, definitely don't know what's going on here. And I definitely don't know how to call java code yet, another thing to look up when I get a moment. So I do some google searching for clojure addP and find this info about addP in clojure. So, seeing that we have access to addP in clojure.lang.Numbers.

user=> (clojure.lang.Numbers/addP 1 2)
java.lang.IllegalArgumentException: No matching method: addP (NO_SOURCE_FILE:52)

Tried some other ways, and those didn't pan out. That syntax looked like what I was seeing elsewhere on the web so that's the one I included.

If I remember correctly, the (. is a call to java. So I try this stuff:

user=> (. clojure.lang.Numbers)
java.lang.IllegalArgumentException: Malformed member expression, expecting (. target member ...) (NO_SOURCE_FILE:8)

user=> (. clojure.lang.Numbers 1)
java.lang.IllegalArgumentException: Malformed member expression (NO_SOURCE_FILE:9)

user=> (. java.lang.Numbers)     
java.lang.IllegalArgumentException: Malformed member expression, expecting (. target member ...) (NO_SOURCE_FILE:10)

user=> (. java.lang.Numbers 1)
java.lang.ClassNotFoundException: java.lang.Numbers (NO_SOURCE_FILE:11)

user=> (. java.lang.Numbers (+ 1 1))
java.lang.ClassNotFoundException: java.lang.Numbers (NO_SOURCE_FILE:12)

user=> (. java.util.Date)
java.lang.IllegalArgumentException: Malformed member expression, expecting (. target member ...) (NO_SOURCE_FILE:18)

So, I start asking around and get these:

user=> (java.util.Date.)                            
#

user=> (. (java.util.Date.) getTime)                
1347486819531

The "." is calling a method on a java object when it's "(." and it's creating a new java object when it's after the java object "Date.", That makes sense enough to move forward.

  ([x y] (. clojure.lang.Numbers (addP x y)))

If I'm saying this right: Call the method addP on the underlaying clojure/java Numbers, code passing in X & Y, and return that result. If that's correct, I'm going to assume based on it's naming, and the naming/code of the underlaying java code that addP adds two values together.

Moving Along

And finally the last overload of the + function:

  ([x y & more]
    (reduce1 +' (+' x y) more)))

One of the big things that jump out here is that it's calling itself as part of this function overload to perform its tasks. It's calling (+ x y) and it's passing itself "+" into it's reduce function. This seems like pretty standard stuff, but figured it would be worth noting that it's a functional language and that my guess would be you can't call an overload in one that precedes it.

user=> (defn fn-order
  ([] "first")
  ([message] (format "%s and then second" (fn-order)))
)
#'user/fn-order

user=> (fn-order)
"first"

user=> (fn-order "woot")
"first and then second"
user=> (defn fn-order                                      
  ([message] (format "%s and then second" (fn-order)))
  ([] "first")                                        
)           
#'user/fn-order

user=> (fn-order)                                          
"first"

user=> (fn-order "woot")                                   
"first and then second"

The first one fired off as I would have expected it to, however I was surprised to find that declaring them in the other order, everything worked! That's definitely something I'll need to ask one of our Clojure/Functional gurus.

After that, the "& more" jumped out. It's a way to call arguments/parameters optionally. The "&" can take any number of params and assigns them to, in this case "more". Later when you call the optional arg, it has all of the values after the required ones assigned to it. So if you were to call this function with say: 1 2 3 4, then the "more" would be (3 4).

user=> (defn test-optional-args                              
  [x y & more]                                          
  more
)
#'user/test-optional-args

user=> (test-optional-args 1 2 3 4 5 6 7 8 9 10)             
(3 4 5 6 7 8 9 10)

One part of the source that's kind of throwing me off is things like "reduce1". Calling that from repl results in errors, but its in the source. Hopefully that'll make sense the further I get into this. Aside from that, using "reduce" in repl instead sheds some light into what it's doing. for reduce you use as such: (reduce f coll). So, you call reduce, passing in the function you want to apply to the values in the collection and then the collection. It will then go from the first value and apply the function to the second value. Then continue that process over and over until it runs through the collection. Lets look at it in actual code.

user=> (reduce + [1 2])
3

user=> (reduce - [1 2])
-1

user=> (reduce * [1 2])
2

"reduce" also has an overload: (reduce f val coll). Where the f is the funciton and coll is collection, val is a value to add to apply before beginning the walk through of the collection. In our "+" functions case: (+ x y). So, for this overload we are adding X & Y, and then adding all of the other values passed into the optional args.

Another thing that doesn't work for me is the "+'" calls in the source. I'll show you an example. I'm beginning to think I've missed something somewhere. The only difference is not including the ', then in repl all is good.

user=(defn test+ ([x y & more] (reduce +' (+' x y) more)))  
#'user/test+

user=> (test+ 1 2 3 4)                                      
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to java.lang.Number (NO_SOURCE_FILE:0)

user=> (defn test+ ([x y & more] (reduce + (+ x y) more)))  
#'user/test+

user=> (test+ 1 2 3 4)                                    
10

Experiment

When I wrote the "test+" function to work through reduce, I realized that, even though I was reading the source code that showed the example, that + was declared in the code as the function name. Looks like there aren't any and/or few restricted values that names can be. So I wanted to test this out a little:

user=> (defn TK-421 [] "Why aren't you at your post?")
#'user/TK-421

user=> (TK-421)                                       
"Why aren't you at your post?"

Ha, now that's a function! But what happens if I override a function that already exists? Say the + function:

user=> (defn + [] "rawr")
WARNING: + already refers to: #'clojure.core/+ in namespace: user, being replaced by: #'user/+
#'user/+

user=> (+)
"rawr"

user=> (+ 1)
java.lang.IllegalArgumentException: Wrong number of args (1) passed to: user$-PLUS- (NO_SOURCE_FILE:0)

user=> (+ 1 2)
java.lang.IllegalArgumentException: Wrong number of args (2) passed to: user$-PLUS- (NO_SOURCE_FILE:0)

So, we overrode the + function, which overwrote all of its overloads. Or better said: Our awesome override, overrode, the old overloads...

Summary

Day 1 in the source and I've learned that we have; Overloading in Clojure, Overloading can call its other overload methods even if they were declared afterwards, Reinforced that functions always return, reinforced that we can create parameterless & optional parameter functions, that "." is (so far) used to call the underlaying java code, Reduce takes a function and a collection and then applies the function to all of the values in the collection, that the source is written slightly differently than the repl expects Clojure to be written, that you can override the already existing functions, and that I'm going to assume for now that naming has little to no restrictions.

Learning Clojure: needing a different approach.

I'm having issues with learning Clojure. I'm picking up bits and parts, but the more I read online and in the books the more I find stuff that isn't sinking in. On top of that the tabs in my browser exploded with blog posts, articles, examples, and so on. It's time to try learning clojure a different way; by digging through the source.

I'm going to start off as small as possible, and see where it leads. I'll post as much as I can about it in the hopes of sounding like I don't know what I'm talking about and someone out there correcting me. I'll need to make the assumption that one can read the basic Clojure syntax, but not much beyond that.

I'm going to use these as my resources, unless I find or am given something better.

http://clojure.org/cheatsheet

http://clojuredocs.org/clojure_core

https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj

If you're interested in the future posts about this, I'll tag them all with source-learning-clojure.

Tuesday, September 11, 2012

Clojure Start

Started in Clojure a couple of nights ago, getting familiar with the language, syntax and functional programming in general. This one is definitely going to test me. I've read through a few online resources and made decent head way on a few of the Clojure books, however something in the language seems to be evading me. I haven't spent this much time in a language and still had, what seems to be pretty standard stuff for the language, be un-readable to me.

Shared learning

So I started bugging the others at work as they had just gone through what I'm starting into. I'm glad they going through the same things, they were able to get me past a few of my current hang-ups.

I'm also going to pair-program in Clojure with a fellow apprentice (Adam) in the mornings. It'll help me with Clojure, and both of us with pairing.

Repo

https://github.com/joeyshipley/game-clojure-simple-rpg

We're going to pair and write a really simple rpg. The focus is to get a better understanding of how to test and what can be tested in Clojure.

Thursday, August 16, 2012

CSS3 Transforms : Update

Here is a quick update to the CSS3 Transforms that I was poking at.

CSS3 Transforms »

Before I was rotating a plane on the XYZ in CSS3 and really not liking the end result, the perspective was a bit off. Looking online and applying the perspective declarations weren't doing anything for the plane either.

Turns out I was applying the perspective to the wrong html element. You need to apply it to the container of the plane, not the plane itself.

New

Previous

Wednesday, August 15, 2012

CSS3 Transforms

I spent a little bit of time in CSS3's transforms today. It was tricky enough to get an angle just the way I wanted it, that I ended up making a 2D transform tester page. It was good to dig into it a little deeper than I was expecting to, as it highlighted what I didn't like about it.

CSS3 Transform repository »

When rotating with the Y axis along with either of the other two, it projects the plane in an orthographic view or a just wrong view. Not entirely sure yet, but the perspective of the plane feels reversed. I would have liked it better if it had just not applied any perspective.

When I come back to this, I'm going to experiment with the rotate3d or matrix transforms. They are trickier, but I'm thinking they are actually what I wanted to use in the first place.

Tuesday, August 14, 2012

Break it down!

As we have found out as we have been going over the principles, they tie into each other, solving each others issues. As we go over this one, you'll see that we've already started using it in our other examples and that it directly ties into the Single-Responsibility Principle. And now for the final principle from the SOLID principles: The Interface-Segregation Principle.

ISP states that:

    "Clients should not be forced to depend on methods that they do not use."

The 411

What ISP is telling us to watch for, is to keep our interfaces from becoming bloated, from taking on more than one responsibility, and to keep them cohesive. That any part of your system that utilizes the interface should need all that it offers, or you are offering to much. Interfaces that pass around methods that aren't needed, couple those areas of the code to the interface. When an area of the code causes the interface to change, where else would the change spread?

So what do we do to conform to ISP? We break up the interface into smaller cohesive interfaces.

    interface IShopKeeper
    {
        ShowStock();
        Buy(Item item);
        Sell(Item item);
        Talk();
        GiveQuest();
        CompleteQuest();
        Repair(Item item);
        CraftItem(Recipe recipe);
        ...
    }

Big interface, lots of reasons it could change, decent amount of places that could be coupled together unnecessarily. Lets segregate the interface to its logical cohesive areas.

    interface IVendor
    {
        ShowStock();
        Buy(Item item);
        Sell(Item item);
    }

    interface IStoryProvider
    {
        Talk();
        GiveQuest();
        CompleteQuest();
    }

    interface ICraftsman
    {
        Repair(Item item);
        CraftItem(Recipe recipe);
    }

    class ShopKeeper : IVendor, IStoryProvider, ICraftsman
    {
        ...
    }

Now the interface has been broken up, the individual parts can be added separately to different characters, and the different parts of the system only know and deal with the interfaces they should be dealing with.

SOLID

These issues are directly tied to the other issues we encountered when looking at the other SOLID principles. Let's look some of our previous code that put together in these examples:

Single-Responsibility

    interface ICharacter
    {
        Attack();
        Defend();
        EquipItem(Guid itemId, string location);
        GainExperience(int xpValue);
        ...

became:

    interface ICombatActions
    {
        Attack();
        Defend();
    }

    interface IEquipmentManagement
    {
        EquipItem(Guid itemId, string location);
    }

    interface ILevelCapable
    {
        GainExperience(int xpValue);
    }

Liskov Substitution

    interface IHero
    {
        Attack(Monster target);
        Defend();
        Move();
    }

became:

    interface ICanAttack
    {
        Attack(Monster target);
    }

    class Knight : ICanAttack, ICanDefend, ICanMove
    { ... }

    class Wizard : ICanAttack, ICanDefend, ICanMove
    { ... }

    class Merchant : ICanDefend, ICanMove
    { ... }

Monday, August 13, 2012

I Can Haz Dependencz!

Lately we've been looking at the SOLID principles, taking a little bit of time to see what they are and how they can help us build flexible systems. This time we're going to look at The Dependency-Inversion Principle.

DIP states:

    "A. High-level modules should not depend on low-level modules. Both should depend on abstractions."
    "B. Abstractions should not depend on details. Details should depend on abstractions."

Um... what?

The core idea we are looking at here is that as much as possible, the system you are building should be dealing with abstractions instead of implementations. And that when a portion of your code needs something to perform its tasks, it asks for it instead of having the knowledge to get it itself.

Its polite to ask

So, why should our code ask for the things it needs? Its fairly straight forward really, by not asking for what it needs our code becomes coupled to its dependencies. Once you start coupling your code it loses its ability to be flexible or re-useable without going back in and doing serious changes. DIP is here to help you be able to change out any layer of your design for a different implementation of that layer.

Lets take a look at this:

    class Knight : ICanCarryStuff, ICanLootThings
    {
        init()
        {
            // create backpack
        }

        Equip(IEquipableItem item, IEquipLocation location)
        {
            // place existing item in location back into backpack
            // get item from backpack
            // equip item to location
        }

        Pickup(ICanBeCarried item)
        {
            // if enough room in backpack
                // put item in backpack
        }
        ...
    }

There's a lot more we could declare there, but this gives us a good idea of one of our heroes dependencies; the backpack. This being a simple game, we had just created the backpack when the hero was initialized and all was good. That is, until just about anything meaningful with the backpack changed. Now we have to change our hero code.

That sounds like we're breaking some other principles too. What happens when we implement the Merchant hero like we had previously talked about, would they have a backpack to start with or would hey have their cart? What if we gave away special promotion codes that all a new character got a bling-plated backpack when they upgraded their game to the deluxe edition.

Now what?

Ok, so we have the issue of our hero currently being tied to the backpack. Let's fix it:

    class Knight : ICanCarryStuff, ICanLootThings
    {
        init(IItemContainer container)
        {
            _container = container
        }

We've inverted the control. Now anywhere we want to create our hero, we are going to have to give us the pass in the dependency, no matter what implementation we want at the time.

What should we pass in?

Now lets look at another part of our code. We had some bad code sitting around in our last examples. Here we are already passing in a dependency, the 'Monster', to our attack code.

    interface ICanAttack
    {
        Attack(Monster target)
    }

    class Knight : ICanAttack, ICanDefend, ICanMove
    {
        Attack(Monster target)
        {
            // hack & slash on the monster!
        }
        ...
    }

So here we are conforming to part of the Dependency-Inversion Principle by passing into Attack the instance of what we want to actually attack. However we are also creating part of the problem that this principle helps us with; we aren't depending on abstractions. Just like the example we used in Liskov Substitution, the first time or any time afterwards, that we want to be able to attack something that isn't a monster we are going to break the Open-Closed principle and have to modify our system instead of extending it.

See what we did there, we just looked at a problem from the context of many of the principles. A quick side track; these principles work together to build a flexible system. The more you come to understand them and use them, the more they help each other with the issues they are tackling individually.

IGetAttacked

Back to the example at hand; here we can fix the attack method to ask for an IGetAttacked instead of a Monster, and then life goes back to being good. We can now extend our system by making anything we want to be attacked to implement the IGetAttacked. Now we can implement our heroes going bad and attacking our innocent shop keepers, or worse... other players.

    class Knight : ICanAttack, IGetAttacked, ICanDefend ...
    {
        Attack(IGetAttacked target)
        {
            // hack & slash whatever I want to!
        }
    }

Friday, August 10, 2012

You want that, to do what?

Last we looked at The Open-Closed Principle and learned how to build our code, open for extension while keeping them closed from modification. There we put together an interface for your hero:

    interface IHero
    {
        Attack(Monster target);
        Defend();
        Move();
    }

And then to build out our game from just having a knight, to having both a knight and a wizard:

    class Knight : IHero
    {
        // knightly stuff
    }

    class Wizard : IHero
    {
        // wizardly stuff
    }

So we have our new hero and through out the system we utilize what they can do like so:

    class Battle
    {
        Collection _heroes;
        Collection _monsters;

        Setup()
        {
            ShowHeroes();
            ShowMonsters();
        }
       
        PerformTurn()
        {
            _heroes.ForEach(hero => 
            {
                askForActionFrom(hero, possibleMonsterTargets);
            }
            
            _attackActions.ForEach((hero, monster) => 
            {
                hero.Attack(monster);
            }

            _defendActions.ForEach(hero =>
            {
                ...
            }
            ...
        }
    ...
    }

Something like that, should suffice to get us started with an actual battle, pitting our heroes of legend against the vile monsters from lore. Well we get that built out, release it to the public and they love it! Then the requests come in again, "Man, Knights are awesomer than Wizards for sure! But now I want to play a merchant!"

The Request

Simple enough, we already updated our system to handle unlimited hero types. The problem though, my doctor told me I had to take a break and couldn't look at code for a couple of days. Fearing the wrath of my community, I ask a buddy who's really into merchants and such to build out the system while I'm away. So what's he put in?

    class Merchant : IHero
    {
        Attack()
        {
            // throw exception("You couldn't pay me to lift a finger!")
        }
 
        Defend()
        {
            // throw coins at the problem
        }

        Move()
        {
            // horse & cart, need to carry my goods!
        }
    }

He then sends me an email detailing his knowledge of merchants in the fantasy dark ages era and their impact on the culture of the knight/merchant/pesant caste. Further stating how he got the story nailed down for me. So following my doctors orders of not looking at code, and my trust in him knowing what a merchant would do back then, I tell him to ship it.

And then...

My email box starts blowing up from my error notifier...

Turns out, everyone who is playing merchants gets a crappy game crash every time they try to attack something. I guess my buddy is the only one who thinks a merchant hero shouldn't be able to beat on monsters.

I call my buddy frantically, "Hey, I can't touch code, fix it!". He's like, "I got this." Still defending his position on, "Merchants couldn't be bothered to attack things", guess what we end up with...

    class Battle
    {
        ...
       
        PerformTurn()
        {
            ...
            _attackActions.ForEach((hero, monster) => 
            {
                if(hero != typeof(Merchant))
                    hero.Attack(monster);
            }

The code gets shipped and the error emails disappear. All is well in life.... Only now, we have to track every type of hero in these methods. As I was tired of the fans sending me emails begging for new heroes to play, the next release is to have 26 new hero types coming. How many of those wouldn't be doing 'Attack', or for that matter one of the other actions available. Our code is going to quickly get out of hand.

So, what now?

Ladies and Gentlemen; The Liskov Substitution Principle!

The principle states:

    "Subtypes must be substitutable for their base types."

The core idea here is that whether it be through inheritance, working with contracts or whatever, that your classes need to implement them in their entirety. By saying that we have a new hero type that can't do everything a hero can do, or does something outside of what it was intending, that it will lead to problems. After all, our system knows about IHero, and this Merchant isn't a complete hero unless he can actually attack.

What do we do?

Let's humor my buddy, and not force merchants to attack. Also, lets fix the issue at hand without creating crazy code in our battle class to handle the numerous hero types that can come in. We're going to change our idea of what a hero is, and break up the IHero interface into smaller behavior contracts. Just for sake of this post, we'll ignore the other parts of IHero, just working with the Attack action, we'll visit the others again in a different principle later.

    interface ICanAttack
    {
        Attack(Monster target);
    }

    class Knight : ICanAttack, ICanDefend, ICanMove
    { ... }

    class Wizard : ICanAttack, ICanDefend, ICanMove
    { ... }

    class Merchant : ICanDefend, ICanMove
    { ... }

See what we did there? The Merchant really can't attack now. So next up, we tackle the battle class to handle the new hero representation:

    class Battle
    {
        _allHeroes;

        _heroesWithAttacks;
        _heroesWithDefense;
        _heroesWithMoves;

        PerformTurn()
        {
            _allHeroes.ForEach(hero => 
            {
                askForActionFrom(hero, possibleMonsterTargets);
            }

            _attackActions.ForEach((hero, monster) => 
            {
                if(!_heroesWithAttacks.contains(hero))
                    continue; // skip this hero

                hero.Attack(monster);
            }

        ...        
    }

Ok, so the battle class still isn't all that great, but its no longer sucky from breaking the Liskov Substitution Principle. You can go back to creating any number of hero types and only include the types of actions you want the system to allow them to do. Next time we come back to these principles, we'll look at the one that gives us more insight on what we did with breaking the IHero up into ICanAttack, ICanDefend, ICanMove.

Wednesday, August 8, 2012

We don't live in a barn!

Next principle up; The Open-Closed Principle. Like my grandmother used to say; Open for extension, but closed for modification! Wait... she didn't say that, I think it was more like close that door, you don't live in a barn. But it was close enough. We liked to keep the doors open so we could extend where we played, and she liked it closed so we would be outside and not modifying her clean house into a messy one. Yah, I know, I'm being not funny.

So OCP actually states:

    "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."

What?!

Well "wtf?!", was probably more like my initial response to this one. And some time after that also. How do you implement something if you aren't allowed to modify your code? Well, the answer is to extend your code base for the new behavior. One of the keys here, is to take it as a rule that you can't modify your code. In fact you sometimes have to; a bug, a change in the understanding of existing behaviors, and such would cause modifications. What this principle is helping out with, is when you want to grow your system, ideally you don't want to change your existing code to accomplish it.

Let's open-close that door

So how do you implement new behavior in your system through extension? Primarily through abstraction. Lets look at an example:

Say we have a knight in shining armor riding their magnificent horse (horsey), as our games main character.

    class Hero
    {
        void Attack(Monster target)
        {
            // hack & slash
        }

        void Defend()
        {
            // shield block
        }

        void Move()
        {
            // horsey charge
        }
    }

The hero hacks & slashes the mosters, deflects anything with his shield, and rides horsey around. All is good. Until those player polls come back and all of a sudden people want to play some kind of silly stick waving wizard. Great, now we need to go hack up the hero class. Attack now needs to know to Hack & Slash for the uber-cool knight, and wave some twinkling wand around for the lame wizard.

Ugh, different heros do different things...

    class Hero
    {
        void Attack(Monster target)
        {
            // knights go hack & slash
            // wizards go pew-pew
        }

Right, so we're modifying our code base to account for new behaviors/features. But why is that bad? Because you know, before it's over you'll have code in there for; Knights, Wizards, Rogues, Clerics, Rangers, Blacksmiths, Barbarians, Druids, Fighters, Monks, Sorcerers, Paladins, Assassins, Merchants, and... oh yah, Bards.

So, lest pull the idea of a hero out into an abstraction and let the logic of the individual type of hero be defined in its implementations:

    interface IHero
    {
        void Attack(Monster target);
        void Defend();
        void Move();
    }

So now you've created your contract of what a hero is, and you use this through out your system. Once you have your system setup to use IHero you can now create any number of hero types by only creating new implementations. You aren't modifying any existing Knight code when building out the Wizard. It's open to extension, but closed to modification.

That's how cool knights are.

And then there were two

    class Knight : IHero
    {
        void Attack(Monster target)
        {
            // hack & slash
        }

        void Defend()
        {
            // shield block
        }

        void Move()
        {
            // horsey charge
        }
    }

    class Wizard : IHero
    {
        void Attack(Monster target)
        {
            // twinkly wand waving
        }

        void Defend()
        {
            // roll over and play dead
        }

        void Move()
        {
            // teleport
        }
    }

But wait, there's more!

Yesterday I spoke of The Single-Responsibility Principle, putting it out there my understanding of what it is and some possible ways to utilize it. It turns out that some of the others had done the same, I guess it was SRP blog night last night for some at 8th Light. :)

They aren't kidding when they say that it's one of the easiest principles to learn and one of the hardest to get right. One of the core ideas I've been getting wrong is that you method or class can actually have more than one responsibility and still protect itself from the issues that SRP solves. The key here is cohesion of your code. The idea that if your responsibilities have strong cohesion, that they would change together, and the actual responsibility becomes what those responsibilities represent.

Another interesting aspect of the SRP principle is the number of times I've read it. How I've come to understand it. And with a some dialog with the others, some learning it, others explaining it; how I have changed my view of it, and can see an area to focus my practices on to gain even better understanding.

Tuesday, August 7, 2012

One Reason to Change

The current book in the reading assignments is, Agile Software Development: Principles, Patterns, and Practices; by Robert C. Martin. Although I will end up doing a general book review post for this when I'm done, I feel the content of the book is important enough for me to post about it as I go.

So, this post is about, The Single-Responsibility Principle (SRP).

What is this Single-Responsibility thingy?

"A class should have only one reason to change."

The idea behind SRP is that your classes should only be responsible for one aspect of the design, so that when you have to change the code, you are not forced to go back into a file for more than one reason. 

Say you are passing this around your system:

    interface ICharacter
    {
        Attack();
        Defend();
        EquipItem(Guid itemId, string location);
        GainExperience(int xpValue);
        ...

So this is only part of what it would take to have some character code, we could add a bunch to the idea, but its enough to get the idea. Off the bat, passing this around, you can see that anyone with an ICharacter can call anything on it, even if it has no business doing so. But using those examples there, you can pretty easily see 3 basic reasons it could change; combat actions (attack & defend), managing equipment (equip item) and leveling up (gain experience). As it stands not only would the system itself be vulnerable to changing for a variety of reasons anywhere ICharacter was passed, but ICharacter itself would probably change during any meaningful change to the system.

Say you wanted to change how attacks happen, or gaining experience shouldn't be based on a actual value but rather some kind of monster difficulty, or you want to be able to equip an item that takes up more than one location. All of these separate reasons to change lead you back to the single place of ICharacter.

And that matters why?

The generic reason here is that, like the other principles, you do this to help decouple the parts of your code from each other. So you can build out new functionality or change existing parts and have as little places as possible to touch. The less places you need to touch the less places you need to investigate to understand what is going on in your system. And of course, the less chances of causing side effects.

Another aspect to think about is the dependencies of each of these responsibilities. When a class has more than one responsibility you also need the dependencies for each. So if you have a dependency of a IEquipmentContainer for your EquipItem call, anywhere where you want to call Attack would also need it, as the system only knows about ICharacter.

So what could it look like after SRP?

For our fake class, I would go in this direction to utilize SRP:

    interface ICombatActions
    {
        Attack();
        Defend();
    }

    interface IEquipmentManagement
    {
        EquipItem(Guid itemId, string location);
    }

    interface ILevelCapable
    {
        GainExperience(int xpValue);
    }

Depending on what it means to attack & defend, you could further break those up. However its enough for SRP to just assume right now that they are super simple and just opposites of each other. At any rate, now that they have been split up by their responsibilities you pass the individual parts around your system and decouple the rest.

    interface ICombatActions
    {
        Attack(Monster target);
        Defend();
    }

Now if they come back to you to tell you there can be more than one bad guy you are fighting at a time, you only need to change Attack to take in a target. And per the dependencies issue, if you need a backback to equip an item from, the parts of the system that do the attack/defend combat calls don't care.

Wednesday, August 1, 2012

Test-Driven Development: By Example

One of the books in the 8th Light apprenticeship book series is, Test-Driven Development By Example, by Kent Beck. The book takes a deep look at testing, what it means to not only write tests first, but to continuously drive your development from them. Beyond the ideals, examples and general share of knowledge on the subject, Kent provides some great explanations of practices one can employ to be a better TDD developer and have less stress while following the process.

What was TDD to me?

From when I started testing to where it has evolved; I looked at TDD as a way to enforce the individual parts of my design were confirmed to be working before I put them together. Once I had the design planned out, I would put into place as many tests as I could think of for the initial phase of development, and then begin to build them out until eventually I had all the tests passing and a bunch of new ones added during the process.

In the end, I would have a pretty well tested system, and a confidence as strong as the care I put into the tests.

What is TDD to me now?

Since I began talking with the various people at 8th Light, I quickly realized that I was missing a very important part of TDD, driving my development from the tests. As I got further into Kent's book, it became pretty apparent just how important this step was. With the testing mantra, Red, Green, Refactor; You create a test, write the absolute minimum amount of code that will make it pass (even if its not the right code), then refactor all of your code to clean it up and reduce duplication.

Although I had lost my fear of refactoring a little while back, it had been nothing more to me than going back days or weeks later to clean up what I was rushed through to finish. With minimal code and refactoring immediately takes development in a completely different direction, literally you will have the minimal amount of code needed to have a working system. The confidence level of your code will be at its highest as you will have tested and refactored your code thousands of times catching bugs instantly.

As I am breaking down my Test-First Development and turning it into Test-Driven Development, I find myself fighting how I think a system should look and finding the next best test to prove it. To really take a deeper look at where I'm at in the current design and what the end product needs next to become one step closer to being completed. Right now, it feels like less code is just a happy side-effect.

Test Helpers

Beyond the examples and general testing knowledge in the book, two of the chapters really stood out to me, Green Bar Patters and Refactoring. Maybe its because I have a little bit of testing background maybe those chapters really are more important. At any rate, they really provide a great deal of understanding on how to develop via TDD pretty well.

Green Bar Patterns

In the Green Bar Patterns, Kent really digs into how three very practical ways to write effective tests. First by faking the code that a test wraps you get a quick successful green test and literally the absolute code needed. If your method under test has a test that says the result needs to be '5', then have the method return '5'. Technically speaking, that's all your code needs to do. No addition, no subtraction, no calling out to other classes, just the result. Then as you write more tests or triangulate your tests the requirements change and you continue to fake as much as you can or write as little as you can to make them all pass. Eventually the design will have been created.

When you are writing your tests if you don't feel up for faking the implementation or you need to drive the design more in one step, you can triangulate your test. By creating two assertions in your test that would get the same result but not through faking it, you have created the two points needed to find the third. The third being the implementation.

In the same manner as triangulation helps to drive the development faster with less tests, another practice furthers this and is called Obvious Implementation. Which is simply, if you see a simple solution to the test you have created, go ahead and implement it. This further saves time and energy to keep going. Then as you are developing, depending on the complexity or understanding of the problem at hand, you can vary which practice you are using to help you complete it.

Refactoring

For me, refactoring has always been an important part of the process. My willingness to hop into a portion of code I haven't been in for a while and just start changing things with out fear of breaking something somewhere else came when I started understanding testing better. As such, I found that my refactoring skills developed later in the game than the others. This chapter of the book really goes through different practices of refactoring and details the whys and hows. This one is definitely one of those sections of a book that needs to be revisited from time to time, pulling in more as your understanding changes.

Friday, July 20, 2012

Old stuff dug up.

This is old, I just found it sitting in my drafts from a couple years back. I believe I was writing a tutorial on how to do this in ActionScript 3, but I'm to old to remember that far back now... :(

Anyhow, it was a world of warcraft inspired character inventory/backpack system in flash.



And the pieces:





Ruby/RSpec Callback Argument Capture

Yesterday I had been poking around trying to get a parameter passed into something I was stubbing out in Ruby & RSpec. Like I had mentioned before in .net with rhinomocks, moq or similar mocking frameworks I would do something of the sort:

var repository = Mocks.Get();
repository
  .Stub(r => r.Save(null))
  .Callback((Player entity) =>
  {
    _player = entity;
    return true;
  });

Due to terminology differences, unfamiliarity with Ruby and my shifting understanding of testing; I was having trouble figuring out how to do that. After a bit of searching and experimenting I pieced together what I needed to do as so:

board = nil
@game_runner.stub(:draw) do |arg|
  board = arg
end

And then as the design changed as I continued testing, it was no longer needed. It was good to poke around it and figure it out, funny that it didn't survive more than an hour or so in my code.

Monday, July 16, 2012

My game asset share

I was digging through some of my files the other day and I ran across my 2d game/site assets. I generally end up offering my artwork to co-workers and friends when they show an interest in it. Now that I have a good place to actually share my work, I figured it wouldn't hurt to throw the work up there also.

Keep it clean, and have fun. :)

Game Assets Share

Game Assets Share

Monday, July 9, 2012

Extreme Programming Explained: Embrace Change, by Kent Beck with Cynthia Andres

The second book in the stack 8th Light has given me, Extreme Programming Explained: Embrace Change, wasn't what I was expecting it to be. Normally when I hear about XP, it's some eccentric way those new-age developers do things. Not something a real business can afford the luxury of. So going into the book, I was expecting some crazy, wacked out things like; the Batman programming technique is practiced by spends exactly 13 minutes everyday coding... while hanging upside down.

Turns out, nothing of the sort. The book just lists a bunch of really good ideas; test-first, automated tests, continuos integration, quick feedback, caring about quality, sitting with your teammates, communication focus, and so on. You know, the stuff that is really good for a development team and the business.

One of my previous employers practiced much of what the book covers, and oddly enough hadn't told me it was XP. My last employer ran from the word, cursing it to die. However they loved the idea of the individual concepts that I tried to push on them. It's odd how so many use good terms for their buzz and never really understand them.

So, what is XP?

Besides being a refresher for me, the book really took care to explain and relate amongst itself the various aspects of XP. I've seen most of the ideas in practice here and there, utilizing many myself. They really aren't anything that would be considered out of the norm for most teams that aren't afraid to keep up with the times. But the bigger picture that I was missing is how they feed into each other, making each more effective.

Sitting together in an open room wasn't just about creating a more friendly environment, it was also about building better communication. Communication wasn't just about better understanding, it was also about building the clients trust. Planning for and working short development cycles wasn't just about getting quick feedback, it was also about getting the entire company to shift their way of thinking. Testing wasn't just about confirming bug fixes and elevating fear, it was also the stepping stone towards building what the client needs in this cycle. Automated tests weren't just for one button test runs, continuos integration wasn't just to keep us from having to clicking publish; they were to reduce our stress levels, so we could code more clearly. Which I do decree; I will take to heart any practice that purpose it is, to reduce stress.

XP: Extreme Process

Another aspect of the book that jumped out at me was the care it took to reinforce that you don't have to be a programmer to be able to utilize XP. Quickly the book begins to tie in the practices of XP to the other aspects of a company. The practices build trust with the clients, the team, the employers. While improving the process and elevate pain for the other departments, the development team and all of the individuals involved. By tying the practices so closely to the other groups of people involved, you begin to affect how they work. All of a sudden clients, managers, executives, all have their role to play to make XP really work.

Embrace Change

In the end, utilizing one of these practices, a few, or all; doesn't become the focus of what XP is about. Its the change in the mind set. The breaking apart inefficient or down right bad development practices. Its about moving yourself, your team and your environment in a better direction.

Wednesday, June 27, 2012

Software Craftsmanship: The New Imperative, by Pete McBreen

Just recently I finished my first reading assignment from the 8th Light library; Software Craftsmanship: The New Imperative, by Pete McBreen. From what I have heard about, been told of, and have seen from 8th Light; this book presents the ideals, practices and dedication to the craft that they work very hard to achieve. The underlaying ideal this book presents is the choice we will all face at one point in time, whether you write code, design or employ those who do; Is mediocrity acceptable?

The Gripe

To get it out of the way early; the aspect of the book that I found little interest in was authors dive into the world of software engineering. I understand the need to highlight the issues and problems, as there are some pretty strong mis-conceptions in the development industry having a one and only one way to do things. These sections mostly served as amusement to me, reminding me of the annoying aspects that have plagued me in one form or another in the recent past. The gripe here, is really that I wanted more chapters on craftsmanship and less on mainstream norms.

So what's with this craftsman stuff?

If you are reading this, you most like are a nerd on some level. Being a nerd, the term craftsman has already been hijacked by the multitude of games and movies out there as being some blacksmith, whom forges a shiny magical sword; in which some hero is going to find and then go impale some evil stuff with. I don't think you are that far off in thought here.

Now before you take that the wrong way, stop and look at the development industry. In my limited experience; I've seen hiring practices shift from trying to get a couple awesome developers to getting as many minimum wage interns that a building can fit. I've seen tests get ripped out of projects to speed up future development. I've seen an abundance of highly rushed code. I've seen amateur wrestlers spend hours everyday researching their moves for the next match. I've seen reporting get shut down so it doesn't incur technical debt while moving to the next project. The list goes on, and I haven't really been around the block all that much. I can only imagine what your list is like.

From what I have seen, the craftsmen who strive to better themselves above all else, is the rare magical sword waiting to be wielded. All nerdiness aside, very few of us will ever get to the point where we can tell something is just off with our profession. Sadly fewer will realize they can do something about it. A software craftsman is just a developer who puts their reputation on the line when they select a job, that care what happens to it during and after the project has completed, and they want to use every job as a stepping stone towards mastering their craft. It's oddly surprising that such a vital industry has such a low entry point and average expertise level.

The guts of it

Setting aside the look at the industry and its norms, what really struck me in this book was the aspects of craftsmanship applied too developers. A craftsman was someone that didn't just make chairs (or what ever their profession had them make), they made amazing chairs, tailored for the family that was going to use them. They put everything they had into making the furniture, knowing full well that their work was a permanent representation of their skill. It would act as their resume for anyone who ever used it. And if it was amazing work, it would be the best marketing money can buy. As professionals, why wouldn't we want that for ourselves?

Guts: The User

One of the most ignored aspects of craftsmanship in our industry, is developing systems for your user, not just against a task list. Those emails you get after you've launched your code, is the dialog you missed when you were developing it. The more you can understand what the user is actually going through, the better you can provide the services that they are paying you for; to develop a system for there use. The ultimate goal here is communication, early and abundant.

Thankfully, the agile movement has taken amazing steps in this direction. With short development cycles, you can get something infront of the user to start breaking sooner rather than later. The more they start using and affecting your development the better the communication becomes between you. These quick responses to the users troubles, build a level of trust that you won't normally see in development shops. Most of the time the users stop being the annoying part of the job and become a welcome and vital part.

Guts: Growth

Another very important aspect of craftsmanship is the want and need to achieve something greater than you already can. A craftsman is defined by their work, and the only way to produce better work, is by becoming a better developer. Years are spent learning, not days. Knowing that an idle understanding of individual areas, lowers the quality as a whole. While in the opposite direction, over specialization leaves a developer with a golden hammer, the craftsman seeks a well rounded set of expertise.

In some ways, this ideal will be the hardest for most people to accept. In our industry today, the focus is to turn out certified specialists over night and fill the hole we have of qualified developers. Although this mentality is very much the problem, almost all of the companies out there want the very thing craftsmanship contradicts, warm bodies trained in the use of language X and practice Y. Walking the path of craftsmanship not only has you seeking to better yourself, but also seeking a better environment.

Guts: Environment

Can you imagine working at a place where at any moment, without notice; you could get up from your computer to go on some nerdy magic sword searching quest... yet have no worries about who picks up your work? Knowing that whom ever sits down in your chair will finish what you started, to the same level of quality that you would expect of yourself. I know you can think of a variety of people that you've worked with, that would wouldn't trust with your work. But how many people do you know that you could trust to do the job correctly? Craftsmanship is very much about building up those around you and environment you work in.

To make sure that they can rely on and trust their workmates, craftsman seek to teach as much as they seek to learn. When cultivating a team, a craftsman carefully picks apprentices and other craftsman who strive to for the same goals in quality and care. Knowing that everyone's background and skills are different, it benefits to share as much knowledge as they can. After all, the apprentice when they are ready to do so, will one day replace the craftsman. Through this transfer of responsibilities they tie their reputation into the craftsman, and craftsman into theirs.

To be continued...

For me this book really brings forward some ideals about our industry that I have been wanting in some form or another for a very long time. In the past I've had some great mentors and some pretty cool environments, but with my particular mix of talents, most have no idea how to fit me in to their plan. With craftsmanship, it's not about a company or employer's plan, its about the plan the craftsman has. The very idea of a craftsman's diversity, that craftsmen build their environment, and the acceptance that it takes a lifetime to truly master the profession suits me just fine.

Monday, June 11, 2012

Digital Doodles

To whomever has been following my blog; I wanted to drop you a quick note and let you know about the shift in posts over the last few months. A while back I made the decision to focus more on my programming than on my art. Although I still goof around on my sketch pad and a bit in illustrator, most of my energy has been in programming.

To further the shift, I've been given the opportunity at 8th Light to really hone my software skills and push myself to the next level. A big part of the learning process will be to reflect each day, putting my thoughts to words, and onto my blog.

For a while a least, there will be quite a bit of posts about the learning process and coding. However, I'm going to make a conscious effort to post what artwork I do goof around with.

Sunday, January 22, 2012

LINQ to XML (XHTML)

The blog is going to be more code based from now on. I'll probably still post some art here and there, however, personally I'm focusing on my programming. Anyhow, here's some LINQ to XML extension methods I'm working on. I write my LINQ with lambda expressions. These are in context of querying for HTML elements, so I'm guessing their use will be limiting for most.


https://github.com/joeyshipley/LINQ-to-xml-extension-methods


var htmlElement = xdoc.Descendants()
 .FirstOrDefault(d => d.Attribute("class") != null && d.Attribute("class").Value.ToLower().Contains(searchingForClassNameVariable.ToLower()));
var htmlElementValue = htmlElement != null
 ? htmlElement.Value.Trim()
 : string.Empty;

With the extension methods, I'm now writting the above code as:

var htmlElementValue = xdoc.Descendants()
 .FirstOrDefaultByAttribute("class", searchingForClassNameVariable)
 .ElementValue();

Sorry about the formatting, I'll find my code formatting and put it back on the blog. In the somewhat near future.