Writing a Javascript Component

Ok, for my next blog post, I thought I’d actually put in something useful. Enough of writing about myself and where I’ve been and what I’ve been doing. Time to drop in on some javascripting action!

So, fair warning, if you’re not much of a javascripting fan, I think this is where we ought to part. Of course, you might want to take a look at some of my other posts.

Now that we’ve got the non-javascripters out of the way, let’s get started!

First, a bit of lame theory. What must your javascript component do? What must it not do? And what must it definitely not do?

Separate Content, Styles and Functionality

While designing a javascript component, it pays to keep the content, which generally involves (X)HTML, the styling done through CSS, and the functionality added on by your javascript code separate. This keeps your HTML, CSS and Javascript code from occassionally stepping on one another’s toes, and making what must otherwise have been simple tasks, such as adding a little bit of content, or changing how the component looks a nightmare.

By abstaining from using inline styling, and moving all your CSS styling into a separate file, you make your css code cacheable.

Avoiding the use of HTML attributes for javascript events (such as, onclick=”blah()”), and instead, using some event queuing mechanism that comes along with pretty much all the common general purpose javascript libraries (like jQuery, Prototype or YUI) makes your javascript code unobtrusive, meaning several scripts can play on the same page and on the same HTML elements, with no bullying involved.

Finally, always consider the case where your content is edited by one person, who is just reasonably good at HTML, and knows nothing about javascript or css. Keep his job simple, and there will be no trouble.

Multiple Instances or Not?

The next question to consider is whether your component ought to allow multiple instances of it being created on the same page or not. Except in some very few cases, for example, if your component is an abstraction for an event queue, etc., the answer is generally yes.

However, when you design a component to support multiple instances on a page, you need to take care that every bit of data you use in the component is confined to an instance, as members, rather than being in the global namespace (unless you intend to share something across instances, of course). The best way to take care of this might be to wrap your component into a class. The user of your component gets to instantiate your class as many times as he needs on a page. Or, if your component can be expressed as a set of procedures, such as a few event handlers, it might be easier to just bundle it as a single function that attaches the handlers to the desired events (an example of this is what I describe later on).

Design for Everyone, Degrade Gracefully

Another thing to keep in mind is that not everybody has or runs javascript. From the security freaks who live in perennial fear of everything cyber, and keep javascript off at all cost to the busy traveller who browses on a phone, your website mustn’t punish those who don’t use the correct version of Firefox or Internet Explorer.

Always design your components to degrade gracefully at times when javascript is disabled, or is not available, or when certain features that your script needs to survive are just not supported on the visitor’s browser.

Designing a Scrolling Tab System

Now we’ll see how to design a scrolling tab system, such as the one on the Pragyan Events page.

We first decide what the HTML should look like, for such a contraption on screen. The following is the structure I decided to use.

<div id="myscrolltab" class="scrolltab">
	<div class="scrolltabheadingsleft">
		<div class="scrolltabheading" rel="content1divid">Heading 1</div>
		<div class="scrolltabheading" rel="content2divid">Heading 2</div>
		...
	</div>
	<div class="scrolltabheadingsright">
		<div class="scrolltabheading" rel="content5divid">Heading 5</div>
		<div class="scrolltabheading" rel="content6divid">Heading 6</div>
		...
	</div>
	<div class="scrolltabcontainer">
		<div class="scrolltabcontent" id="content1divid">Content corresponding to heading 1.</div>
		<div class="scrolltabcontent" id="content2divid">Content corresponding to heading 2.</div>
		<div class="scrolltabcontent" id="content3divid">Content corresponding to heading 3.</div>
		...
	</div>
</div>

You might, of course, think of other (possibly better and more common sensical) ways to structure your content. This is the one that occurred to me off the top of my head. 🙂

Next, we’ll add just enough CSS to take care of basic styles, positioning, etc.

.scrolltab {
	width:660px;
	margin:8px auto;
	position: relative;
}

.scrolltabheadingsleft, .scrolltabheadingsright {
	width:120px;
}

.scrolltabheadingsleft {
	float:left;
	margin-right:-120px;
}

.scrolltabheadingsright {
	float:right;
	margin-left:120px;
}

.scrolltabheading {
	border: 1px solid white;
	padding: 4px;
	margin-bottom: 8px;
	background: white url(../images/scrolltab-inactive.gif) scroll repeat-x center center;
	font-size: 14px;
	font-weight: bold;
	cursor: pointer;
}

.scrolltabheadingsleft .scrolltabheading {
	margin-right: -1px;
	border-width: 1px;
	border-style: solid;
	border-color: #B9B9B9;
	text-align: right;
}

.scrolltabheadingsright .scrolltabheading {
	margin-left: -1px;
	border-width: 1px;
	border-style: solid;
	border-color: #B9B9B9;
	text-align: left;
}

.scrolltabheadingactive {
	background: blue url(../images/scrolltab-active.png) scroll repeat-x center center;
	color: white;
}

.scrolltabcontainer {
	position: relative;
	margin: 0 120px;
	border-left: 1px solid #B9B9B9;
	border-right: 1px solid #B9B9B9;
	padding:0;
}

.scrolltabcontent {
	padding: 0;
	border-top: 1px solid #B9B9B9;
	border-bottom: 1px solid #B9B9B9;
	height: 480px;
}

.scrolltabcontent ul {
	margin-top:0;
	margin-bottom:0;
}

Note that after adding the css, the component doesn’t quite look like what it should in the end. This is because we’re not going to mess with the display styles of the scrolltabcontent divs just yet. Why? Because if we add css to, say, show just the first scrolltabcontent, and hide the rest, and if javascript does not work on the client, the visitor ends up having no way to view the content in any of the other clusters. So, by moving a few things out of the css, and into the javascript, we’re determining how the component degrades in a javascript-less browser.

The next step, you guessed it, is adding the javascript. With a library such as jQuery, your work becomes reasonably simple and straight forward. The code, with necessary comments, is given below.

$(document).ready(function() {
	// hide everything but the active scrolltabcontent
	$('.scrolltab').css('overflow', 'hidden');

	$('.scrolltab').each(function(index) {
		// if the scrolltab hasn't been assigned an id, assign one
		if (this.id == '')
			this.id = 'scrolltab-' + index;

		var scrollTabId = this.id;

		// add an event handler to handle heading clicks
		$('#' + scrollTabId + ' .scrolltabheading').click(function() {
			var contentDivId = $(this).attr('rel');
			if (contentDivId == '')
				return;	// oops, no associated content? leave it alone

			// set the current item as the "active" heading
			$('#' + scrollTabId + ' .scrolltabheadingactive').removeClass('scrolltabheadingactive');
			$(this).addClass('scrolltabheadingactive');

			// make the container large enough to hold the current tab item's content
			$('#' + scrollTabId).css('height', $('#' + scrollTabId + ' #' + contentDivId).height() + 2 + 'px');

			// compute the top in pixels of the current tab item's content
			// and move the container up by the negative of that value
			var position = $('#' + scrollTabId + ' #' + contentDivId).position().top;
			$('#' + scrollTabId + ' .scrolltabcontainer').animate({top: '-' + position + 'px'}, 'normal');
		});

		// simulate a click of the first heading
		// so that the first heading is selected by default
		$('#' + scrollTabId + ' .scrolltabheading:eq(0)').click();
	});
});

The way the code works can be visualized like this. You have a big sheet of cardboard with a window in it. This is the scrolltab div, with overflow-y set to hidden. Behind the cardboard, there is a long scroll of paper with stuff written on it. This is the scrolltabcontainer div, with all the content inside it. When the user asks for some information, you scroll this sheet of paper by the correct amount so as to align the required content with the window for the user to see. Easy peasy.

Well, that does it for this reasonably short post. If you’ve got all the time in the world, please do test this out on different browsers, and post your comments.

– Rugged-Scripting-Rat

 

