Thursday, April 11, 2013

Extending Dobjanschi - An Attempt at an Android REST Client Pattern


I've been working on several mobile apps, most of them needing some way to communicate with services of the REST variety. This is an incredibly useful talk from Google I/O 2010 by Virgil Dobjanschi - if you make RESTful clients and haven't seen it, I recommend you find an hour to watch it and then find considerably longer to digest it.

Google I/O 2010 video and presentation materials here.

The pattern that really jumped at me was B: the idea of sending everything through the Content Provider. So I started making a 'simple' POC that quickly grew out of control. Without going into the development details TOO much at this point, I was stuck on two points:

  • I didn't like the idea that my CRUD calls to the Content Provider were either hitting a service, or hitting a local database. I wanted to distinguish them.
  • When Dobjanschi made his talk, Loaders didn't exist yet.

In the end, I created a pattern that was something of an amalgam of A and B: I've attempted to draw it here.

To explain in words:

  • Your activity/fragment inits a Cursor Loader and assigns something (probably itself) as a callback.
  • Your activity/fragment creates an adapter - probably ideally something that extends CursorAdapter - and assigns it to your listviews, etc.
  • Any time your activity/fragment needs to DO something (even w/o user interaction, like making a refresh request on load) it calls into your Content Manager.
  • Content Manager crafts your intent and fires it off to your Service Helper.
  • Service Helper, a singleton, tracks existing calls. If your call is a 'new' one not already running, it fires it off to the Service - which uses Intent Filters.
  • The Service (which maybe or maybe not has a queue of requests and processes them one at a time) makes your REST params, spins up a new thread, and passes them to the REST Method.
  • The REST Method handles the HTTP request/response calls, and sends the raw data to the Processor.
  • The Processor munges response data into some Content Provider-centric logic (either DTOs, or if you prefer straight to ContentValues) and makes the CRUD calls into the CP to make your database reflect the results.
  • After finishing, the Processor notifies the Content Resolver of new data. This can also be done pre- or post- HTTP request/response, if you want to show the loading process to the user. (In which case, the REST Method will need to call the Processor during each step.)
  • Because you already registered your UI components, the rest is 'magic': your adapter will find the new data and refresh the UI automatically.
This assumes a SQLite database behind your Content Provider - I put another layer between my CP and my DB and called it "__DataSource" - my CP handles the URI routing to different DataSource methods while DataSource handles the actual heavy lifting (making queries, parsing ContentValues, etc). I've also found it handy for my DTOs to have 'fromCursor' methods on them - makes it very easy for my adapter to do something like "view.bind(Data.fromCursor(cursor));" in bindView.

Hopefully this gives some good direction on how I've gone about implementing a responsive client. I feel the pattern is good enough that it works beyond REST - any long-running async calls would likewise benefit from something like this, and it keeps you from having to constantly know WHEN to update the front end. You just bind it, and walk away: whenever the data changes, you sound off to the Content Resolver and any active pieces that care come running.

Up next (soon I hope) I'll discuss using an in-memory-only "database" for your Content Provider repo.

Happy coding!

Wednesday, October 3, 2012

Wanted: 2D artist/animator for mobile game(s)

EDIT: I've selected an artist, thanks to all the applicants!

I am looking for an artist and animator to work with me on my current project, a mobile app game for Android (and eventually iPhone). The project is basically feature complete, I have been working on it for several months now, and what is left is polishing and adding a few animations I haven't made placeholders for. The art right now is all just temp stuff that I made myself using Paint and Gimp.

