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.