Notes:

  • Don’t forget to download and include jQuery, if you’re planning to use the above code off-the-shelf (or, off-the-page).
  • For my purposes, I had put in Yahoo’s Reset CSS. I’m not sure if that might change a few things on a few browsers. If things aren’t looking as expected on some browser, please also try including the reset css along with the styles given above.
  • In the css given above, I’ve put in a height for the scrolltabcontent class. This isn’t necessary. I just added it because the html given above has absolutely no content in any of the divs. You should probably try adding some javascript to handle short content too. This wasn’t much of a concern for me, so I haven’t bothered.
  • Bug fix for (a few versions of) opera: Setting overflow-y to hidden seems to mean nothing to the browser. The first line inside the document ready handler has therefore been changed to $(‘.scrolltab’).css(‘overflow’, ‘hidden’); as opposed to overflow-y.
Advertisements

Finally Free

Starting work on a blog post in the middle of the exams ought to be some indicator of lowered expectations from what I consider the most hectic semester thus far. From getting jobs to scraping through in the exams, from qualifying for the ACM ICPC World Finals to Pragyan and Delta work and Product Design, and a weekend where I managed to be at three geographically far-flung places (several paragraphs on that later), it’d seem I’ve covered a lot of ground and seen and done a lot of things over the last few months.

The semester started off like any other, with a dull auto ride to the campus after getting to Trichy on a train that always runs late by an hour, and a sinking feeling I’ve grown accustomed to, having gone through much the same thing six times previously. Besides, I was probably a little excited about placement tests and interviews. You never know what these things are like, till you’ve done it yourself. People give you advice, sure, but that’s just their opinion, and if you’re like me, you’d prefer to form your own. I was also looking forward to the one legitimate excuse to wear my tie, putting the several hours spent on youtube and in front of a mirror to good use.

Had my first flight ever when I got flown down to Mumbai for, er, business reasons. I did my best to look rich and affluent. Flying became a habit ever since. Oddly enough, every time I flew, I also found myself sitting on the steps of an unreserved train compartment soon after.

Google Codejam was happening parallel to all of this. An Air India strike that put me on an unreserved train from Chennai to Trichy while returning from Mumbai saw me through to missing my second online round.

The Kanpur-Gwalior ACM ICPC onsite regionals came next. Hospitality was managed by IIITM Gwalior, and kudos to them, while IIT Kanpur came out with the problemset, though sadly I can’t say the same for them. Needless to say, an algorithm contest where every problem had to be bruteforced is less than ideal.

Towards the end of October came the Amrita onsite regionals. Amrita’s online contest was free, and saw close to four hundred teams registering, from which, around fifty, including a few foreign teams were selected for the onsite contest. The contest was scheduled for a Sunday morning, and registrations could be done on Friday evening and Saturday morning.

Interestingly, I had to travel to Chennai on Thursday night to collect the circuit for Product Design that we had given for fabrication there. Got to Chennai on Friday morning, got everything we needed, and got back to college by midnight on Friday. My teammates, Akhil and Venkatesh, on the other hand, had left for Amrita on Thursday night.

Even more interestingly, we had our comprehensive viva voce – the grueling test where it’s completely legal for them to question you on anything and everything you ideally would have learnt in your entire life, and force you to redo your whole B.Tech. course if they find you, for lack of a better word, unfit – on Saturday morning.

Hence, I was in college attending a silly viva where they asked me the difference between accuracy and precision, while great storms were brewing at Amrita. Things would’ve been pretty smooth, had the external examiner showed up at 9am that day, as he was supposed to, because I had booked a flight at 1.30pm out of Trichy to try to get to Amrita by that night. Instead, I had around 10 minutes to pack up and leave on a cab when my viva got over, thanks to which I forgot everything from toothpaste to clean underwear. I landed in Chennai a little before 3, followed by a long wait till 6.45 for the connecting flight to Trivandrum, and I must thank one or two resilient colleagues for keeping me entertained over SMS 😛

After reaching Trivandrum at around 7.45, it was a sprint to the railway station, where I already had people (well, not henchmen, just my mom and my grandpa) waiting for me with my ticket to Kayankulam on an 8.45 train. The taxi ran into traffic, backtracked, took another route, and did a few other exciting things before dropping me at the railway station at around 8.35. I got to kayankulam at 11 give or take five minutes, and then to Amrita by 12 in the night. I had to make do with six hours of sleep, and maybe it was just the lack of sleep that kept me sharp during the contest. We finished second to a South Korean team (Team Oasis, Sogang University), and this sufficed to get us a slot in the World Finals.

Three teams from India qualified for the World Finals,

The World Finals are to be held at Harbin, China this time around, from 1st to 6th February, 2010. I’m really excited about the trip, ’coz not only is it my first venture abroad, but apparently we’re headed there in the middle of their Ice Festival, and, well, it happens in Harbin for a reason. Average lows in February there are supposed to be in the thirties (degrees Celsius) below freezing, and, being from the Tropical lands down south in India, I’ve never even seen anything less than twenty degrees above zero!

Well, that said, an apology goes out to the Delta and Pragyan CSG folk. I know I haven’t been around too much over the last semester, but I hope you understand how badly I wanted something worth holding on to from college. We’ve got a whole semester ahead, where things will be a whole lot different, I promise 🙂

In any case now I’m finally free, for one full month! Can’t wait to see what happens 🙂

– a Rugged Rat heaving a sigh of relief!

One Thing to Another

Whew, that was a tough couple of months and, without doubt, several more grueling ones are on their way. Keeping this post short (kind of, remember: I type really really fast) for sheer lack of time ought to suggest something, I suppose.

I just spent the last two months working on a project at IIT Madras. As much as the project was interesting work, I had neither accommodation, nor food taken care of, so such things were of more concern than writing the cleanest bits of code. I used to stay with my cousin around forty-five minutes away on foot, and there was no other mode of transportation possible along that route short of an auto-rickshaw, which I certainly did not wish to pay for. In truth, I didn’t mind the distance as much as the heavy tan I used to get walking it, which, I suspect, will hamper me in several of my endeavours in the near future. But my cousin and his roommates were probably the people to stay with.

The IITM campus was quite nice, what with all the trees, and the deer and the sleek buildings. I wasn’t too impressed with their labs, though. Running age-old software on the latest and greatest hardware didn’t strike me as the way to go. The project kept me busy for the most part, when you’re writing a framework, you generally like to have most of the things figured out before you start, not your most basic assumptions and understanding of requirements pulled right out from under you when you’re half way through. The worst part is how, when all the dust settles, it’s the user interface tools that get all the attention, when the framework churns away under it, doing all the useful work. 😐

Attended a lecture on iWires, and a workshop by nVidia on CUDA while I was there. iWires was a rather interesting concept; and the nVidia CUDA workshop and the subsequent dinner were rather fine. It’s amazing, the kinds of things people are trying to do. I just hope all of this development doesn’t run away without me.

Got to see Angels and Demons at one of Chennai’s multiplexes. To be fair, I did not like it. No, not the movie, just the multiplex. Not only did I have to pay around three times what I would have back where I’m from, the hall and the screen were small, there was no balcony, and the food and drinks cost twice as much by way of taxes. Imagine a 40 Rupee 600ml Pepsi bottle, brr! I did enjoy the gaming arcade they had, though. For some reason, people find it hard to believe I’m something of a gamer till they mess with me. If you’re thinking along those lines, you’re welcome to try. What makes matters worse is I got to see the same movie later for 30 bucks at IITM’s Open Air Theater, with a much larger screen, great seats and a couple of bread-omelets.

People used to exchange slippers for apparently no reason. Mine went to Mc Donald’s once without me. I must admit, it’s a little depressing when one’s footwear gets ahead of one in life.

Managed to throw in a trip to Pondicherry too. The beach, the beer, the babes, all packed into one 18 hour day. But I’m not really sure whether all the R & R didn’t leave me extra tired for the next day.

In the end, a couple of thousand lines of code, a great deal of presenting, defending and debating, and a hundred pages of documentation later, I’m back home again, for a couple of weeks of absolute doing-nothingness before the next ordeal begins.

