Archive for Pallet Town

Pallet Town: First Steps to Functional

I’ve been taking a deeper look at Functional Reactive Programming in the form of RxJavaand ReactJS. While I am still at the early stages of really looking at this and forcing myself to actually work in these technologies that I’m still no really sure make a lot of sense for my use cases (more on that at a later date), I was taken aback by the simple usefulness of the “Functional” part of the equation. At the risk of grossly oversimplifying the benefits of functional programming (or at least adopting a more functional style in your object oriented code), there is a ton to be gained with just a little bit of re-thinking of how you think about the relationships between your objects and how you structure your methods. This is because one of the main benefits of functional programming is that it minimizes state and therefore unintended side-effects. Here are the two quickest and easiest ways to improve your code today using a more functional mindset.

One Function == One Action:” Every function you write should do one thing and only one thing. Let’s take a very simple sample of what this should look like:

public Pokemon getPokemon(int id) {
	Pokemon  myPokemon = PokemonStore.getById(id);
	myPokemon.setType("fire");
	PokemonStore.save(myPokemon);
	return myPokemon
}

The Assumptions in that are that we have some PokemonStore class that is effectively an ORM for your Pokemon. That’s fine. The issue here is that our ‘getPokemon’ function doesn’t just fetch us the correct record by id as you would expect it to. Instead it updates it ‘type’ property and reserves the mutated record to the datastore before returning the record. This is obviously terrible on a number of levels but looking at it from a functional point of view, the primary sin is that it does three things (getting a record, mutating a record, and saving a record) rather than just one and what it does doesn’t match the method signature. A better version of this method would have mutating the type in another method and simply return the record:

public Pokemon getPokemon(int id) {
	Pokemon myPokemon = PokemonStore.getById(id);
	return myPokemon;
}

As you can see that’s easy to read, does one thing, and there’s little to know risk that a future developer won’t understand what the method is supposed to do.

Deterministic Outputs: A method given the same inputs should always return the same outputs. If that’s not true, then you likely have too much coupled state in your code that is causing unforeseen issues. This is a great example of what not to do:

public Pokemon getFirstPokemonInRoster() {
	List<Pokemon> roster = User.CurrentUser().getRoster();
	Pokemon starter = roster.get(0);
	return starter;
}

There’s a lot not to like in this method. For starters it relies on the start of a Users.CurrentUser() singleton, which instantly creates couple state. Another issue is that it’s not very flexible — is it really true that we will only ever care about the current user’s roster? Finally it’s not written in a way to be optimized for easy BDD / testing and violates the functional principle (or perhaps guideline) of passing in the objects / values a method needs to run into the method directly rather than pulling them from another place. Here’s a minor change that addresses all of those issues:

public Pokemon getFirstPokemonInRoster(int userId) {
	User user = UserStore.getById(userId);
	List<Pokemon> roster = user.getRoster();
	Pokemon starter = roster.get(0);
	return starter;
}

As you can see, the revised method can now the pull the roster for any arbitrary user and does not rely on a user singleton. You can easily imagine a test being written that passes in a valid user id to test the golden path for this and also another test with an invalid value for the userId paramater; incidentally, my method still doesn’t handle that case, but there are multiple ways you might do that and catching that sort of thing is really what automated testing is for ;).

I hope you’ve found this helpful! If you have any questions or comments, please sound off below or on Twitter.

Pallet Town: OO with Pokemon and Java pt2

Welcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

Ok, so we are picking up where we left off in our last post. We have a basic Pokemon class:

public Class Pokemon { 	
	public int id;	
	public String name;
	public int hp;
	public int ap;
}

We also have learned how to construct a Pokemon based on our existing class:

Pokemon pikachu = new Pokemon();

And of course how to set some properties for our new pikachu:

Pokemon pikachu = new Pokemon();
pikachu.name = "Pikachu";
pikachu.ap = 10;
pikachu.hp = 100;

That of course works, but is a little bit of a pain. Let’s take things a step further and make a more convenient constructor for our Pokemon class:

