Keeping Count II – A Tale of Many Stores

In my previous post I described Daryl’s experience as a programmer writing an inventory control system for a candy store. Over the next few weeks Betty, the store owner, spread the word about Daryl’s fantastic inventory and billing management software amongst her friends. Daryl was flooded with requests for a computer application “just like the Betty’s”.

So he got down to work again. But Daryl now felt that writing inventory control wasn’t as much fun any more. So he wanted to get away with as little code, in the shortest amount of time as possible. He looked at what he had written for Betty and realised that most of the core inventory code was supposed to work exactly the same. All that was needed was to detail out some business specific stuff such as sale-units. This code could go into a thin layer on top of the code inventory module.

This is what his base Inventory class looks like.

class Inventory
{
    function AddUnits(Units:Number)
    {
        m_units += Units;
    }

    function RemoveUnits(Units:Number)
    {
        m_units -= Units;
    }

    function PrintUnits()
    {
        print(“Remaining units: ” + m_units);
    }
}

Daryl adds a member variable called FunctionReference and a method called SetUnitConvertor() to this class, which accepts a function reference as a parameter.

function SetUnitConvertor(ObjectReference:Object, FunctionReference:Function)
{
    m_unitConvertor = Delegate.create(ObjectReference, FunctionReference)
}

Then he modifies the PrintUnits() method to use this function reference.

function PrintUnits()
{
    print(“Remaining units: ” + m_unitConvertor(m_units));
}

He copies the Inventory class into the project for Mr. Coton’s cloth store and adds a class specific to that store inheriting from the Inventory class.

class ClothStoreInventory extends Inventory
{
    function ClothStoreInventory()
    {
        super.SetUnitConvertor(this, ConvertUnitsToLength);
    }

    function ConvertUnitsToLength(Units:Number)
    {
        // Find the total length of cloth sold
        return Units / 1000
    }
}

And another class is added for Mr. Chiseller’s consultancy firm.

class ConsultancyFirmInventory extends Inventory
{
    function ConvertUnitsToTime(Units:Number)
    {
        // Show the number of hours worked
        Seconds = Math.floor(Units / 1000);
        Minutes = Math.floor(Seconds / 60);
        Seconds = Seconds % 60;
        Hours = Math.floor(Minutes / 60);
        Minutes = Minutes % 60;
        return Hours + “:” + Minutes + “:” + Seconds;
    }
}