It’s one of those times when you’re on top of something and you still feel like a kid. Somehow, after having worked my way up the ranks through the last couple of years, I still feel as young and unworn, and also as inexperienced, as the tiny second year coder I started off as. I wonder if my predecessors had felt the same way, they looked a lot more mature, if anything.

That apart, placements seem like something of a concern now, as does a dreadful subject called Product Design & Development, God help me pass in that one! It’d suck to get an arrear after six semesters of scraping through without much effort.

Next year’s ACM ICPC (read my previous post, if you haven’t already) looms, as registrations start next week. I’m hoping to get a serious team to compete with this time around. When it’s your last shot at something, there’s no holding back, and I’m pretty sure you wouldn’t feel bad whatever happens in the end, as long as you know you tried.

As they say, let’s wait and see. Or probably crouch, observe and pounce.

– Rugged Rat

How to code – again

Well, those were some really busy weeks. Despite all that was said in my previous post, I ultimately did do truck loads of work over the last couple of months. A sense of responsibility keeps me from leaving jobs that I’ve taken up, though I sure ain’t getting any younger.

Contrary to the widespread delusion that when you work as a team, you need to work less, and you tend to have someone to cover your back when you need it covered, I rather found that it could as well be a really tough task. I took some time to analyze the partnerships I’ve been in, and thought I’d put out a few pointers that might help people code better, and may serve as a reference to any future teammates I may have :).

Most of the instances cited in this post are real. I name no names in this post, but there might be references or examples that may identify the person/persons I’m talking about. But please keep in mind that the post is not targeted at the people, but rather at the practices or lack of them thereof. The post is intended to be nothing but constructive, and I sincerely hope it doesn’t discourage anybody from doing what they do best. I’m just exploring better ways to do a few things. Few turn into coding gurus overnight.

Code in English

You become a better programmer when you realize that, like any other language, programming languages are simply a means of expressing yourself, to slightly more retarded contraptions. Whether you use C, C++, Visual Basic, Python or Ruby, you need to find ways to express your intents to their fullest. A few examples might throw some light on the issue.

Consider a function named quizcomplete, which takes a Quiz ID and User ID as argument. What does the function do? Does it check whether the user has completed the quiz, or does it mark a user’s quiz as completed? Or, as a third alternative, is it meant to be called when a user completes a quiz? Simply put, the name of the function tells you absolutely nothing you might want to know about the function. Next time, ask yourself whether you’re naming things right. A function that checks whether a quiz has been completed needs to be called something along the lines of checkQuizCompleted (or isQuizCompleted) and one that marks a quiz as completed needs to be called markQuizCompleted (or setQuizCompleted).

The same applies for variables. It’s generally good practice to keep global variable names (that is, if you really really needed global variables in the first place) long and ugly, and local variables that last for no longer than five to ten lines of code short and sweet. Don’t be scared of long names: a few extra keystrokes today will save you hours worth of debugging time later, and longer variable names don’t contribute to the memory footprint of your application ;).

To take it a step further, the rule even applies to the loops you write, and the way you structure code. For example, prefer a for loop over a while when, say, you’re iterating through a list of items, or performing some computations a predetermined number of times, and prefer a while over a for in such cases where you wait for a condition to break in order to stop doing something. do .. whiles have their own set of uses.

Not so good:

int i = 0;
while (i < 10) {
	// Do things
	++i;
}
Better:

for (int i = 0; i < n; ++i) {
	// Do things
}
Not so good:

for ( ; a == b; ) {

	// Do things

}
Better:

while (a == b) {
	// Do things
}
Not so good:

// Do things with a
while (next_permutation(a.begin(),a.end())) {
	// Do things with a
}
Better:

do {
	// Do things with a
} while (next_permutation(a.begin(), a.end()));

As another example of how you express your intents, consider how you’d reverse bits in a number:

int res = 0;
while (m) {
	res *= 2;
	res = res + (m % 2);
	m /= 2;
}
int res = 0;
while (m) {
	res <<= 1;
	res |= m & 1;
	m >>= 1;
}

One of my friends said she preferred the first version, and the second looks complicated. To me, the second one expresses your intentions more clearly.

Consider how a programmer (who is well acquainted with bitwise operations and operators, mind you) would read the two snippets of code:

Snippet 2: “Set res to be 0, keep shifting res left, appending the last bit from m to res, and shifting m right, till m becomes 0. Hmm, keep removing the last bit from m and attaching them to res. Reverse m’s bits! Yay!”

Snippet 1: “Set res to be 0, keep multiplying res by 2, add 1 to res if m is odd, and divide m by 2 till m becomes 0. WTF?”

If something is repetitive, it probably deserves to be in a loop

Loop is rather metaphoric here. Make use of language constructs to handle collections of objects, and operations that occur repeatedly, and represent their inter-relationships.

Just so you don’t limit this rule to loops and arrays, I’ll cite a slightly deeper example. I had to work on an online treasure hunt not too many days (hours) ago. My task was to simply go through the code, and look for things that might go wrong, cases where the code might fail.

An online treasure hunt is a rather simplistic application where a user is given some kind of a puzzle, and is expected to make his way to the next one by solving this one. Effectively, it all boils down to keeping track of users, and the level they’re on, showing them the problem, and validating their solutions. The existing system consisted of one file for each level in the game, with each file checking whether the submitted answer is correct, and if it was, redirecting to the next file, and displaying the current file’s contents if it wasn’t.

What’s wrong with this approach? For one thing, you couldn’t add or remove levels, or reorder them without considerable effort. For another, if you were to find some bug in any of the duplicated code, or were to think of a better way to do some of it, you couldn’t get away with anything less than changing all the twenty five or so files you’ve made.

How do we come up with a better solution? We try and characterize all the data that would define a level comprehensively, and try to develop a system where the levels and the process of traversing them remain independent. This way, we can add and remove levels without ever bothering about the code that guides a user through these levels. When you find something going wrong with a user’s progress through the game, you know you’re supposed to look at the user management code, rather than the level definitions. Both of our problems are solved.

It turned out that each level could be defined by just a few fields, such as the name of the level, the content to be displayed to the user viewing the level, some kind of function to check whether the answer submitted was correct, and a pointer to the next level to which the user must be directed. Moreover, most levels either posted the user’s submissions to the server, or expected the user to type in a url directly to go to the next level. An associative array that represents the field names, and their expected values could be tied to every level that submitted solutions via POST, and a string representing the url of the right answer could be tied to levels that expected urls, and two simple functions could be written to check if the user has found the right solution.

Mostly, I would’ve made a table with these many fields, and added levels there. Because I had only one night to get the whole thing running, I turned to simple PHP arrays to hold all the data. In the end, the whole system was reduced to just two files weighing in at less than a hundred and fifty lines each, and one file to hold information about levels as a PHP array, all written in just one night’s time.

Copy and Paste is not a form of Code Reuse

From the previous example, I’d gather that if you ever needed to write the same piece of code twice, you know you’re doing something wrong. Copy and paste is not code reuse, it’s quite the opposite. Code reuse is when you have just one piece of code that serves your purpose at a variety of different places. When you copy and paste something, that’s called redundancy.

Before getting to code reuse, I’m going to ask, how bad is redundancy?

Here’s the deal: in a relatively small web application I was developing a while ago, we had a registration form. So what? All web applications have registration forms. Simply define a few fields that need to be filled in, validate them, and insert them into a database. I didn’t write the form or the handler, but I was asked to add asterisks (*) to all fields that are mandatory. Hardly a few seconds’ task for anybody. Unfortunately, despite making the change, and refreshing my browser window several times, the asterisks were simply refusing to show up.

