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?

Tuesday, August 28, 2012

Android Apps and Image Memory Management


Recently I discovered an interesting (and somewhat counter-intuitive) feature of drawing drawables as bitmaps in an Android game.

The intent: Produce a refreshed canvas at something around 30 to 50 FPS, using about a dozen images.

I had already made several of the images into sprites with source rectangles to handle grabbing the different frames: if you want to know more about what I'm referring to, Google 'drawing animated sprites', and do some digging into the concepts of source rectangles vs destination rectangles.

The responsible programmer in me approached this problem with the idea that I was going to load all my images, draw them, and then recycle and clear them. That would allow the garbage collector to come along and efficiently manage my memory.

After dealing with the surprising limitations of bitmap sizes in the Android VM (a simple 1024x768 background image caused an OutOfMemory exception initially), I was still not drawing nearly as fast as I wanted to.

For reference, one way to load larger images is to use temp storage when loading the drawables into bitmaps, like this 16k buffer I typically use:

        Options options = new Options();
        options.inTempStorage = new byte[16*1024];
        _image = BitmapFactory.decodeResource(_context.getResources(),
                resourcePointer, options);

The goal was 30 to 50 times a second, the initial reality was about 1 frame every 30 seconds. What I was seeing was that the GC was happily gobbling my memory... and taking about 100ms for every image cleanup. Adding that to the load times from the BitmapFactory, and multiply by 12, and there you go.

The solution? At first, it was 'blindly frontload the images'. That way I could avoid the load/dispose delays, but it kept a lot of data around in memory that I wasn't thrilled with. I had to reconcile my need to clean up with the reality that if I needed it again in 20ms, I probably wanted to keep it around.

Eventually I wrote a piece of dynamic code that iterated over all my image processing classes and said 'load or unload based on game state' and returned a boolean telling me to run GC when I was done with the processors. That code ran every frame draw, but only caused delays when changing game state, which I had written such that it happened asychronously when I finished fading out the previous screen but before fading in the new one.

    private void Redraw(Canvas canvas)
    {
    LoadUnloadImages();
        switch (_game.State)
        {
            case X:
                RedrawX(canvas);
                break;
(...)
        }
    }

    private void LoadUnloadImages()
    {
    Boolean runGC = false;
    runGC |= xProcessor.LoadUnloadImages(_game.State);
(...)    
    if (runGC)
    System.gc();
    }


xProcessor.LoadUnloadImages(_game.State) has another switch in it that says to Load or Unload based on state, and the loads/unloads only happen if the image is actually there to unload (or not there to load) so it doesn't waste time on pointless executions. GC only comes back on successful unloads, since the only time I need to explicitly clean up is after I recycle the bitmaps.

That way, each state has only the images it needs, and kills them as soon as the state changes (typically a screen change: menu, paused, main game screen, cutscenes, etc). The combination of all these responsible memory changes have allowed me to easily achieve the 50FPS goal I set out for at the start.

Another thing I should note: this is the only place in the entire app I call System.gc(), because that command WILL slow down your execution if you call it too much / inappropriately. Let the gc work on it's own if you can afford to, but you might still want to think about recycling your unused bitmaps and nulling them out.

Hope this helps all you Android devs out there with similar image delays!

Friday, August 3, 2012

Calling an Asmx Service using PowerShell

So a recent problem we had at work was calling a one-way asmx service on some kind of repeatable schedule; no security concerns to speak of, it was all internal-facing. So it became my job to write something as small and light as possible.

My first approach involved jumping into what I will call our 'existing' ticketing system. The popular analogy we were using was 'using an ICBM to kill a mosquito'. It involved a windows scheduler waking up an executable to drop a message onto an MSMQ, that was picked up by a BizTalk service, and was routed to some command processor. In this case, that would have been an HTML send port in same said BizTalk world... not simple, not quick, and pretty much vomit-inducing complexity for what should be REALLY dumb and simple.

My next approach, somewhat better: a quick console app, pulling the configurable values (server, command parameters) from the app.config. It looked something like this:


        static void Main()
        {
            try
            {
                var username = ConfigurationManager.AppSettings["username"];
                var password = ConfigurationManager.AppSettings["password"];

                var client = new XXXSoapClient();
                client.ProcessXXX(username, password);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }

Better, and certainly usable in our current world. Our Enterprise Architect made a great suggestion to me though; check out  PowerShell, see if there is some really light way to just 'get' the proxy and make the call. Turns out, there was:


        $page = New-WebServiceProxy -Uri 'http://server/InternalServices/XXX.asmx'
        $page.ProcessXXX('USER','PASS');

And there you have it. Two PowerShell lines to call the server, get a proxy, and make the call.

Thursday, January 26, 2012

Logging In to Google: A Commentary on OAuth

Maybe it's just the fact that I'm going about it wrong, and that it's really not meant for C#, but my general opinion of interfacing with Google APIs is that it's like pulling teeth, at least when it comes to DotNet.

First, make sure you find the right pages, and know -exactly- what you want to do and how you want to do it, because there are about 50 different ways to log in and use Google tools, and all of them are slightly different. Then make a project, and get your special top secret keys: something that I agree with on the surface, but why do I need a key for a console app and a web app? And while straight up mobile apps count as console apps, what does a wcf server count as? Because in the end, I want to authenticate on the client, but authorize on the server (to do things like pull your friends list, etc). Add to that the fact the tutorials are cryptic and complex, and it's really just a complicated, painful experience.

In the end, I'm still not fully set up with Google. I also want to interface with Facebook: hopefully that's a little simpler than this has been.