public Class Pokemon { 	
	public int id;	
	public String name;
	public int hp;
	public int ap;

	public Pokemon(int _id, String _name, int _hp, int _ap) {
		this.id = _id;
		this.name = _name;
		this.hp = _hp;
		this.ap = _ap;

		return this;
	}
}

I know that might look a little crazy but it is actually pretty simple. Basically, we are setting values for the properties of our Pokemon in the constructor itself rather than having to do so in the implementation — this is a very primitive form of encapsulation, one of the most important concepts of all of software development. So, using our new constructor, we’d create the same pikachu from before:

Pokemon pikachu = new Pokemon(14, "pikachu", 100, 10);

Doesn’t that look much cleaner?

Hope this post helps you on your journey to become a Pokemon… err coding master! Please feel free to send any feedback to me on Twitter or Google+. Also, be sure to check out my company Fingertip Tech, INC on Twitter.

 

Pallet Town: OO with Pokemon and Java

Welcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

Object oriented programming is one of the most common and widely used programming paradigms on the market today. In fact, if (like me), you code for a living, then it is likely that you have to deal with OO concepts on a daily basis; in fact, they have probably become something of a second nature to you. Still, maybe you are just dipping your feet into the wide world of Pokemon… err I meant Java… err I mean programming. Well, this post and its follow up posts are for you.

Before we begin, take a look at this fast code snippet:

public Class Pokemon { 	
	public int id;	
	public String name;
	public int hp;
	public int ap;
}

If that seems foreign to you, don’t worry, we will be going over it right now!

OK so what we have there is a simple but boring class that represents Pokemon. Bascailly, we are defining the basic attributes (or properties) of a Pokemon. Taking it from the top, all Pokemon need to have an id so we can store them in our Pokedex (which is basically a fancy database), they all have names, they all all have hp or hit points, and they all have attack points. Of coure, we are likely over simplifying what Pokemon are but we will look at that issue in future posts.

At this point we have a Pokemon class, but no actually Pokemon objects. We need to create an instance of our Pokemon class. To do this we are going to use Java’s ‘new’ operator like so:

Pokemon pikachu = new Pokemon();

Our resulting “pikachu” is a little lame… he has 0 hp, 0 ap, and his name and id are null. Let’s try that again but take it a step futher:

Pokemon pikachu = new Pokemon();
pikachu.name = "Pikachu";
pikachu.ap = 10;
pikachu.hp = 100;

That’s it you have a very basic Pikachu! Sure it can’t do much right now and is a little boring and has some data encapsulation problems, but we will address some of those issues in the next post.

Hope this post helps you on your journey to become a Pokemon… err coding master! Please feel free to send any feedback to me on Twitter or Google+. Also, be sure to check out my company Fingertip Tech, INC on Twitter.

 

Pallet Town: Intro to AFHTTPClient Part 1

Pallet TownWelcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

This week we are going to take a look at getting some simple networking done with the new hotness in iOS networking frameworks: AFNetworking. To be specific we are going to focus on one of its more important classes: AFHTTPClient Now there are is a little bit of a prerequisite here, we are going to go ahead and assume that you have already added AFNetworking to your iOS project and we are also going to assume that we are going to use ARC.

For starters, let’s take a look at how we instantiate the AFHTTPClient:

Now that we have our client, let’s say we want to make a simple RESTFul GET call; this sample builds a bit on our Pokemon themed ASP.Net MVC web app from the last installment of Pallet Town. Ideally, this call would just get all the Pokemon available on the API; this of course assumes you followed the normal MVC patterns in your routing on the API. Here’s the code:

- (void)getAllPokemon
{ 
	AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"SOME_URL_STRING"]];
	[client getPath:@"api/pokemon/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
			NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
			NSLog(@"Request Successful, response '%@'", responseStr);
		} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
				NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
	}];
}

That was fun but let’s make things a little more complicated. Let’s say you want to pull a particular Pokemon via its Id. That’s still a GET request but takes a parameter like so:

- (void)getPokemonById:(NSNumber *)pokemonId
{ 
	NSDictionary* parameters = @{@"Id" : pokemonId}
	AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"SOME_URL_STRING"]];
	[client getPath:@"api/pokemon/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
			NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
			NSLog(@"Request Successful, response '%@'", responseStr);
		} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
				NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
	}];
}