Not understanding what the problem was, I try typing in some arbitrary pieces of text into the form’s code. Still nothing. I check if I’m working on the same copy that I was looking at, whether the pages were getting cached because of url-rewriting, whether the file was write-protected and my editor didn’t realize that it couldn’t write to the file, and, after exploring many such possibilities, it turns out there were two copies of the registration form: one for the user’s first view and one for when the user has submitted some content, but it was rejected by the server because it failed validation. For a small change such as adding an asterisk, you probably wouldn’t mind doing it at two places. But what if you were adding three fields, removing two, and adding JavaScript validation rules for all fields in the form? Now that’s double the amount of work you need to do.

Coincidentally, at one point of time, the application also ended up having one copy of common.php in every folder, till I painstakingly cleaned it up. After all, why would you call something common, if there was going to be several different copies of it, all of which would be changed in different ways over time?

Frankly, having several different copies of the same code in your application is going to be one heck of a maintenance nightmare. Avoid it at all costs. When you start off, generalizing a piece of code might seem like a very tedious task, but it will be well worth the time and effort when you need to make changes later on.

And how exactly can you reuse code? You don’t need to understand templates, inheritance, or even classes to make sure you write the least amount of code possible. Besides, different languages differ in the mechanisms they provide or encourage for code reuse. In most cases, smart use of functions alone can take you a long way in this regard.

Whitespace Matters

When you write code, write it neatly, or don’t write it at all. There is nothing I hate more than having to read through horribly intended (or, well, non-indented) code that looks like an egg splattered on your screen. Free-formatting wasn’t a feature any language developer worked so hard on, that you should feel obliged to make full use of it.

“Eek! What is wrong with you?”:

int N, R; cin >> N >> R;
	vector< vector<int> > 
graph(N, vector<int>(N, INT_MAX));
	for (int i = 0; i < R; ++i) {
				int a, b, l;
	cin >> a >> b
>> l;
	--a;--b;		
		graph[a][b] = graph[b][a] = l;
		}

“Where does the } start?”:

	int N, R; cin >> N >> R;
	vector< vector<int> > graph(N, vector<int>(N, INT_MAX));
	for (int i = 0; i < R; ++i)
		{int a, b, l;
		cin >> a >> b >> l;
		--a;--b;	
		graph[a][b] = graph[b][a] = l;}

“Ok, now clean up that whitespace”:

	int N, R;
	cin >> N >> R;
	vector< vector<int> > graph(N, vector<int>(N, INT_MAX));
	for (int i = 0; i < R; ++i) {
		int a, b, l;
		cin >> a >> b >> l;
		--a;
		--b; 
		graph[a][b] = graph[b][a] = l;
	}

And that’s how you write neat code.

Set standards for yourself: either use tabs consistently, or use spaces, but not both. I personally prefer using tabs to indent my code, because most editors let you choose the width of a tab, so you can change the level of indentation at any time. Since tab width varies from editor to editor, or with editor settings, you can never rely on spaces to indent code right if you’ve already used tabs somewhere.

Think Ahead

Think about all the functionality your code needs to implement before starting to write code. This way, you’ll start seeing similarities that you can exploit to write only as much code as is necessary.

For example, let’s say you’re implementing a quiz system. A quiz is divided into sections, and each section holds a set of questions. Ordering of sections and questions is important, so you need to provide Move Up and Move Down buttons for the administrator.

You might think of writing four functions, moveSectionUp, moveSectionDown, moveQuestionUp and moveQuestionDown for this, but you’ll soon see that moving something up or down is a very general problem that you can solve with a very generic piece of code. Once your generic function is ready, you can probably write some single-line wrappers to use the generic function to make your code more readable.

Extensibility

Unlike in most other trades, when it comes to developing a system, present-day needs ought to be the least of your worries. Before beginning to type away to glory, ask yourself what your system needs to do today, and what it might be expected to do in the future.

If you’re writing a CMS, you might want to extend it later by adding more types of pages, layouts, templates, support for a variety of database systems etc. Ask yourself how probable each of these kinds of additions would be, and how easy or hard it will be at that time to incorporate it. The amount of time you spend on making a system extensible would depend on how probable you think that such an extension might happen in the future.

Ideally, extending an application should mean no more than adding your new code at a certain, well-documented location, and perhaps changing a configuration setting somewhere.

Stick to Conventions

Make rules for yourself, and stick to them. These rules ought to cover everything from the way you indent code to the kinds of names you give to your types and objects, to how you split code into files. Be a fanatic. Being predictable is a virtue in this regard.

Don’t Reinvent the Wheels

What else is a virtue? Laziness.

Make use of existing libraries and frameworks to build your application. There are several plusses in doing so.

A library simply provides an abstraction over existing API and gives you functionality that you either use regularly, or that might have been quite tedious to implement using the existing API. They let you write clean code, with complexities hidden away under the more pleasant interface that it provides to your application (this is true especially in the case of JavaScript libraries, where a lot of browser-dependent code is buried deep in the bowels of the library, and you get to write a single piece of code that works well on all the most common browsers, and some cross-platform C or C++ libraries such as boost, where you get a version of the same library for different platforms, so you don’t need to maintain different versions of your code for different operating systems.).

The library would probably have been tested more extensively than you can afford for your application, and it would have seen several mistakes and fixes in its development cycle, all of which you are bound to reproduce, along with your own few innovative bugs when you rewrite the entire thing for yourself.

You get to focus your attention on your application logic, rather than having to waste time with implementation details someone else has already worked so hard to take care of for you.

Epilogue

I’ve seen many good coders crash and burn when it comes to writing a real application that people are actually going to use. Getting an application design right the very first time is something that takes a great deal of skill, vision, and a whole lot of luck, and I’ve had the chance of knowing just one guy in all these years, who could.

Designs need to bear a close correlation with the problem they’re trying to solve, while being down to Earth, and addressing all the fine implementation details. Designs can make what might be very trivial tasks outrageously difficult, or even outright impossible. You need to keep the big picture in mind, while making sure that you make room for the grass-root level components that form the veins of your system.

Sad as it may seem, I learnt most of what I know today solely from mistakes, mine or otherwise. I guess that’s the only way to learn, in this business.

– Rugged Rat

The ACM-ICPC Experience

As this year’s ACM ICPC Regionals played out in front of us, our road to the ICPC world finals seemed to run into a dead end. Despite the failure, I feel obliged to put this one down in my blog, a permanent record of how and what happened, though I’m pretty sure I’m not going to forget any of the details any time soon.

For the uninitiated: The ACM ICPC is one of the most coveted programming competitions for college students. ACM stands for Association of Computing Machinery, and is the world’s largest educational and scientific computing society. ICPC is short for International Collegiate Programming Competition. The ICPC is open to contestants from all over the world who happen to be studying in colleges, during the prime of their algorithmic lives. There are 5 regions, Asia, Africa and the Middle East, Europe, North America and South Pacific. Contestants are to compete in teams of three, with a coach, and an optional reserve candidate, and take part in an online round, to qualify for the onsite regional finals. The top two to three teams from each region compete in the world finals.

Suren, Nutty and I had qualified to take part in the regional finals, to be held at Amrita Vishwa Vidyapeetham, Amrita University, Amritapuri Campus, Kollam, as team LRSL (Last Row of Sun Lab: something of a cult back in college). I don’t think I’d be speaking for myself when I say what followed were an amazing four days that left us with memories of a lifetime.

Day 1

We were supposed to check in at Amrita on Day 1. Nutty had made his way to campus by himself. Suren came over to my place in the morning, and we left for the college by train in the evening. Not having travelled along this route for a long time, I was quite excited at the prospect of a train ride through the beautiful green countryside of Kerala. The speed of the trains plying on this route adds to the fun.

We arrived at Karunagapalli Railway Station at around 6:45pm where a car was waiting for us. We hopped on, and made casual conversation with the volunteer who had come to pick us up, as we sped to the campus. None of us had ever been here before, and had no idea what to expect. We were met with a warm reception, a host of cheerful volunteers who made it clear they were there to help, and a college adorned with banners, balloons, and tapestry, all exuding the idea that something big was coming up, and something big certainly was.

We completed the registration process, and were handed a bag of goodies, a notebook, a pen, a bunch of brochures and texts related to the college and ICPC, and a lovely ICPC T-Shirt, and were then led away to our room.