The current company name is Sevomasean Productions, the same name I used when making flash games in college (and is, as such, open to change since it's a pretty terrible name). Right now I have no real web presence, as it's just me and the 10-15 hours a week I find time to contribute to the project. Once this project has real art and is closer to release, I plan to set up a site (possibly under a new name) and start hyping up the project more. I'm aiming for a holiday release, as my current projects have me done with my end around Halloween (then add testing, extra balancing, etc).

For my resume of past completed games, my Newgrounds site is http://arclite83.newgrounds.com. Please note that Newgrounds cleared out most of the images associated with my account through some cleanup they ran about a year ago, so the only pieces that still have icon art, etc, are the ones that are still linked in featured categories (a defense game, and a valentines day holiday game). The short of it is I made flash games in college for beer money. Now that I'm a professional programmer I'm applying my work skills to making a few apps in my spare time, this being the first of hopefully many.

The Game:

Run an alchemist's potion shop: fill orders, unlock upgrades, become rich and popular, and pay your wizard landlord to keep him from turning you into a frog!

Work fast to assemble customer's orders from a recipe list that starts simple and grows as more ingredients and formulas are unlocked. The simple color-based recipes are easy and intuitive, while the extra ingredients add complexity and keep the game interesting. Fill orders quickly and accurately to earn popularity, giving you more customers and better tips. As you progress, your evil wizard landlord will throw obstacles in your path, such as preventing you from restocking an ingredient or making rounds shorter, to try and ensure your failure. Earn money, restock your inventory, and buy permanent or temporary upgrades from the market that allow you to make even larger profits. Set aside rent money before it's due, or work extra hard right before the wizard shows up to collect; just make sure you have all the money when the time comes, or it's game over!

Easy mode is designed for kids or ultra-casual players, and features no rent and a small credit each round to ensure the fun never ends. Normal is a balanced game, with fair rent and a reasonable number of obstacles to make the game challenging but still relaxing. Hard mode has a much steeper rent curve, and the wizard will repeatedly harass you to try and trip you up. Once you earn enough you can purchase the deed to the potion shop, and be rid of the wizard forever! Afterwards, you can continue to play your character and see how much money you can accrue, or start again on a different difficulty setting.

Amount of work:

This is all approximate based on what I have now and my best guesses for the finished product.
6 background screens
10-12 button animations
~30 icons for inventory items, etc
app launcher icons
5-6 static section backgrounds (popup notices, money, etc)
11 cut scenes (intro and game over scenes, plus 9 short 'announcement' scenes when events happen)
player animations, 6-7 distinct actions
customer animations, 2-3 actions

Compensation:

This is a tough one for me to settle on what is fair (upfront payments vs percentage of profit, etc), and I'm open to talking about it more with the right candidate. Like I said, right now the team is just me, and I'm looking for someone interested in possibly forging a longer relationship for other game app ideas I have. This is not intended to be some big life changing money maker, though I do believe I have something that could do well if it's given enough attention to detail and polish. Also, I don't have a lot of capital for this, it's just a spare time thing right now. I'm much more open to a profit percentage than shelling out buckets upfront. If that's not something you would be comfortable with, I completely understand: people deserve to get paid for their work, and this position will likely NEVER be something you can feed yourself on solely. I certainly don't expect to. The plan is put it on Android, use whatever profits come from that to port it to Apple, and then move on to the next app. If it pays for new laptop, I'll call it a big win.

Job Requirements:

I'm really looking for someone who can draw/animate, be it by hand or computer. I'm looking for a childish, whimsical feel, like a Saturday morning cartoon, or a Disney short, or Bitey of Brackenwood, etc. This is meant to be a game for a generally younger audience, so going for a lighter feel is a big priority for me. I'm especially interested in simple animation samples if you've got them.

Please send inquiries, resumes, and work samples to <REMOVED>. Show me yours and I'll show you mine - quality work samples from interested parties will get a link to the latest beta APK file to load on their Android devices and see what you would be working on.

I look forward to hearing from you!

Friday, September 14, 2012

Clarity over Cleverness: Follow Up, and a Practical Example


I had a nice discussion with a coworker about my last post, and wanted to add some clarity: specifically, the topic was about a piece of unit test code that looked something like this:

        public class UnitTestHere()
        {
                ...
                Db.CreateThing();
                ...
        }

        public static int CreateThing(this IDbCommand command,
                Action<Thing> modifier = null)
        {
            var thing = new Thing
                                    {
                                        ...
                                    };

            if (modifier != null)
            {
                modifier(thing);
            }

            command.Insert(thing);

            return (int) command.GetLastInsertId();
        }

So that, to modify the default values for the 'Thing' in the unit test, users had to do this:

        public class UnitTestHere()
        {
                ...
                Db.CreateThing(t =>
                        t.someField = someNonDefaultValue);
                ...
        }

My argument was along the lines of 'I don't want to have to do this to write my unit test'.

To which I got the reply (very correctly, I might add) that if I don't know it, then I should use it as a learning opportunity. Which is very true. In my case, the argument was less that I didn't know it and more that I felt the delegate was fancy-clever-overkill.

In this case, the code is both clever and clear - it serves a valid purpose, allows people reading the unit tests to see very obviously what values are being set IN the test, and it's dynamic enough to handle changes to any and all value changes in the inserted 'Thing' that might come up in future tests (like the one I was writing that brought about this discussion, for example). The hurdle of writing it is pretty quickly solved, and once the code is there it is clear enough to be maintained / changed with little effort.

I never meant to imply that more advanced tools don't have a place, just that sometimes people use them when they may not be better than the more basic options available to them.

And with that, I'm dropping this one. Happy Coding!

Tuesday, September 11, 2012

Coding at a Gradeschool Level



There are plenty of articles available for advice on writing clean and clear code. Many of the general principles are easy to grasp: short methods, straightforward logic and flow, clear and unambiguous variable names, consistent terminology usage, etc.


All of these things make your code easier to read, to understand, and ultimately to maintain and change. A good programmer knows that writing something clever and cool doesn't necessarily mean it was written the best way, even if it makes the code smaller. There are certainly limits to this (no one would argue much if you turns a 200 line class into 2 lines, even if those 2 lines weren't the clearest in the world, for example) but the point stands. There are 1000 ways to write code for a given feature, and there is no one true 'right' way for anything.

Which brings me to my point: a lot of times, writing something 'clever' may not be as good in the long run as writing something 'simple'. That abstract class filled with generic methods and callback delegates may get the job done and then some, may allow you to easily extend it and do anything you might ever have to do, but it's probably not easy to pick up and understand at a glance. We can set aside the benefits/risks of violating YAGNI in my example; it's worth addressing, but that's not my focus here.

