Programming Discipline!
I was reading the article “Destructors Considered Harmful” on DrDobbs by Andrew Koenig. Generally I agree with Andrew’s views on various programming topics but I thought I should just write down my thoughts on this particular article. I have a number of agreements and disagreements on certain points. One point that specifically sticks out especially with the new generation of dumb-down languages is that it looses the traditional power of kind of raw functionality that you can churn out from a piece of code. Of course we can all be happy with a walled garden approach if we are only implementing some business logic which does not need to actually utilize the full power of the underlying HW but instead rely on language/OS supported runtimes to do the required optimizations for them. But what happens when we start arguing against a programming concept/construct just because it requires some basic programming discipline and understanding of basic principles before one actually needs to start using it?
One such typical argumentation occurs with GoTo statements. And as mentioned in Dijkstra’s paper as well as that article, GoTo’s definitely create a branching pattern which will be hard to follow, and now comes the important part “If they are used haphazardly and just as a means of executing particular lines of code without taking into consideration what the state of the program might be!”. A structured language definitely has no place for GoTo. But what about assembly language? Just rejecting GoTo as a general programming construct is not a sensible way going forward. Instead, the programming discipline should be taught on how to understand the program state and use proper branching constructs. GoTo’s are essentially a boon when I am writing boot loaders or doing POST routine implementation. A failed device initialization or return code will not stop the POST from executing.
The article goes forward stating that GoTo affects our ability to think about programs! I really don’t agree there. Before I compile program or even before I add a variable, I follow certain strict rules. I will try to jot them down below which falls into the discipline category. If people follow that, everything will fall in order more or less.
Checklist for declaring/using variables:
- Why is the variable needed?
- What kind of variable is needed?
- Does it have to be on the stack or heap?
- What is the lifetime of the variable?
- What is the typical memory allocated on a particular architecture for that variable?
- Will that variable need more memory than it would be allocated?
- Is it necessary to consider endian-ness while evaluating the variable?
- What are the bounds for the data being help by variable?
- Does the variable need validation before evaluation?
- Is it an alias for holding other variables or memory addresses (in other words, is it a pointer)?
Once you answer the above questions, one very well understands why the variable is needed and how it should be used. Why am I talking about variables now? Because branching very much depends on the state of a variable or memory location (register, etc.). The author in the article also talks against pointers. Yes, pointers create problems when you don’t follow certain rules. I will try to put down my points using simple statements with the below C examples.
| Prog1: | Prog2: |
#define CONST_SIZE 10
…
int n=5;
char ptr[CONST_SIZE];
…
while(n>0) {
… // Do some logic implementation here // …
n-=1;
}
…
|
#define CONST_SIZE 10
…
int n=5;
char *ptr = (char *) malloc(sizeof(char)*CONST_SIZE);
…
while(n>0) {
memset(ptr, 0, CONST_SIZE);
…// Do some logic implementation here // …
n-=1;
}
free(ptr);
ptr=null;
|
Most of the newbies that I see would use the programming construct on the left and not on the right. And believe me, even professionals do it simply because we don’t follow certain programming guidelines. Prog1 has advantages but is limiting in terms of scalability. Since the memory is allocated on stack, your code will simply be a bottleneck if you increase the CONST_SIZE. On the other hand, if this particular function is called multiple times or is recursive, it will lead to stack overflow and even end-up fragmenting the stack. Prog2 is much more dynamic and scalable. Increase in CONST_SIZE will not be an issue and it can even be passed as a dynamic parameter to a function in future versions if needed. The best part is that we reduce the stack usage and re-use the same memory locations during the whole run of the function.
Of course if some programmer ends up messing with ptr without storing the initial location in another variable, he will end up with the problems that Andrew is pointing to especially “pointer exceptions pointing to invalid memory locations”. But instead of saying pointers are bad, why not say that pointer manipulations are bad without storing the initial memory address location. All the reasons he has mentioned in the article happens just because a programmer is inefficient in his use of pointers.
The rest of the article than goes on comparing pointers to labels in GoTos. That I would say is absolute BS. First of all, labels in GoTo statements are “labels” or entry points to code fragments. i.e. they are addresses. Secondly, pointers are variables pointing to memory locations. i.e. they are not entry points to code fragments. Andrew philosophically tries to confuse basic constructs to prove his case.
A look at page 2 in the article, one immediately notices the fallacy of his arguments. Now he moves into C++ domains but let me try to prove why I disagree with him. Firstly he is not following the rules for using pointers. i.e. pointer validation before assignment is an important aspects. Most of the bugs arise because of no/improper pointer validation. Ownership of variable is an important aspect. Even in C++, the scope, extent and evaluation of the variable needs to be thought of. One important rule to remember is, “If your code is not owning the memory i.e. your variable has only been assigned the value and has not been passed the ownership, then you don’t own the memory!“
The code that he has written will not even pass my basic code review test. In the constructor for ThingHandle, he is simply assigning the variable to the pointer tp. i.e. he is simply assigning the value but not passing the ownership. And in the destructor, he is assuming ownership of memory location and trying to free it. Of course it would fail but not because pointers are bad in nature or destructor are stupid, it is only because some guy didn’t follow the proper coding discipline. He writes that he is encapsulating “memory allocation” but in the code fragment he shows, he is not encapsulating “memory allocation”!
All the other statements after that falls down as a pack of cards. The errors he points out only happens because somebody has messed up with the concept of ownership and data encapsulation. And then he goes on to state the analogy behind GoTo and destructors! And I say again, labels have to be unique and pointers can point to the same memory location. So his last paragraph is nothing but pure BS. And on page 3, he advises to use shared_ptr which I agree we should but I don’t agree with the case that has been build up by Andrew to push for shared_ptr. I would have more approved the statements if he had made it WRT inheritance (especially multiple) and tried to base the facts on relationship between objects.
In any case, programming disciple is a must and people should be made about possible pitfalls of using certain programming constructs instead of just telling them that it is bad to use. Programming guidelines, checklist and deep knowledge of the language constructs as well as knowledge about how a compiler will work will not only help us get better code but will also help us write code with lesser bugs. I have seen many c#/java programmers who lack understanding of basic concepts simply because they are not present in the language and they haven’t been taught to deal with it. I personally feel that the rise in bloat is because of programmers not understanding a few simple and basic constructs.
In my next article, I will point out to some coding mistakes that I have seen in professional real-time code!
Review – Prodigy 3D Black 3D Media Player
The Samsung 3D PS50C680 is a very good TV but misses on some features of being a fully smart TV though it is a Series 6 TV. I have searched quite a few websites for information on how to change the FW and get it upgraded with a similar model C700 or something but haven’t found confirmed results. Again, there is a huge risk of bricking the TV so I am a bit hesitant at this point in time to take such a risk. So the next move was to get a small smart media player or IPTV box which provides me with the smart capabilities. After going through a lot of dilemma on whether buying a Boxee box or IOMega TV, I settled on Prodigy 3D black because of only 3 reasons:
- It was cheaper by 200 SEK compared to Boxee box or IOMega TV
- It boasted of more features then the other two
- It was featuring itself as the first 3D media player and it had Android enabled
When I went through the box it had a lot of nice pictures and a lot of stuff written on it. Of course I didn’t like the remote that was shown, but I thought that the features listed could overcome that defect. I read the HW description and was not that impressed by the stuff in there. It has a Via 600MHz processor with 750MB of RAM which didn’t impress me as much. And the reviews on other websites besides the prodigy ones were not that impressive either.
But I took my changes and got the Prodigy black. And now starts my rant on how stupid and senseless that product is. I took it out of the box and was not impressed by the size at all. I plugged it into the TV with the HDMI port and started it up. The startup was painstakingly slow. But expecting something better, I was still a little enthusiastic. Fired up settings and connected it to my WiFi. It connected properly but there was no support for automatic data-time sync. They have that function executed at startup before connecting to the internet. On the UI, there was no feasible way of changing the dates.
Anyways, I continued to the Youtube widget to play some songs. It was painstakingly slow to type in with the onscreen keyboard and the stupid remote. I got a listing of videos and selected one of them. To my surprise I got a brief message that the video could not be loaded and it skipped to the next one in the search list. After skipping about 5 of the videos, it played one. I restarted the unit and tried again with the same results. This was the first blow I had on the device’s capabilities. I tried with a 3D movie which ran like shit. I tried to bring up Android and it ran once every 5 launches.
I then tried to upgrade the FW and it busted 2 of my USB sticks before taking in the FW from the 3rd one. This was the final blow that pissed me off. So after my close brush-up with a stupid product that was not even worth 100 SEK (I think the byteonnet of 100SEK is much better than this stupid black box which cannot even stream properly). The next thing I did was pack it up and give it back to the shop. The shop guy was not surprised since all the boxes that he had sold ended up being returned. I trust a Chinese guy more on alibaba than the extreme prodigy boxes.
So my final advice to anybody who is looking for a smart media player, DON’T BUY ONE! I would much better go for an HTPC or an EEBOX or something like that including a Linux based IPTV player which is much better than the media players.
Enough of my rant and I have taken out my frustration so “Peace out”…
Configure “Delegate” as a Forward Proxy
Delegate is a very simple and nice proxy which can be configured into many different kind of proxies depending on the use-case you are trying to implement. Best of all, it is open source i.e. free and works across various operating systems including our most hated Microsoft Windows platforms. But before I start to write out on the solution, I will write a bit about the problem I was trying to solve.
As you probably know from this article, my company has implemented a simple but stupid form of authentication i.e. HTTP Basic Authentication, for accessing the internet from behind company servers. The problem with that are manifolds when considering security like transmissions of username:password combination using only a Base64 encoding in request headers, etc. But the biggest problem as a legit user is the browsers popping up an “Enter your username and password” dialog everytime a new browser instance is opened. And all other programs which do not support HTTP Basic authentication or which only supported connection with a proxy did not work. The good part was that browsers were able to save the username password combination and all you had to do was press “ENTER” when such a box showed up. Of course when I changed my login password, it was a real mess.
Also my ubuntu running in Virtual Box was not able to access the internet. A simple solution in ubuntu was to explicitly set the http_proxy environment variable to http://username:password@proxy-server-address:port/ the problem with that being that your password should not have an “@” symbol. As you probably have guessed, I use secure passwords and do have a lot of weird characters in my password including “@” symbols. So that trick does not work for me. Hence I modified the cntlm proxy to support HTTP Basic authentication. This of course did not work with Windows since I have to re-compile and use the totally messy cygwin libraries. Besides taking a lot of space on my windows system, it also creates problems with my mingw installation. Anyways, so I lived in Windows with the stupid pop-ups but my Linux VM was working great.
All was well when our IT department suddenly thought that they would still use the HTTP Basic authentication but instead of asking that as a HTTP AUTH request in the http request header, they will simply ask it through a web interface (Smart eh!
). Now instead of getting a browser based popup, I used to get an ASP page which asked for my username and after clicking submit, it took me to another ASP page which asked for password. After entering both of them, I was allowed to browse. I guess they have a cookie stored in my browser and the authentication or proxy server is now adding my HTTP AUTH credentials based on the cookie stored. Well, I don’t know why people implement systems which are pain in the ass. I haven’t checked out but I am pretty sure that the cookie stores my credentials without any encryption (whoops!) or for a better sake I maybe wrong.
In any case, I was so tired of doing this just for 3 days, that I decided to see if I can install a local proxy and bypass the stupid authentication process. I positively did not want to use Apache for it since it is huge, messy and too complex for such a task. So I thought of using either nginx or Delegate. nginx started out pretty fine but since I cannot deactivate caching, I was not able to put in the proper configuration. So I switched over to Delegate and voila, no more pain in the ass entering username password stuff on two different ASP pages every morning/with every browser. I also do not need to change any settings in any programs when I change my password, etc. It took me a bit of time to do this since there is virtually no information on how to setup Delegate as a forwarding proxy, I thought maybe I can share my experiences with you.
So enough of bla-bla, lets get on with the (not) dirty work. First of all, download the latest Delegate server from the site. I use version 9.9.7, so if things don’t work out for you, try with this version. Extract the zip file to your root folder inside Delegate directory. Goto the bin directory and create a new batch file. Write the following in there:
dg9_9_7.exe -Plocalhost:80/udp SERVER=http ADMIN=naresh@localhost PROXY=proxyServer:proxyPort MYAUTH=username:password REMITTABLE="http,https/443,gopher,ftp,wais,udp,tcp" CACHE=no
Save the batch file to whatever you want in the same directory. Now all you need to do my friend is double click the bat file. It will create a service in Windows and set it up to start automatically at system boot. Just keep pressing “ENTER” to all the questions this bat file asks. If you are using Windows Vista or later, right click on the batch file and run it as an administrator.
Now go to your browser/system settings and make your settings point to localhost in the server address and port 80. Voila, no more annoying pages where you have to enter your username and password day-in and day-out again.
If this method works for you, like this post. Leave your comment if it doesn’t. Also if someone is feeling like it, can you please re-compile my modifications to cntlm for Windows?
Piss out till I see you again…
First day in India – 2nd Dec 2011
I decided to go to India after 2 years and landed in India on 2nd December 2011. A lot of things have changed since I last visited India in 2009. The first things I noticed was the people, lots and lots of them. Even my baby was a bit upset and frightened to see so many people going along their own business and the constant hustling with a steady noise stream. The good part was that things were moving quickly. Of course all the paper work to be done when landing in India is a pain in the a**. I filled up all the forms with a green colored gel pen. When I reached the immigration counter, I was asked to fill up the forms again using either a black or blue pen. And nowhere was it written that green ink was not accepted. Anyways, I had to waste another 20 minutes filling up those stupid forms.
I again had to stand in the queue. We were really very tired after the long journey. I had allowed a lot of people to pass by me since I was filling up the forms. Now I asked the people to return the favor but instead of helping me, everybody wanted me to get back in the long line. And then there was a pakistani diplomat who was creating a lot of fuss at the immigration counter. Luckily a good man allowed me in the queue. Once out of the immigration, we rushed towards the belt. And guess what, 3 international flight luggage was being deployed on the same small belt.
There was chaos everywhere. The number of trolleys on the airport was not enough to cater to the number of people who were expecting their luggage. Also there were quite a few people who were asking for money in exchange of allowing to us a trolley. Finally after waiting for 10 minutes and quite some searching, I was able to get a trolley with a broken wheel. I got my luggage and then started the arduous journey of going out towards customs exit and then to the Mumbai domestic airport. At the customs screening, there was a long queue again. Fortunately the customs inspector present was a good guy and after some initial questions, I was allowed to go through without any screening. I reached the domestic transfer terminal. A bus was being run to transfer the passengers from the terminal.
When the bus arrived, people rushed passed me and went into the bus. All rules of queue were broken even by non-Indians. I was able to get onto the next bus but not peacefully. I had to hit a guy in the leg to get my luggage onto the bus. He was the one who broke the queue and was trying to get ahead of me. All the heat was making me sweat. At the domestic terminal, I went to the Jet airways counter to get my tickets. I don’t know if this was intentional but there were calculating my weight in a manner which showed excess baggage of almost 40KGs. I asked them to do it again and then realized that the helper boy used to put his leg on the weighing scale while weighing so excess weight was recorded. I complained and finally the excess weight was 8KGs. Even though I had nothing in my hand luggage, I was asked to pay for the excess check-in or else carry the luggage myself into the cabin. Finally I coughed up the money and we were expecting our flight.
The worst part was not over yet. Our flight was delayed by more then 4 hours. I finally was able to board the flight at around 1300 hrs. I reached Baroda at 1400 hrs. It took us 10 hrs to reach from Copenhagen to Mumbai and it took the same amount of time for us to reach from Mumbai to Baroda. Imagine that! It was a tiresome journey. I slept for most of that day and the next. But not all in India was bad. I saw that the people in India are suffering. They are suffering from lack of services, humane values, trust and compassion. It is a dog come dog eat world out here. Most of the people I saw were honest. I also saw dishonest and greedy people. All the poor and working class people were more or less honest. The rich ones were greedy and dishonest. The young ones have become arrogant. Also when it comes to service industry, it is a disaster. Hospitality is an idea of the past.
The last time I visited India, I saw a different world. This time I saw quite some changes. The India of my dreams does not exist in reality anymore. Well only parts of it survive. The moral values and codes of the old have been lost. The youth has been distracted by uncontrolled imitation of the western values. Spiritual and humane ethics have been replaced with material values. I personally think that India is a volcano about to erupt. I will write in more details about those thoughts in my next rant. Stay tuned…
Android Applications released!
This post is a bit of marketing for the applications that I have been doing since the last couple of weeks. I have now release three applications on the Android Market. The first one is a re-write of my open source application Conference Manager (GPLv2) for Maemo. This application is also available in the Maemo Extra repository. I was hoping to port it to MeeGo but Mr. Elop had other plans. So I have stopped contributing to MeeGo all-together. And the best thing that happened was that I got an Android device (HTC Desire HD) about 3 months ago. The first thing I did was root it and then load some custom ROMs.
After much experimentation, I am now stable on HoneySense 3D 1.1. It has excellent battery life, no FCs and is a very good ROM. I am in no mood to change my ROM anytime soon. So now I have focused on the application aspect. The first thing I did was a complete re-write of Conference Manager for Android. This one is licensed under proprietary license and the source is closed. I am also planning to launch a PRO version with added capabilities like directly looking into Calendar and creating profiles, editing/deleting of templates, sync of data with users google mail account, etc. The free version will have all the capabilities of the Maemo Conference Manager with support for getting templates from server, creating templates and creating profiles from templates. I will release this version in a couple of days.
The second application that I have developed is SMSBiljett (GRATIS) and SMSBiljett PRO. This application basically is a ticketing application that can be used all across Sweden. Most of the Swedish states and cities have stopped accepting cash on trains and buses and replaced it with SMS Ticketing. My applications help people to get the ticket without remembering the cryptic codes and numbers to SMS, etc. It is also very flexible to buy tickets for more than one person in a single go. The GRATIS version is only working with Skånetrafiken.
The PRO version works with a lot of different city traffics including Skånetrafiken, Stockholm Transport, ÖstgötaTrafiken, Västmanland Public Transport, Västtrafik, Hallandstrafiken (Urban), Umeå (Urban), Upplands Region Traffic, etc. I will also update the application with support for SMS parking, traffic routing, etc. in later phases in the PRO version.
Hopefully it would be fun and people will help me with some cash motivation(!)
. But please feel free to download the applications, take them for a spin and give me your valuable feedback and comments. I would also like to hear about the features that you might want to get in. Separate application ideas are also welcome. So take care and peace out. Hopefully you will like my Marketing post!