The hostel we were meant to stay in was as good as a lodge. The door of our room bore an ICPC label that brandished our team name and institute. A comfortable room, furnished with sleek cupboards, tables and cots, clean mattresses, the softest pillows and long blankets you could wrap yourself in like a candy, and a bottle of water for each inmate, we seemed to have everything we ever wanted.

Day 2

Our first full day in the college, Suren and I took in the complete picture of what our hosts had done to the college for our visit. Majestic ACM ICPC banners proclaiming the battle of the brains that loomed in the near future livened up the hallways. The pillars bore balloons of blue, yellow and red. Twenty-five foot leaves of ICPC colors hung from a disk suspended in the middle of the quadrangle of the college’s main building. The quadrangle was further decorated with two foot dice, and two dozen B, Y and R balls.

We were given the official welcome in the traditional Keralite style, with a volunteer applying chandan, followed by a thalappoli (a path marked by beautiful girls wearing saris and holding oil lamps on either side) leading into the college main building, and panchavadyam (music using five different instruments, although I didn’t care to count) in the background.

Breakfast, lunch, evening snacks and dinner were served at the campus canteen, modified into a makeshift mess for the ICPC contestants. Food was exquisite, and I ate a whole day’s worth for each meal. They followed a buffet system, and never before had I seen such a variety of rich food on my plate during breakfast, or gone for thirds for lunch, or enjoyed a purely vegan dinner so as to fill myself up till my vision blurred.

We used to get idiappams, appams, uppuma etc. for breakfast, along with as many slices of bread as we pleased, with jam, and the best butter served as cubes, followed by a bowl of corn flakes with milk, and tea or coffee (poor Suren couldn’t have any of these, due to his hostilities with milk). Lunches were topped off by delicious curries and one variety of payasam every day. The tea alone was sufficient reason to show up for snacks at five. Dinners saw roti and either fried rice or pulao, with dal, gobi, paneer and mushroom dishes to go along, hardly leaving space in our tummies for dessert, mostly ice creams, fruit salads and juices. Fruits were served regularly with lunch and dinner.

We had two practice contests on Day 2, one in the morning, and the other later in the night, after supper. Practice contest problems were pretty simple, and quite rightly so: practice time is meant to get yourself used to the environment, and work out different specifications, such as how much memory and stack space your code is allowed, how many instructions the judge machine can run per second, what warnings are treated as errors, and what warnings are ignored, what libraries are allowed and so on. Both contests were supposed to have the same problems, so we went for just one, got all the specs we needed, and left after submitting both problems.

In the afternoon, we had a beach trip. The previous day, during the registration process, we were given the choice of either going to the beach, or playing in a variety of indoor games, such as chess, carroms, and badminton. We pretended to consider our options for a while, though we had telepathically debated the issue, and decided on the beach trip even before the question was complete. Beaches are always most fun when you have people your same age and intentions all around you. There were five teams from my college, so there was no lack of friends to make merry with. This beach was one of those remote not-commercialized-yet getaways we urban folk dream of. The water was pure, and the sands were free of the usual plastic and paper wastes we normally find at the most famous beaches around the country. Get wet we did, though I had to hold back a bit for fear of taking ill before the contest.

We also had the formal inauguration ceremony. Nothing unusual there, it was just a few speeches followed by a mohiniattam by a student of the host college. We got to look around and see all the big brains from around Asia gathered there. Among the people that caught my attention would be a bunch of students from Singapore, a coach from Kazakhstan that seemed to move around like a short circuited robot (although a lot of girls were tailing the guy the next couple of days, so I have something to be jealous of), and a funny looking girl from Bangalore (I think, my intelligence sources are questionable) that keeps spotting me every time I look at her (and this continued as a vicious circle till we left, me, looking at her to see if she’ll spot me again, and she, spotting me looking at her).

The Big Day

The contest was scheduled for 8:00am on the third day. We got up early, quite against tradition, freshened up and trotted off for breakfast. I was feeling the pressure then, struggling with my food and having second thoughts about the amount of sugar in the corn flakes. To make matters worse, we ran into The Great P, intimidating, as a God watching over a battle of mere mortals.

The contest environment was grand. Good computers with my favorite DELL keyboards, with Ubuntu 8, and with just two teams in every row, giving you sufficient space to move about to let out steam to keep your head from overheating. The computers for each team’s use were marked up by a small radio sized pyramid bearing the ICPC logo and the team name on it. Each time a team gets a problem right, a volunteer comes along and attaches a balloon to the pyramid, so that at any point of time, you could just look around to get an idea of how the other teams are dealing with the contest. The balloons would also be of the same color as the color code for the problem, so you can also see which problems are being solved the most, without looking at the ugly percentages in the statistics page. Of course, I was quite confused why the volunteers were giving us fewer balloons than everybody else, and needed Nutty’s help to figure it out.

Supposedly being the best coder (in terms of speed, correctness, etc., nothing to do with skill) in the team, I was given the responsibility of implementing the solutions my teammates came up with. I’m not sure whether I had wanted to do well, and I was worried if I could, or whether I was simply scared of making mistakes and letting my teammates down, but that’s exactly what I did.

I had a shaky start, having trouble implementing the easiest problem of the lot. After half an hour of toil, I finished the code, and submitted it, and thankfully got it right. We were in a good position then; even after what I consider one of my slowest and sloppiest pieces of work, it seems most teams submitted the problem after us, either because they were having the same kind of trouble, or because they saw the problem later.

I messed up our second problem with two wrong submissions, racking up 80 minutes of penalty time, before managing to get it right. I was getting up to speed: even with two wrongs, we were looking good amongst the other teams who got around to completing their second one eventually. Most of the other problems were tough, and they made the difference between the best and the rest. The top team got seven correct, while second, third and fourth managed six. We were down in twenty fifth, a good start at ICPC, but not good enough, at least in my view. All five teams from our college were separated by less than a dozen or so ranks. I was gloomy, and wasn’t very social, to say the least. I didn’t respond to chat all afternoon, though I’m not the least bit apologetic: my status message clearly said I wasn’t in the mood, except for the choicest few.

By evening, I was feeling better, and so was everyone else. We went for tea, and by the time we made it to the auditorium, the presentation ceremony had started. Luckily we got there before our team’s turn came, and we had a chance to go on stage and receive the certificates amidst a flurry of flashes and a steady applause from the crowd. I really appreciate that they took the trouble of presenting every team with certificates on stage. It made me feel a whole lot less of a loser.

We had a good dinner, and were asked to stay back for the official photo session. We sat on the soft green lawn discussing rarely-told stories about each of us: funny, weird, goofy, romantic and what not: geeks keep no secrets from fellow geeks. My senior, who had made it to ICPC as part of another team, and I discovered we had nurtured a crush on the same fellow competitor after getting there, a good looking mallu girl who sure could code, and were fighting over her. Everybody had something to talk about, and we quickly left our failures behind and were moving on already.

Day 4

Hospitality seems abundant at this college set in a village town. The fourth day saw us driving off on five buses on an excursion to Thenmala, a hill station in south eastern Kerala, one of the more recently discovered and exploited tourist spots, a plethora of awe inspiring landscapes, with a few monkeys thrown in.

The bus ride was fun, though not everyone would agree. I’m the kind that can sit in a cage on wheels peering outside for any amount of time without complaining. Most people were sleeping in the bus, because we had reported at 5:45am and started in another three quarters of an hour. The bus ride was a whole lot more fun once they woke up.

We stopped at the Lookout Point for breakfast: nothing like a breathtaking view of a vast expanse of forests endorsed by a long range of evergreen hills grayed by the slightest cover of mist to help digestion.