In many cases, I try to keep my code as simple as I can. The analogy I try to about is a newspaper; in order to reach and be read and understood by the masses, most papers will dumb down their verbiage in order to be better understood. Similarly, I try and write my code so that a majority of it can be picked up and read by entry level programmers.

That's not to say don't used advanced programming techniques, but I know a lot of people who will use them because they are 'neat' or 'clever' or any other word that describes using it because it's interesting and not necessarily because it is the right tool for the job. There is nothing wrong with an if-else, a switch, or a foreach loop, and basic overloading or overriding of methods can get you very far. The keys to clear code lie in intelligent naming and intuitive methods.

Few people will look at this and not get the basic idea of what you are trying to do:

        public void OnClick(int id)
        {
       var ball = GetClickedBallById(id);
       ball.Roll(Units.Yards, 10, Direction.East);
        }

        private Ball GetClickedBallById(int id)
        {
       foreach(var ball in ballList)
       {
       if (ball.Id == id)
       return ball;
       }
       return null;
        }

But some, especially new programmers or those unfamiliar with the code, might scratch heads at something like this:
        
        public void Clicker(int i)
        {
       Get<int>(i).Execute(2, 10, 1);
        }

        private BaseClass Get<T>(T i)
        {
       return objList
                .Where(o => o.Id == i)
                .FirstOrDefault();
        }


Now, I'm not saying I hate generics or Linq, because actually I don't, and they definitely have a place and can be very intuitive. This is just an example, and an observation that more people will quickly understand a foreach loop with a couple of if statements than a possibly complex where clause in a Linq lambda. I know in reviewing my own code after the fact, sometimes what seemed like a really helpful and clever replacement would come back and bite me when I needed to tweak some minor functionality in that loop that I hadn't considered originally.

Every developer should ask themselves some questions in the above example: does killing those 4-5 lines make the code harder to read? Is there any way I can fix that? Is there a middle ground between clarity and concise code? How much do I expect my programmers to understand when they pick up the code? What about the BAs, or managers?

Don't be afraid to dumb down in the interest of clarify. There's nothing stopping you from refactoring it later into some super-generic-awesomeness if you REALLY feel you need it, and that it actually helps your code.

Happy coding!


Thursday, September 6, 2012

Using SQL xQuery to Select Multiple Node Values


A recent task involved us having to grab information out of an rdl whose dataset was saved as xml in a sql table (Yes, you can shudder at that statement, it's ok, I know I did). This was my first foray into xQuery in a sproc, so it was a pretty interesting experience.

There was existing code for dealing with a single value (handily, as a 'value' command), but not much on selecting multiple rows. What we wound up doing was a select from the table using a cross apply to grab the nodes we cared about, then performing a value on the returned data. Like this:

SELECT temp.dataStuff.value('.','varchar(50)')
  FROM XmlTable xt
CROSS APPLY xt.xml.nodes('(/root/nodes/data)') as temp(dataStuff)

If you do a select, you will see the nodes we return are untyped sql; the value call just says 'grab the nodes we returned and shove them into varchars'.

So, with an XmlTable entry with an xml column of this:

<root>
<nodes>
<data>ABC</data>
</nodes>
<nodes>
<data>DEF</data>
</nodes>
<nodes>
<data>GHI</data>
</nodes>
</root>

You would return this out of SQL:

ABC
DEF
GHI


Another helpful source for this is here: http://stackoverflow.com/questions/1393250/getting-multiple-records-from-xml-column-with-value-in-sql-server

In the linked example the cross apply wasn't necessary because they started with an xml string. Since we had to join in and grab multiples from different rows, we needed it here.

BizTalk Scripting Functiods with Same Name Methods


So a coworker had this happen to him today, and I thought it was interesting enough to share.

Create a BizTalk map with two different C# scripting functoids, both with the same method name and input parameters, like this:

System.String GetMe(System.String input)
{
return System.String.Format("Test 1: {0}", input);
}

System.String GetMe(System.String input)
{
return System.String.Format("Test 2: {0}", input);
}

Now link them to and from some placeholder xml schemas. I won't bother detailing the boiler-plate code for that here, if you know BizTalk I'm assuming you can link two schemas using a map.

You won't get an error, but the map won't function as expected: VS/BizTalk never catches the fact that there is an invalid overloaded method in the code attached to the map. What will happen is BizTalk will execute the first valid method it finds (in this case, 'Test 1' will probably appear in both outputs).

Hopefully this will help some figure out the cause of their strange map behavior!

Friday, August 31, 2012

Eat That Frog: A Helpful Philosophy

I've been following this philosophy for about a week now, both at my job and working on my Android game on the side. It really does help! I feel like I'm getting a lot more done, and the 'frog' doesn't taste as bad going down as I think it will looking at it. There is a lot to be said for just rolling up your sleeves and diving in to a problem.

Check it out!

Feeling pretty accomplished at the moment. I would love to hear someone else's opinion on it! Does it work for you, or if not, what does?