The result of this hoopla is that the base class will always call the formatting function from its inherited class (which would be quite impossible otherwise without using a messy callback system, or hard-coding the object reference into the base class, or (gasp!) event generation.

“But why use a delegate, you silly goose! The base class can override the PrintUnits() method with whatever it wants to use in its place.”

Well, that’s true. But when you start overriding methods from the base class, it means that the base class has not been designed to anticipate future use. This is a very basic example. But if your PrintUnits() method becomes more elaborate, such as drawing a dialog box with icons and buttons, or maybe even handling multiple output devices such as printers and LCD tickers, replicating all that code in an inherited class is really bad design. By using a delegate, you also allow yourself room to use static utility classes for mundane functions such as this.

Keeping Count I – The Candy Shop

Its been quite a while since I wrote about a serious programming-specific problem. In this two part series I will show you a popular database normalization method (don’t touch another database until you don’t grok that), and an alternative use for delegates. All code is written in Flash ActionScript and is purely illustrative.

Betty Green runs a candy shop that is wildly popular with the neighbourhood kids. The sweets she sells are sold by weight or by piece, depending upon the type. For example, peppermints are sold by weight, while chocolate bars are sold by the number of bars purchased. Being a good manager, Betty also keeps a register to track the amount of items of each type that she’s sold. At the end of the day she totals up the register and updates her inventory for the next day.

The system itself is quite good, but Betty would prefer that she didn’t have to wait till the end of the day to check out on which items she’s running low on, because then it means that her supplier can be notified only the next day. If she could let him know sooner, then she could stock up again on the same day and not lose customers.

Betty has received a new computer on her birthday from her aunt, which she feels can be used to good effect in her store. Daryl, a friend of hers, is a computer geek of sorts who has offered to write a software application for her billing and inventory management. He offers her many snazzy features such as automatic SMS order placement to her supplier when inventory falls low, a digital gallery of candies that she can display on an LCD ticker outside her store and of course, email. But what really gets her attention is a boring feature called inventory management. That is, the computer keeps track of her inventory and can give her updates after every sale, which allows her to place orders immediately if stock runs low.

So Daryl gets down to work. One thing that keeps nagging him is that inventory is to be maintained in two different units – grams and number of items. In her book-register, Betty used to draw two columns – one for weight and one for pieces. Whenever a sale was made, she’d fill in the appropriate column based upon the type of sweet she sold. Now, why should the database care how she sells her sweets? That is something that only Betty needs to know when she makes inventory. Daryl designs his database with a single UnitsSold column, in which he stores the number of units of each sale. His application interprets the sale units depending upon the type of sweet and displays the value with the appropriate unit symbols.

This is a simple illustration of an extremely powerful concept in data processing. All data are eventually converted to integers for the processor to work upon. By understanding how those numbers are encoded for abstract data types, you not only understand what’s going on behind the scenes, you can also drop down into the primitive level to perform operations that are not supported on abstract data types. For example, bitwise operators will balk at strings, but will gladly accept integers.

Programmers at Learnet, where I worked some years back, never quite understood this. So their assessment tracking database for fifty different activities would contain fifty columns, some of which contained numeric values, some floating point, some Boolean and some time. If new activities had to be added, they would add another column to the table and replace the database files. Everything looked okay until someone logged in the next time after the update and found that their previous scores were all gone. Whoops!

In my next article I’ll explain how multiple data types can be parsed efficiently at runtime, without rewriting too much code. Stay tuned.

Learning ActionScript

When I first jumped into programming in ActionScript about a year ago, I was carrying a lot of baggage with me from 6 years of Director/Lingo development. I was expecting more than just a change in syntax – this was going to be a paradigm shift for me! From coding in a language that comes close to writing a sentence, to something that resembled a real programming language. Heck, it even had {}’s.

Thing’s didn’t go as smoothly as I had expected though. This was nothing like what I had expected or was used to. Code in separate text files? What in heavens name are classpaths? And why does this language have an overdose of ;’s? Being on a tight schedule didn’t help much. I threw in the towel, hacked together something using old school techniques, and just about threw out Flash from my arsenal.

But an opportunity presented itself to give a second shot at Flash. NPAPL contracted their website redesign to Fractal Ink and an important aspect of the project was their portfolio. Since they wanted a lot of glitz into the presentation, this task would generally have been assigned to the designers. But due to the immense volume of data involved (100+ projects), I figured that a data-driven solution would make more sense than having the design team churn out a multi-megabyte, timeline driven file.

So I got to work digging up tutorials on component development, database access and XML parsing. Since the site was being hosted on a Windows server meant that my PHP skills would be of limited help (we ended up using static XML files instead). But the Flash code was pristine. I had finally broken through the glass ceiling.

I don’t remember the instant at which the change came through. But even today as I look upon the code, it looks nice. Simple, easy, readable. It took less than a few seconds to understand how it all fits together. What I remember thinking at that time was “How will I do this in Director”. By abstracting my thoughts out of the unfamiliar syntax of ActionScript, I was able to work my way around the requirements and atleast devise a solution. What remained was a very simple translation exercise, which got underway with ease.

I’ve moved on a lot since then today. I’m not a Flash guru or anything. But then I’d rather not be stuck working in a single environment day-in day-out. The new world of the interweb is rich in technologies, and I’m going to taste them all.

A Search for the Truth

I’ve spoken to several people since July 11 and can’t help notice the anguish that creeps through their voice when they speak about our government’s inability to stop terror strikes on our soil. Why is it that the largest democracy, heralded as a world power by many, isn’t able to protect its citizens? When the United States was attacked in 2001, President Bush came down hard upon the terrorist organisations and the nations which were suspected to harbour them – to the point of launching a full scale war in coalition with some of the strongest armies in the world. Why then can’t India perform such a feat against a country that it knows is responsible for several terror attacks in the past?

Our search for the answer begins on the premise that that the minority community feels insecure in India which political parties look to exploit.

Over the years I have seen the BJP and Shiv Sena combine champion the Hindutva cause. L. K. Advani has openly incited Hindus to bring down the Babri Masjid. Bal Thackarey used Saamna to encourage his party workers to launch offensives on Muslims during the riots of 1992-93. And in spite of the findings of the Sri Krishna Commission, the perpetrators of this violence are going scot-free. In such a situation, the insecurity that the community feels is not unfounded.

The problem is further aggravated by more politicians, who portray themselves as benefactors of the downtrodden. Parallels are drawn between the Hindus in Pakistan with the Muslims in India. The message that Muslim youth receive is that India is not their home and any act of violence that they help perpetrate upon its citizens will show their loyalty to their own motherland. Enter the LeT or Hizb-ul-Mujahideen, and their steady supply of weapons, explosives and training camps. These organisations fuel their terror operations on this sentiment.

In this vitriolic political scenario we bring in a government composed of a rickety coalition of parties with conflicting ideology. The Opposition is looking for every opportunity to criticize the ruling coalition and bring its government to a grinding halt – the country be damned, we want our seats back. And we expect this government to lead the country into an offensive war? Against a country which a sizable segment of the population considers their true homeland? That is wishful thinking at best and ridiculous misunderstanding of the political situation of India at worst.

All I can say to conclude is that India will never launch a war on terrorism unless its citizens unite in their opinion of what they call their homeland. And the power to do that lies with the citizens themselves.

  1. Always treat your communal neighbours the way you would want to be treated.
  2. Boycott media mouthpieces which carry a communal twist to their reporting.
  3. Speak up against wrongdoings by politicians, whether they are against the majority or minority community.
  4. Teach your children about the equality of religions and communities at an early age.
  5. Never violate human rights in an attempt to seek justice for wrongdoings.

Birds Banned in Mumbai

In an unprecedented move, that could have far reaching consequences on the country’s ornithological populace, the Balasaheb Thackarey led Shiv Sena has officially banned birds from entering the country’s financial capital, Mumbai. Shiv Sena spokespersons say it is an unfortunate step, but is required in order to maintain the dignity of statues and busts scattered throughout the city. Earlier, birds would use these statues as resting points, and defecate upon them. Post this ban, statues will finally be able to heave a sigh of relief for not being mistreated in such a manner. Shiv Sena leader Udhav Thackarey says, “Imagine how you would feel if a bird came and shat upon your brand new outfit? Such is the condition of statues in the city many of which are being subjected to such rude treatment within hours of dedication.”

When asked how the ban will be implemented given the communication barriers between humans and their feathered friends, several creative ideas have been put forth by party members –

  1. Installation of a fine wire net over the entire city with entrance/exit points for non-feathered creatures
  2. Satellite monitoring of the city’s precincts, along with James Bond-style satellite mounted laser’s to pinpoint and annihilate offending birds
  3. Worldwide extermination of birds (a bit difficult to implement given that Shiv Sena’s jurisdiction extends only within Dadar)

Sena leaders have promised their cadres to lay these plans before the state government and demand implementation at the earliest.

In related news, noted animal activist Maneka Gandhi has raised her voice firmly against the Sena stand. Joining hands with her are hard line animal rights organisations AHIMSA and PETA. Although details of their plan of action haven’t been revealed yet, spokespersons for both organisations say their plans will take flight soon.