We climbed up what are called the Ambanaad Hills, if I remember the name right. The road was treacherous, with gutters, twists and turns making the bus feel like a raging bull in rodeo. The climb was so steep and the roads so narrow at parts that only two of the five buses could make it all the way up, and the other three stopped midway, and had to wait for the two to ferry all of their passengers the rest of the way batch by batch. The hairpins were so sharp that the buses couldn’t take them in one go. I was sitting at the very back, and wasn’t less than a little scared when I seemed to be hovering in mid air, as the buses backed up till their tires were dangerously close to the edge, so that they could make the turn.

The treacherous climb was well worth the boredom and scares as we saw when we came to our destination. We pulled up somewhere close to the top of a hill, and hiked up the rest of the way. We came across a tea plantation interspersed with spices like pepper. Most people were interested in this, although it was something I used to see in my backyard: being a local sure doesn’t help sightseeing. We saw several exotic plants on the way, the most memorable being one with red leaves, which, when seen from a distance, look like flowers. There were several rock faces that begged us to climb them, and several that looked out of the hill, and into the sea of green far down below, and the hills and the trees in the horizon, silhouetted against the dim white of a cloudy sky. I’m cutting this paragraph short for want of words.

We made our way back down to have lunch at a KTDC restaurant. There was a bus waiting for us. A few volunteers were already in it, and the other contestants made their way in. My college mates and I were the last to get there, so we were left with no seats. Seeing this, the staff from the host college started asking them to get down, so that we may take seats. After having leached off their hospitality for the past three days, we felt like rich little bastards throwing their weight around. We tried telling the staff that we were quite willing and able to stand for a while, but they were relentless. We even told the students that we really didn’t want them to vacate for us, and despite our sincerest efforts, they merely smiled politely and left the bus, saying it was no trouble at all. I could only think of what would have happened in a similar situation in a college like mine. The faculty would just stand around talking on their cell phones, order the students to get down once they had finished discussing their family matters, the students would have been quite unwilling to give up their hard earned seats, and at best, would’ve started trickling out sneering at the visitors. I realized I had written an All India examination, and after so much effort landed up in a place that treats virtues as vice, and holds no values dear.

After lunch, we visited the adventure zone, which had a lot of fun stuff to do, such as mountain biking, boating, shooting and river crossing. Shooting was fun, because I got to show up Suren, who was a reputed rifler, having gone to an NCC camp and everything. I made him wish he hadn’t given me advice about the calibration. River crossing was more of a pond crossing. I don’t think the water made any difference. The robotic Kazakh coaching darting across the river (pond) on a flying fox cheered up the ladies.

We returned to college after having snacks from the same KTDC restaurant. The driver we had for our bus was quite a Schumacher in the making. We were scheduled to get back to college by 9:45 pm, but he made it by 8:45 and that after taking some five minutes out to refuel. We just had enough energy left to have dinner, pack up and go to sleep. Suren had left that night itself, and I, the next day morning, leaving Nutty to stay on till the evening.

A Word of Thanks (well, two of them)

I really appreciate the amount of toil our hosts had undergone to put up a great show. Being a Keralite, I’m no stranger to the widely acclaimed Malayalee Hospitality, having been on either end of it myself, but what we saw there was really something else. It felt really nice to walk up to a help desk, and find that the volunteer there actually cares about your predicament, and didn’t think twice before going out of his/her way to tell you what you wanted to know, or get you what you wanted to have. To see that the students were doing what they did of their own accord, as exemplified by the bus drama, and not as a result of threats from the staff was quite inspiring.

Credit must go to my teammates for putting up with a lifeless git like me. I learnt a lot from the two over the last few months when we were preparing, although, apparently, not quite enough. I began to see the pros in Suren’s use of macros to reduce code size and subtle errors in the process. Nutty’s resilience with problems and his command over math are things you wouldn’t fail to notice. I can’t help but feel more than partly at fault for the bad contest. I broke under the pressure I had mounted on myself.

The Epilogue

The four days have left quite a mark. I saw how many people from different parts of the continent are so much better than me at what I have always tried to excel at. I saw how complacent I had become, when there was so much more to do and so much more to be. I saw how different, and how much healthier the environment at what one might consider a lesser college could be. I saw how much of my own self I had forgotten in the last two years and a half since I got shipped off to college.

Now, my goals seem well defined, my path well etched out. I saw the reality that certain people’s ill-advised or ill-meaning flattery was blinding me to, and it turns out it’s time to turn a blind eye to them. It’s time to shake off meaningless responsibilities that I never had to break a sweat to earn, and that I earn nothing from, save for a few half witted critics and around the same number of imbecilic enemies. It’s time I realized my full potential.

This marks the end of an old beginning.

How to code

Well, I think this post might start off my tech-blogging spree. That’s not to say much about the original spree. Three posts in two years’ time doesn’t quite fit the definition of one.

This one goes out to all of you out there who have just done 12th standard or typical first year B Tech C or C++ and, in my opinion, have a lot of things to unlearn. Some of you may find the content in this post shocking, some even offensive, but hey, I present facts as they are, and I didn’t write the standards documents.

Yes, there are standards documents for C and C++, very detailed guidelines regarding how to write clean, portable C and C++ code. Download them for free from http://www.open-std.org/.