Getting Pokemon from the server is a lot of fun, but you know in the age of Minecraft, I like to  be a little more creative than just working with the set number of Pokemon that Nintendo provides. Tune in for our next installment to see how to POST my very own legendary Pokemon to the server!

Pallet Town: Intro to the Repository Pattern MVC4 pt 2

Pallet TownWelcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

This week we are carrying on with our introduction to the repository pattern in ASP.Net MVC4. We’ve done well so far if I can be allowed to say so myself, but we left one glaring issue in our application: we forgot to persist our data.

Let’s start by adding a database context to our existing Pokemon class:

namespace PokeSample.Models
{
  public class Pokemon
  {
     public int Id { get; set; }
     public String Name { get; set; }
  }

  public class PokemonContext
  {
     public DbSet PocketMonsters { get; set; }
  }

}

Now let’s actually use out PokeContext in our repository:

namespace PokeSample.Models
{
  public class PokeRepository : IPokeRepository
  {
    private PokemonContext db = new PokemonContext()
    private List pokemon = new List();
    private int nextId = 0;

    public PokeRepository()
    {
       this.pokemon = db.PocketMonsters.ToList();
    }

    public Pokemon Add(Pokemon somePokemon)
    {
        if (somePokemon == null)
        {
           throw new ArgumentNullException("somePokemon is null");
        }

        somePokemon.Id = nextId++;
        pokemon.Add(somePokemon);
        db.PocketMonsters.Add(somePokemon);
        db.SaveChanges();

        return somePokemon;
    }

    public Pokemon Get(int id)
    {
       return pokemon.Find(p =&gt; p.Id == id);
    } 
  }
}

That’s it! If you are running on localhost with Visual Studio 2012, the data will be saved to a .mdf file on your App_Data directory. If you are running on Azure and publishing with a publisher profile, then it should all be set up for you, assuming you have properly set up a Azure site with a corresponding SQL database on the Azure web portal.

Pallet Town: Intro to the Repository Pattern MVC4

Pallet TownWelcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

I’ve been having a great time with Windows Azure  or more specifically ASP.Net MVC4. .Net developers will be familiar with the repository pattern, since it is a common pattern used in that community. Let’s take a look at a simple repository example using everyone’s favorite objects: Pokemon. To start we need a simple Pokemon class.

namespace PokeSample.Models
{
  public class Pokemon
  {
     public int Id { get; set; }
     public String Name { get; set; }
  }
}

We now need to create an interface:

namespace PokeSample.Models
{
  interface IPokeRepository
  {
    Pokemon Add(Pokemon pokemon);
    Pokemon Get(int id);
  }
}

And now it’s time for the repository itself:

namespace PokeSample.Models
{
  public class PokeRepository : IPokeRepository
  {
    private List pokemon = new List();
    private int nextId = 0;

    public PokeRepository()
    {
       // adding some test data
       Add(new Pokemon { Name = "Charmander"});
    }

    public Pokemon Add(Pokemon somePokemon)
    {
        if (somePokemon == null)
        {
           throw new ArgumentNullException("somePokemon is null");
        }

        somePokemon.Id = nextId++;
        pokemon.Add(somePokemon);

        return somePokemon;
    }

    public Pokemon Get(int id)
    {
       return pokemon.Find(p =&gt; p.Id == id);
    } 
  }
}

You’ll notice that we are seeding the ‘pokemon’ List and have creates some simple CRUD methods. The idea here is that you could call these methods in response to HTTP requests from the PokemonController. Assuming you’ve setup your dev environment correctly this should all work just fine on localhost.

However, there is one pretty obvious glaring issue with this implementation — the data is not persisted. Stay tuned for the part 2 of this series that will show how you can use the common DBContext (ok that’s my term but it’s catchy) pattern to persist your data using MSSQL or some other datastore.

Hope you enjoyed this first entry in Pallet Town and I would appreciate any feedback you might have to offer. Please feel free to contact me on Twitter or Google+.