Before starting, I’d also like to make a few disclaimers:

  • I’ve tried to keep the content of this post as technically accurate and unambiguous as I could help it. Wherever appropriate, I’ve cited references, and most of the things I’ve cared to mention here are probably explained in more detail at the references.
  • Being a C++ programmer myself, some of the content in this post might be C++ specific. Though the languages share many things in common, there are many subtle differences. I’ve made efforts to highlight these differences wherever necessary. On the other hand, having used C++ most of my life, when it comes to C, there might actually be differences that I don’t know about. It’s up to the reader to verify the authenticity of such content in this post. (http://www.c-faq.com/ might come in handy.)
  • If you find some errors in this post, please post them as comments. I’ll do my best to verify and post the corrections here as early as possible.

The order in which topics follow is quite random. Most of them are unrelated, and you can probably read the ones that intrigue you the most.

Important terms:

I’m copy-pasting a few definitions with examples from the standards documents here.

Undefined Behavior:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

For example, the behavior of your code on integer overflow, or the behavior of constructs like a = a++; are undefined.

Undefined behavior doesn’t mean that your code wouldn’t compile. It simply means that the standards specify no requirements on the behavior of your code. For all you know, your program might start baking cookies.

This is probably a good time to point out that just because your code compiles without errors, it doesn’t mean the code is absolutely right. Going a step further, protests like, “a = a++; seems to be working fine for me,” are meaningless, and are equivalent to saying, “I was playing soccer the other day, and threw the ball into the goal post with my hands, and it worked fine!”. That’s just not the way the game is played.

Try this page, for more information: http://www.eskimo.com/~scs/readings/undef.950311.html

Unspecified Behavior:

use of an unspecified value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance.

For example, the order in which arguments are evaluated in a function call.

Implementation Defined Behavior:

unspecified behavior where each implementation documents how the choice is made

An example would be the propagation of the high-order (most significant) bit when a signed integer is shifted right.

Locale-specific Behavior:

behavior that depends on local conventions of nationality, culture, and language that each implementation documents

Example, whether islower() returns true for characters other than a-z is locale-specific.

Further, as far as C or C++ is concerned, the terms byte and char are, for the most part, interchangeable. Consider the following definitions as per the standards:

  • sizeof returns the size of an object, or a type in bytes.
  • A char is a single-byte character, this means that sizeof(char) is 1 by definition.
  • A byte is an addressable unit of data storage large enough to hold any member of the basic character set of the execution environment.

Putting these pieces together tells you that a byte needn’t be 8 bits anymore. In fact, if I made a standards-compliant C compiler that works with Unicode, rather than ASCII, my chars would need 16 bits. But sizeof(char) is 1, and sizeof returns size in bytes. That means, for my implementation, a byte is 16 bits of data, not 8 bits. The number of bits in a byte is specified by the macro CHAR_BIT found in limits.h (climits, in C++).

Good code should try not to rely on the number of bits in a byte being 8. In most cases, you should be able to do without such assumptions. Use the CHAR_BIT macro if absolutely necessary.

Let’s begin, then.

Why main shouldn’t be void:

This is definitely going to be new to somebody who hasn’t seen books other than Kanetkar’s or Sumita Arora’s. void main() is wrong!

The explanation given in these books for such usage is something like, “we do not wish to return any values from main, so we mark it as void.” But main() isn’t any other function, now, is it?

As far as the standards go, main must return int, and only int: (this is with reference to a hosted environment: your C or C++ program runs with the help of an operating system)

5.1.2.2.1, C

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

 int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

 int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

The standards clearly specify two valid ways to define main, and they both return int. (And or equivalent simply means that int may be substituted by some other name typedefed to int, or that char *argv[] may be replaced by char **argv and so on.) In fact, a program that defines main in a way not equivalent to either of these specified forms invokes Undefined Behavior.

The question is, where does this return value go? Well, the value returned by main goes to the calling system, something that invoked your application. In many cases, this might be the operating system. It may also be some applications written by other programmers like you. The return value of main is a handy way to test whether your program executed correctly, a lot handier than having to look at the error stream of your application, and parsing it to figure out if something went wrong. Generally, a return value of 0 indicates success, and a non-zero value would stand for different error codes.

As an example, let’s say I’m making an installer, and you’ve already made an application to unpack archives. I can simply run your application with necessary arguments, and check the return value to see if your application extracted my archive correctly.

Sizes of structs:

Consider a struct defined as below:

 struct MyStruct {
  int a;
  char ch;
 };

If you’ve learnt that sizeof(MyStruct) would yield 3, it’s wrong. For one thing, the size of an integer is specified to simply be the natural size suggested by the architecture of the execution environment. This means that an integer can be 2 bytes or 4 bytes, or how many ever bytes as the implementation sees fit.

Now, is sizeof(MyStruct) == sizeof(int) + 1?

The answer is still no, thanks to something called structure padding. Compilers are free to pad structures with excess bits (or bytes) for optimization purposes. Generally, structure padding is done in a way as to align the objects with words of the system. On a 32 bit system, for example, this kind of padding would leave structure sizes to be a multiple of four bytes. Hence, the above struct can very well weigh in at 8 bytes.

See the wikipedia page that deals with this: http://en.wikipedia.org/wiki/Data_structure_alignment

http://www.goingware.com/tips/getting-started/alignment.html might prove to be a good read too.

No more conio.h:

There is no such thing as a conio.h as far as standard C or C++ goes. Or a graphics.h. DOS mode graphics are obsolete, and ought to be done away with.

No more clrscr(), either. Though system(“cls”); and system(“clear”); may prove to be alternatives.

But do you really want to clear the screen? On a terminal like Windows’, clearing the screen practically wipes out everything that the user had on his terminal. There is no way to retrieve the information (as far as I know). What if he’d spent the last few decades calculating the first billion gazillion digits of PI? (in which case, he ought to have redirected the output to a file, but, hey, what the heck? This is just an example. Besides, I doubt if a Windows machine could have such uptimes.) Would you wash it all away without even warning the chap? I wouldn’t.

Short circuit evaluation:

The logical and (&& ) and or (||) operators operate by what’s known as short circuit evaluation. (The last time I checked, Balagurusamy didn’t know about this.)

What this means is that they guarantee left to right evaluation of operands, plus:

  • The && operator evaluates the expression on the right hand side only if the left hand side evaluated to true.
  • The || operator evaluates the expression on the right hand side only if the left hand side evaluated to false.

Think of it as a kind of optimization. If the left hand side of an && is false, the result is going to be false, so there’s no point in evaluating the right hand side (who knows how long a function call might take, eh?). Same kinda thing goes for ||.

Besides possibly saving some time, there are a few notable consequences to this.

For example, thanks to short circuit evaluation, expressions like:

 b != 0 && a / b < 100
 p != NULL && p->value == 50

and so on become inherently safe.

You can also use handy expressions like:

strcmp(str1, str2) || cout << “Strings are equal!” << endl;

(I’d consider this a little difficult to read, especially for people who don’t know what short circuit evaluation is, and avoid this as far as possible.)

As another example, try:

 int i = -1, j = 5;
 int k = ++i && ++j;

Does j get incremented? No.

(C++ only) structs can have member functions:

As far as c++ goes, structs and classes are the exact same thing. structs have public visibility by default, while classes have private. Other than this, possibly small, difference, you can do anything with structs that you can do with classes. Add member functions, inherit them, anything!

Why a = a++ is undefined:

This was an example I used earlier in the context of Undefined Behavior. Perhaps I can elaborate a bit more on why this construct invokes Undefined Behavior in this section.

The standards clearly say:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

This pretty much gets all different combinations like

 a = a++;
 a = a++ * ++a;
 A[a] = a++;

and so on out of the way for good.

To understand the statement, however, we need to know about side effects and sequence points.

Side effects are basically changes of the state of the execution environment, like, for example, modifying an object, modifying a file, etc., or calling functions or using operators that involve these kinds of operations. For example, in a simple a++, the increment is a side effect.

Sequence points are points in the execution sequence where all side effects of previous evaluations have taken place, and no side effects of subsequent evaluations will have taken place. The end of a full expression, for example, denotes a sequence point.

In a = a++; consider the two consecutive sequence points, one immediately before and one immediately after the statement. You’re modifying a with an increment, as well as trying to assign a new value to a using the = operator. Two modifications between two consecutive sequence points, undefined behavior.

To be a bit plainer, just know that the exact point of time when the ++ increments a is not specified. It is guaranteed that the increment will occur before the next statement, and that’s about it. This leaves several possible ways in which the expression can be evaluated, all of which are completely valid, as far as the standards are concerned, two of which might be:

  1. Perform the assignment, and then the increment. In this case, the value of a gets incremented by 1.
  2. Store the original value of a in a temporary variable, perform the increment, and then assign the value in the temporary variable back into a. In this case, the value of a remains unchanged after the expression.

This kind of a discussion itself is pointless, but I’m including it here for those of you who need stout examples.

Why fflush shouldn’t be used on stdin:

 int fflush(FILE *stream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

This simply rules out any possibility of using fflush on input streams. And for good reason. What does flushing an input stream mean, anyway? Does it make sense? Flushing refers to writing out all the left over contents in a buffer. Why would you ‘write out’ contents in an input stream?

To clear the input stream, use a function similar to the one shown below:

 void clear_stdin() {
  char ch;
  while((ch = getchar()) != '\n' && ch != EOF);
 }

More intelligent use of scanf might save you the hazzle of having to clear the input stream at all. See http://www.cplusplus.com/reference/clibrary/cstdio/scanf.html and pay close attention to the section named ‘Whitespace character’.

I can access private variables with pointers!:

Such a statement simply betrays all the misconceptions you have about ‘data hiding’.

Firstly, an object is a physical entity that resides on your computer’s memory, so yes, a little bit of low level code can tell you what’s stored in it. So you’re working no magic here.

Secondly, when we say ‘data hiding’, we simply mean that keeping data members in private sections of your classes will save them from being altered accidentally. Keeping data private gives your class a certain level of confidence about the different states it might find the data in at any point of time, because after all, it’s just the class that can meddle with the data right? One needs to understand that such ‘data hiding’ is simply a kind of contract that you make, which details what are the right ways to work with a class, and what aren’t. It’s up to the users of the class to follow these guidelines while working with objects of the class.

What are string literals?

A double quoted string lying around in the code is a string literal.

For example, in cout << “ruggedrat” << endl; “ruggedrat” is a string literal.

What are the consequences?

Try

 char *str = “ruggedrat”;

Now, str is a pointer to a literal. This means that any attempts to modify ruggedrat to ruggedbat, like, say, str[6] = ‘b’; invokes undefined behavior.

str is a const char * and you’d do well to declare it that way too. To create a mutable string, use one of the following:

 char str[10] = “ruggedrat”;
 char str[] = “ruggedrat”;
 char str[10]; strcpy(str, “ruggedrat”);

or some equivalent.

I think that should do for now. There are a lot of other issues I could have taken up in this post, but my aim is neither to create a complete C++ reference here, nor to break the longest blog post record. This post is just aimed at directing people to good C and C++ coding practices, and showing where to find more information on them.

I’d conclude by saying that the compiler is just an executable. It’s not a foe you’re supposed to overcome. In fact, you’d do well at programming once you realize it’s quite the other way around. Efforts at cheating a compiler beats the purpose of having one, and better programmers would see them merely as a vulgar display of your ineptitude at using the language.

Throw away outdated books, and delete antique compilers. Get the standards documents, and start writing clean applications.

– A Rugged Rat exhausted from all the typing.

P.S. A few neat FAQs to learn from:

Encored!

Over the weekend, I was informed that I was to become part of Delta (™, I think, or maybe it was ®) Core, the Central Webteam1 of the college, the elite2 group that takes care of NIT-Trichy’s official website, and all their LAN services, among other things.

“Hey, RR, we decided next year’s core. It’ll be you and Bharath,” said the head honcho3. “Bhattu will be so surprised!” he added, somewhat shamelessly.

Sure he will. And I’m just a robot. I won’t be surprised. We robots are never surprised. At best, we might throw an exception.

Not extremely sure what to say to what might be construed a cold reception, I just nodded, and let out a squeaky, stifled, ‘yay’, which the head honcho pretended not to hear. Perhaps, I hoped, the casual welcome was designed simply to not throw me off my working spree. Having spent a really long year working on a Content Management System4, during the course of which, PHP and MySQL had threatened to become second nature, it was clear I’d go on a sabbatical at the faintest knock of much anticipated opportunity. A parade and a party to celebrate the occasion, I hoped he feared, might just do the trick.

Having gotten into the Central Webteam in such spectacular fashion, the next question was, what do I do once I’m in there? What’s in store for the next couple of years?

Those astrology websites proved to be of little use to this end. They were more worried about my relationships and finances than I was. Despite the numerous good things they said about me and promised would happen to me, neither have I had a relationship until now, nor have I touched a penny that wasn’t eventually spent on food.

A little digging showed that Delta Core happens to be the secret-keepers of the Octa LAN, for those of you who are Harry Potter fans. They hold the passwords to pretty much all of the servers lying around, and most importantly, the lovely Mac kept in one corner of Sun Lab that gracefully glints in the sunlight coming through the smoked windows, and even plays music.

One thing’s for certain, more coding, lots of decision-making, and several night-outs5 await, and we robots don’t complain. At best, we can throw an exception.

Rugged Robot

1 Central Webteam: The Central Webteam of NIT-T. More information here: http://www.nitt.edu/home/students/clubsnassocs/computing/delta/webteam/

2 Elite: I like to call it that. Delta Core means a lot of work, and we don’t get paid. I gotta have something to hang on to.

3 Head honcho: Find a more detailed description here: http://parijat-cybertechie.blogspot.com/2008/02/adventure-that-is-life.html (paragraph 6)

4 Content Management System: The Pragyan (™, I think, or maybe it was ®) CMS. Woo hoo! It’s on SourceForge: http://sourceforge.net/projects/pragyan/

5 Night-outs: A sleepless night; generally spent outside one’s hostel, in most cases, at the Octagon6.

6 Octagon: NIT-Trichy’s Computer Center7.

7 Ok, enough, already!

What’s in a Name?

Since in my first post, I’d talked about myself and my interests (maybe without the trailing s), and in a way, given sufficient excuse for my existence, I think it’s time I looked at the blog, from a wider perspective, why I made one, what I’m planning to do with it, and most importantly, why it’s called what it’s called.

Names are, in a way, meant to reflect some aspect about the named, if not describe it in its entirety. This, however, does not mean that a guy named Goodman is a good man, and if, by any chance, he is, we must be inclined to accept that that might be purely coincidental. This observation perhaps directly follows from the fact that not much can be conceived about a person’s attitudes, behavior, manners, likes, dislikes, or anything else, as for that matter, when the person is an infant, or hasn’t been born yet, which is when most names are bestowed on their owners.

On the other hand, when it comes to naming things we create, we ought to pick something descriptive, lest we should look back at a later date, and wonder along the lines of, “what automobiles use carnot’s engine?” Wouldn’t it have been awkward if bicycles were called bags and vice versa? In fact, naming is so important that programmers like myself are advised to stick to guidelines. A variable named bWhetherIShouldHeatTheWaterAndThenPutInTheTeaPowderOrNot makes a whole lot more sense than an a or an i or an n.

So why “Rugged Rat”? I must say, I had a bit of thinking to do before I could write this one. I think a look at the kind of conversations I find myself in every now and then should throw some light on this one.

A typical conversation in the couch in front of the TV:

“Hey, bro, I think I need to do something about my physical condition.”
“What condition?”
“My point exactly…”

Let’s say a potential girlfriend gets a birthday wish from me at 12.00 am sharp. The next day’s conversation would go something like:

“Wow, RR, that was so romantic. I love you!”
“Well, you should… Do you know how much trouble I went through to make that client and schedule it to deliver your greeting?”
“You mean it wasn’t you? Why you… I hate you! I don’t wanna see you anymore!”

That, I guess, should explain “Rugged Rat”: I’m a rat for having been at one end of each of those kinds of conversations, and I’m rugged ’coz I have been at one end of those kinds of conversations. However, in all sincerity, the name has nothing to do with any of it: it was, and still is, just a variation of the name “rugrats” 😛

Why I’m a Computer Geek!

What are you passionate about?

Movies? Are you the kind that, given the name of a movie, or maybe even its initials, starts reciting the entire cast and crew, the result of whose sweat and blood it is that you see on the screen? (I am, though I generally start with the actresses)

Soccer? Has never a club existed that managed to elude your scrutiny?

Music? Well, that’s been around ever since the caveman went about beating monkeys with a stick.

Quite frankly, if you’ve ever looked at somebody, and wondered why he or she is crazy about something, well, don’t. Everybody has their passions, and if you were thinking, “no, I don’t,” well, you’re the freak here.

And if you’ve ever looked at yourself and asked why you were crazy about something, I hope you’ve found some good enough answers.

I’m a programmer, and I make my living, oh wait, I don’t, I’m still in college. The one thing that drew me to computers so badly was that, well, the small box you keep on your desk, or on your lap, or even in your pockets packs more punch than world history, or geography, or perhaps both.

How does a package of circuitry, a maze of conductors dotted with diodes and transistors, a weird looking PCB that’s smart enough (or dumb enough) to recognize (just) 0s and 1s let you listen to music, watch a video clip and check the latest EPL results all at the same time? How do you get to read your mail, or print your resume? What makes your favourite games come to life? (If you answered, a GeForce, I’m with you, buddy!)

The answer lies in software (I’m sure your GeForce came with a CD). It’s those tit-bits of programming marvel that adds that sparkle to your otherwise worthless heap of hardware, that acts as an interface between man and machine (power extreme!*). Trying not to sound too technical, programming is that art that lets those gifted human beings communicate with a computer. Sounds wacky, but hey, you wouldn’t be here reading this without them. Any kind of (useful 😉 ) communication with your hardware needs to be done through software. Everything you see on your monitor is due to software. And well, like any energetic youth on the lookout for opportunities, I grabbed it by the throat, and now I’m called a programmer. I daresay the venture has taught me a thing or two about how puters function, among other things.

However, as is the case with many professions, being a programmer is one thing, being a good programmer is another. The learning process never ends, and the strife to become better never ceases. Every day somebody or the other teaches you something new. It’s this very fact that keeps things interesting.

Anyway, I think this’s enough on me. I’ll be keeping this blog alive with more (and much better, I promise) posts.

– a Rugged Rat starting off his blogging streak.

* The phrase “Becoming man and machine, power extreme” goes way back. Ever seen The Centurions? Consult the omniscient wikipedia: http://en.wikipedia.org/wiki/The_Centurions_(TV_series)