More new Gmail features

Even though Google introduced Anti-Virus capabilities to GMail recently, now they have introduced another set of new features which are available at What's New page.

Features

Web Clips
This will allow users to view news and RSS feeds inside GMail, without having to leave the GMail page.
View Attachments
With this you will not need to download or open attachments of many file types as it provides a "View as HTML" feature.
Supported file types are;
.pdf, .doc, .xls, .ppt, .rtf, .sxw, .sxc, .sxi, .sdw, .sdc, .sdd, and .wml.


read more | digg story

Google Desktop tweaked to block attackers

Due to a bug in Internet Explorer, data of Google Desktop (in user's machines) was in danger. Google has fixed it quite soon and users do not have to apply any patch as they have done it on their end.


But according to the news Microsoft is still looking into the bug.

Why Microsoft can not make a bugless browser? We know that developing a software without any bug is an (so-called)impossible task. But Microsoft is always issuing patches?



read more | digg story

Rename a database in MySQL through Linux console

Steps to follow to rename a database in a Linux environment can be listed as follows.

1. Stop mysql
    Use $ kill -9 [processID]
2. Search the place where the database folders are stored
    Use $ mysqladmin variables | grep datadir
3. Goto the folder which contains the database folders
4. Rename the folder
    Use $ mv
5. Start mysql
    Use $ mysqld_safe &

Adobe clinches Macromedia deal

Adobe Systems Inc has bought Macromedia Inc for $3.4bn. According to a news; the deal has been closed on last Saturday.

Adobe has commented that the users will experience a cheaper service than before. But normal senario is when a company becomes a dominator the prices go higher. We'll see? going down

read more | digg story

Creative Clock

Check how nice this clock works. A creative idea. ClockBlock

If you think Internet Explorer is great, read this


Many internet users happen to use Internet Explorer as the default browser, since it is provided with Microsoft Windows. So the users do not think of other choices, and stuck to IE.

It's still not too late to switch to a great browser like "Firefox".

www.stopie.com is a site completely related for this matter.

A Baby Named Google

Today only I heard that a child is named Google, actually Oliver Google Kai born on September 17th 2005 as son of Walid Elias Kai (a Ph.D. holder in search engine marketing) who is also a Google fan.

He is having his own home page, and also a blog.

Read More>>

A poem by an African Man


Dear White fella............ Couple of things you should know.....

When I born, I Black,
When I grow up, I Black,
When I go in Sun, I Black,
When I scared, I Black,
When I sick, I Black,
And when I die, I still black.......

And you White fella,
When you born, you Pink,
When you grow up, you White,
When you go in Sun, you Red,
When you cold, you Blue,
When you scared, you Yellow,
When you sick, you Green,
And when you die, you Gray.................

And you calling me Colored ???????????

Quite correct but innocent idea. I love this poem very much.

Have you ever used EJB?

View cartoon story: EJBHammer

Nice and a completely true idea from TSS. Without XDoclet, writing an EJB is a huge work.

I totally agree with this. What do you think?

Google set to display books

Google Print resumes its work from today for books and other contents that are not covered by Copy Right Law. So the authors of the books can decide whether they want their books to be available on Google print or not.


Google print also would be a great help for people who are trying to find a good book to buy since it allows you to read some parts of the book.

A sample linked list

Here is a sample linked list implementation. We should obviously use the std::list that comes with the STL under the header <list>. But since I was not posting something so its just to break the ice and post something...:)

[CODE]

#include<iostream>
struct Node{
               int data;
               Node* next;
};
void InsertAfter(Node **head, int value){
               if(*head==NULL){
                               Node* temp=NULL;
                               temp = new Node;
                               temp->data = value;
                               temp->next = NULL;
                               *head = temp;
               }else{
                               Node *temp = new Node;
                               temp->data = value;
                               temp->next = (*head)->next;
                               (*head)->next = temp;
               }
}
void DeleteAfter(Node **head){
               if(*head==NULL){
                               return;
               }else{
                               Node *temp = NULL;
                               temp = (*head)->next;
                               (*head)->next = (*head)->next->next;
                               delete temp;
                               temp=NULL;
               }
}
int DeleteAll(Node **head,int value){
               int count=0;
               Node *p = NULL;
               Node *q = (*head);
               if(*head==NULL){
                               count =0;
               }else{
                               while((q)!=NULL){
                                               if((q)->data==value){
                                                               Node *temp = NULL;
                                                               temp = q;
                                                               if ( p!=NULL){
                                                                               p->next = q->next;
                                                               }else{
                                                                               (*head) = q->next;
                                                               }
                                                               q = q->next;
                                                               delete temp;
                                                               temp = NULL;
                                                               ++count;
                                               }else{
                                                               p = q;
                                                               q = q->next;
                                               }
                               }
               }
               return count;
}
void DisplayList(Node *head){
               if(head!=NULL){
                               std::cout << head->data << "\n";
                               while(head->next!=NULL){
                                               std::cout <<
                                               head->data << "\n";
                                               head =
                                               head->next;
                               }
               }
               std::cout << "\n\n";
}
int main(){
               Node *head=NULL;
               InsertAfter(&head,10);
               InsertAfter(&head,10);
               InsertAfter(&head,20);
               InsertAfter(&head,10);
               DisplayList(head);
               DeleteAfter(&head);
               DisplayList(head);
               int a = DeleteAll(&head,10);
               std::cout << "Number Of Nodes deleted
                               having value 10 = " <<
                               a <<"\n\n";
               DisplayList(head);
               return 0;
}

Scored 98% - Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

I scored 98%.

Today is a very special day for me as I could comprehensively complete the Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035) exam. I could score 98% which is believed as to be a great score.

I got ready for this while I was too busy with a new project in my office. But I was able to some how manage and complete the exam with a great score.

And if you are having any questions or clarifications I may be able to help you. Just put me a mail with an explanation, so that I will help you on clarifying those.

Tools in BASIC

Some years ago I wrote a GUI editor named FreeForm in Liberty BASIC. I did this to show my users that they could build interesting software. FreeForm comes with Liberty BASIC, including source code. The Liberty BASIC editor permits users to add tools to the Run menu, so FreeForm comes as a tool on that menu when Liberty BASIC is installed.

I haven't worked on updating FreeForm in several years, but that hasn't stopped it from growing and becoming better. The Liberty BASIC community took over development and they've produced several versions, and some of these have been included with Liberty BASIC. Right now they're working on a whole new version, which I hope may be included in Liberty BASIC v4.03.

Other really cool tools that LB programmers have created have been code formatters, lint tools, and even whole IDE's. Brent Thorn is working on a complete IDE for Liberty BASIC written in Liberty BASIC called ViviFire, which includes a BASIC scripting language so that users can extend the IDE in itself. Extra cool!

Google vs Microsoft - Case over Dr. Kai-Fu Lee


According to a news after the court case over Dr. Kai-Fu Lee, from today Dr. Lee will be working for Google on the lab at China, but he is not allowed to work on the areas that he was working under Microsoft such as Search and Speech Recognition.

Both of the companies say that they have won the case. Anyway hearing that Dr. Lee is back on work is nice.

Anyway in this case there are two sides as I feel. Microsoft has a right to say that Dr. Lee should not be using what he gained at Microsoft in a competing company like Google. In the other way if he is not using those, then it is ethical for him to work in a competing company.

See also>>

eBay is on fire

Today I heard two impressive news on eBay.

One news is that eBay is buying Skype for $2.6 billion. The next is eBay plans to acquire Shopping.com in a $620 million cash transaction.

Buying Skype would be great communication tool for the buyers and sellers at eBay. But according to an older news, Google and Yahoo were in the battle for buying Skype (which did not come true).
Now eBay will have to take part in the competition with Google (VoIP-bound Google Talk), AOL (VoIP-bound AIM), and Yahoo (VoIP-bound Dialpad integration).

According to these news, is eBay moving to a competition with other internet gients.

Google hires the Father of the Internet

A big event happend at Google. As a news said Google has hired Vint Cerf (Vinton Gray Cerf), the Father of the Internet.


Cerf's job title will be 'Chief Internet Evangelist', as though Google needs one of those. His role will be to build network infrastructure, architectures, systems, and standards for the next generation of Internet applications.
He will also continue in his role as the Chairman of the Internet Corporation for Assigned Names and Numbers (ICANN).

Read More>>


This must be related to the news on Google's plan of launching their Own WI_FI network.

So is that news going to become true?

By concentrating only on the cup, we fail to enjoy the coffee in it

Today I found a nice little story which reminds us that we have a great life to live.


A group of alumni, highly established in their careers, got together to visit their old University of Notre Dame lecturer.

Conversation soon turned into complaints about stress in work and life. Offering his guests coffee, the lecturer went to the kitchen and returned with a large pot of coffee and an assortment of cups: porcelain, plastic, glass, some plain-looking and some expensive and exquisite, telling them to help themselves to hot coffee.

When all the students had a cup of coffee in hand, the lecturer said: "If you noticed, all the nice-looking, expensive cups were taken up, leaving behind the plain and cheap ones. While it is but normal for you to want only the best for yourselves, that is the source of your problems and stress.

What all of you really wanted was coffee, not the cup, but you consciously went for the better cups and are eyeing each other's cups." "Now, if Life is coffee, then the jobs, money and position in society are the cups. They are just tools to hold and contain Life, but the quality of Life doesn't change." "Sometimes, by concentrating only on the cup, we fail to enjoy the coffee in it."



But I'm still wondering how we could spend the life if we do not think of those tools that hold and contain Life. How do you feel?

TheServerSide Creator Floyd Marinescu leaves TSS after 6 years

According to a mail from Floyd Marinescu, Editorial Director of TheServerSide Communities and co-editor of www.theserverside.com, has decided to leave the Company after 6 years of work.

As www.theserverside.com is one of the best sites that provide quality and new technology discussions and articles, he must have contributed a lot. So your great work is appreciated. I hope the good work at www.theserverside.com will be continued even with the absence of Floyd Marinescu.

What's Special About This Number?

What's Special About This Number?

Nice job. His home site has much more interesting stuff.

Is Google building their own WI-FI network

Today morning I so an impressive news related to Google, the search giant.

Google seems like building their own network through out America. As google has bought resources for providing network services this may become real soon.

As Business 2.0 says, Google is already building such a network, though ostensibly for many reasons. It's also acquiring superfast connections from Cogent Communications and WilTel, among others, between East Coast cities including Atlanta, Miami, and New York. Google has sponsored Wi-Fi hotspot, built by a local startup called Feeva. Feeva is reportedly readying more free hotspots.

Read More>>

But will Google become a free ISP? How huge will be the impact on ISP industry? What do you feel?

OpenOffice 2.0 Beta released

Today I saw that OpenOffice 2.0 beta second release is available for testing now.

As the OpenOffice site expresses;

Beginning with version 2.0 OpenOffice.org uses the open standard OASIS OpenDocument XML format as the default file format. The OASIS OpenDocument format is a vendor and implementation independent file format, and thus guarantees freedom and independence.

Read More>>

Actually I saw this news through one of the blogs at blogspot http://cnpchillers.blogspot.com/.

WinFS

Microsoft released a beta version of the new file system named "WinFS" (Windows File System).

What is WinFS
"WinFS" is the code name for the next generation storage platform in Windows "Longhorn." Taking advantage of database technologies, Microsoft is advancing the file system into an integrated store for file data, relational data, and XML data. Windows users will have intuitive new ways to find, relate, and act on their information, regardless of what application creates the data. Also, "WinFS" will have built-in support for multi-master data synchronization across other Longhorn machines and other data sources. The platform supports rich managed Longhorn APIs as well as Win32 APIs.

Read More>>

The biggest enhancement to Longhorn that is being pulled from the 2006 release is WinFS (Windows File System), said company officials in Redmond, Wash. WinFS is a next-generation storage subsystem that allows advanced data organization and management and improves the storage and retrieval of files.

Read More>>

The next Windows release won't ship with the WinFS unified storage system, one of the three key components of Longhorn, as outlined by Microsoft at its Professional Developers Conference (PDC) in October last year (2004).

Read More>>

WinFS has a new synchronisation engine that can index disparate Windows files in a way that would enable users to more easily search and catalogue them. Pretty much what Google does already.
So will "Google Desktop Search" be vanished? I don't think so. What do you feel?

Const objects and a piece of buggy code!

Question: Here is a mallicious piece of code that I came across a few days ago:
[CODE]

#include
int main(){
const int x=5;
*(int *)&x=10;
printf("Value of x = %d at address= 0x%x\n",*(int*)&x,&(*(int*)&x));
printf("x=%d at address =0x%x\n",x,&x);
const_cast <> (x) = 20;
printf("New x=%d at address =0x%x\n",x,&x);
printf("Value of x = %d at address= 0x%x\n",*(int*)&x,&(*(int*)&x));
return 0;
}

It ran well on VC++ 6.0 and gave wierd outputs:
[Output]
Value of x = 10 at address= 0x12ff7c
x=5 at address =0x12ff7c
New x=5 at address =0x12ff7c
Value of x = 20 at address= 0x12ff7c

Isnt that wierd and wrong? Explain this behaviour.

Answer: The code results in an undefined behaviour.
Explanation: It does not work. It just seems to work. Here is the why and how:

You have declared the variable as a const int. So, when you use the address-of operator on this variable it returns a const int * as compared to a normal int variable in which case it return a normal int *. Now, what you are doing is you got the const int * and then you are using the C-style cast (int *) to cast the const int * to a int *. This is the problem. This is where the undefined behaviour is exposed. You forced the pointer to be converted to an int * and use it to modify the original const object. However, the compiler is free to store the constants whereever it wants which might even be a read-only memory location. And if you try making any changes to it, the results are said to be undefined according to the standards. This could probably work, not do anything or even crash.

Instead of printing what is there with 'x', the compiler optimizes the code. The compiler knows that you have defined x as a const int and you have initialized it with 5. So, it is at its own free-will to use optimization and take the value to be printed from this constant rather than using the variable x and dereferencing from its memory location. Here's a quote I like:

"The const keyword can't keep you from purposely shooting yourself in the foot. Using explicit type-casting, you can freely blow off your entire leg, because while the compiler helps prevent accidental errors, it lets you make errors on purpose. Casting allows you to "pretend" that a variable is a different type."

The villains are actually these two statements:
1. *(int *)&x=10; and
2. const_cast(x) =20;
The first statement is enough to force the undefined behaviour but lets suppose that we avoided it then this second statement becomes the culprit. Herb Sutter in his Exceptional C++ item - 6 says that removing the constness of the const object this way results in undefined behaviour if the actual object is defined as a const. Thats it. If you are further interested, see at the assembly code for this program (VC++ 6.0 Disassembly):
[CODE]
1: #include
2: int main()
3: {
00401010 push ebp
00401011 mov ebp,esp
00401013 sub esp,44h
00401016 push ebx
00401017 push esi
00401018 push edi
00401019 lea edi,[ebp-44h]
0040101C mov ecx,11h
00401021 mov eax,0CCCCCCCCh
00401026 rep stos dword ptr [edi]
4: const int x=5;
00401028 mov dword ptr [ebp-4],5
5: *(int *)&x=10;
0040102F mov dword ptr [ebp-4],0Ah
6: printf("Value of x = %d at address= 0x%x\n",*(int*)&x,&amp;amp;amp;amp;amp;(*(int*)&x));
00401036 lea eax,[ebp-4]
00401039 push eax
0040103A mov ecx,dword ptr [ebp-4]
0040103D push ecx
0040103E push offset string "Value of x = %d at address= 0x%x"... (00420058)
00401043 call printf (004010d0)
00401048 add esp,0Ch
7: printf("x=%d at address =0x%x\n",x,&x);
0040104B lea edx,[ebp-4]
0040104E push edx
0040104F push 5
00401051 push offset string "x=%d at address =0x%x\n" (0042003c)
00401056 call printf (004010d0)
0040105B add esp,0Ch
8: const_cast(x) =20;
0040105E mov dword ptr [ebp-4],14h
9: printf("New x=%d at address =0x%x\n",x,&x);
00401065 lea eax,[ebp-4]
00401068 push eax
00401069 push 5
0040106B push offset string "New x=%d at address =0x%x\n" (0042001c)
00401070 call printf (004010d0)
00401075 add esp,0Ch
10: printf("Value of x = %d at address= 0x%x\n",*(int*)&x,&amp;amp;amp;amp;amp;(*(int*)&x));
00401078 lea ecx,[ebp-4]
0040107B push ecx
0040107C mov edx,dword ptr [ebp-4]
0040107F push edx
00401080 push offset string "Value of x = %d at address= 0x%x"... (00420058)
00401085 call printf (004010d0)
0040108A add esp,0Ch
11: return 0;
0040108D xor eax,eax
12: }
0040108F pop edi
00401090 pop esi
00401091 pop ebx
00401092 add esp,44h
00401095 cmp ebp,esp
00401097 call __chkesp (00401150)
0040109C mov esp,ebp
0040109E pop ebp
0040109F ret

Even I am not very much aware (until now) of the assembly language but I guess this snippet is easy enough to get a feel about what things are happening. The locations marked in black are the one's important to us. Instead of dereferencing x and taking the value from its address, as a optimization techniques the compiler simply pushes in a constant value 5 and uses it while (or even when) there is a different actual value at the storage location of x.

Hence, people! just beware of landing up with code where you cause the undefined behaviour show up. They may look very convincing and correct and that leads to a buggy code very hard to fix. Hope you all liked and enjoyed this post.

P.S. - Please report comments, corrections, and suggestions at this blog. I am learning.

www.kamal.org

Today is one of the happiest days in my life as I got my public domain: www.kamal.org. One of my friends, Maduranga helped me lot in purchasing this. Thanks a lot Maduranga.

I thought of redirecting it to my blog. Later I will buy some space in the web to host my home site (which is not ready yet).

As yesterday was my 25th birthday, I will never forget the day I got my domain.

So a grand ice cream treat was ready for all my friends in the office. (If you were not in my office!!! hard luck. You may have missed it.)

How to avoid the top five IT mistakes

Got a chance to read article named "How to avoid the top five IT mistakes".

Five Mistakes are;
1. Too much customization
2. Skimping on training
3. Absentee management
4. Freewheeling consultants
5. Assuming you're finished

Point number 1. is something that I'm also trying to point out in project meetings as most of the time people think on customizations which they would never ever use. And sometimes providing that much of customization leads to a mess.

What do you think?

Variadic functions and non-POD arguments

This is regarding an issue that I came across a few days back and I really liked this one as I helped the guy understand a few concepts involved better and in the process learning myself. This in heart involved variadic functions. I quote the problem below:

Problem:

There is a class.(I would not provide the code as it would make the post long, its easily understandable in words and if you feel like then you try experimenting with some code on your own). The various members it has are:

1. A constructor with no arguments.
2. A copy constructor.
3. A destructor.
4. An overloaded (++) operator. (not that significant as far as the solution to the issue is concerned)
5. A private data member. (not that significant as far as the solution to the issue is concerned)

We create an object of this and use printf statement once. In the printf I pass the object of this class. Printf and scanf are functions of truely a different breed. You must have heard about variadic functions. They can take any number of different types of arguments that's their speciality. What happens during this whole process in main - constructor is called twice (2nd one being a call to the copy constructor) and the destructor is called just once!!! Is there some kind of memory leak? What happened, whats the reason for this awkward behaviour?

Short answer:

The behaviour in the given scenario is undefined. What it means is you got these results on some compiler - you would get different results on some other and there is no guarantee as such that application would not crash. I tried running the code of my machine with VC++ 6.0 and it worked fine. That is what is undefined behaviour... we never know.


Explanation:

We will look forward to the solution with a very generic approach. We would not restrict the reasoning to just printf. Since they are examples of variadic functions so lets start with variadic functions in general. To know more about variadic functions - I would suggest you to visit this -
Variadic Functions : gnu documentation
and Variadic functions : informit article.

There are various restrictions imposed whenever you try using variadic functions in C++. I would try stating the scenarios making for this undefined behaviour below and put quotes from these links that I find significant.

1. Simply because the rules say (Hehe :-)), you cannot use non-POD types in the variable argument list of a variadic function. That would result in an undefined behaviour. It's about time I gave a definition to non-POD type or rather POD type? Here's what they are (I quote the definition from the C++ FAQ Lite - a collection by Marshall Cline). POD type = Plain Old Data type.

[Definition]
A POD type is a C++ type that has an equivalent in C, and that uses the same rules as C uses for initialization, copying, layout, and addressing. As an example, the C declaration struct Fred x; does not initialize the members of the Fred variable x. To make this same behavior happen in C++, Fred would need to not have any constructors. Similarly to make the C++ version of copying the same as the C version, the C++ Fred must not have overloaded the assignment operator. To make sure the other rules match, the C++ version must not have virtual functions, base classes, non-static members that are private or protected, or a destructor. It can, however, have static data members, static member functions, and non-static non-virtual member functions. The actual definition of a POD type is recursive and gets a little gnarly.

Here's a slightly simplified definition of POD: a POD type's non-static data members must be public and can be of any of these types: bool, any numeric type including the various char variants, any enumeration type, any data-pointer type (that is, any type convertible to void*), any pointer-to-function type, or any POD type, including arrays of any of these. Note: data-pointers and pointers-to-function are okay, but pointers-to-member are not. Also note that references are not allowed. In addition, a POD type can't have constructors, virtual functions, base classes, or an overloaded assignment operator.


2. C++ has two mechanisms of passing arguments - by value and by reference compared to just pass by value as in C. Now, here's the ambiguity that creeps in, in these 2 cases is that when you make the calls by either of these they are same syntax from caller point! So, the compiler (and the variadic function) is not able to distinguish if that is intended to be passed by value or by reference, if a copy is to be made or not. This might be fixed by forcing one single argument passing option i.e. it always happens by pass-by-value (can't choose by-reference as we need to keep them working for C as well). Calling conventions (point 3 below) make this more complicated as you will see.


3. The function calling conventions, we would be considering are __stdcall and __cdecl. You could read up on them on MSDN with a simple search. With __cdecl, the caller has the responsibility to clean up the stack and with __stdcall the callee has this responsibility. Now, variadic functions impose certain basic rules as stated in point (1) above due to which _stdcall would not work. __cdecl would possibly give similar behaviours but still in case of non-POD types, its a general behaviour that the callee (I dont have proofs to back this but you can take my word - or you could try doing some research with the assembly code) calls the respective destructors or atleast that it's not standardized behaviour so you cannot rule it out. Now, here's the problem - the function doesnt know the number and types of the arguments and hence this would be a step that would cause issues..dreading issues. So, it simply assumes what I have stated in point (2) that the variables being passed are POD types (againts the non-POD types that are actually being passed) and the destructor doesn't (or better say, may not) get called! This is a problem.

4. There are certain restrictions regarding variadic arguments/functions that simply are rules to reject any possibilities:

    4.1) A function that accepts a variable number of arguments must be declared with a prototype that says so. You write the fixed arguments as usual, and then tack on `...' to indicate the possibility of additional arguments. The syntax of ISO C requires at least one fixed argument before the `...'.

    4.2) For some C compilers, the last required argument must not be declared register in the function definition. Furthermore, this argument's type must be self-promoting: that is, the default promotions must not change its type. This rules out array and function types, as well as float, char (whether signed or not) and short int (whether signed or not). This is actually an ISO C requirement.

    4.3) The parameter parmN is the identifier of the rightmost parameter in the variable parameter list of the function definition (the one just before the ...). If the parameter parmN is declared with a function, array, or reference type, or with a type that is not compatible with the type that results when passing an argument for which there is no parameter, the behavior is undefined. (C++ ANSI standard, 18.7.3)

    4.4) Lastly, when there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_arg (18.7). ...if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed. If the argument has a non-POD class type, the behavior is undefined. (ANSI C++ 5.2.2.7)

Apart from all that, probably, there might be a way to implement variadics such that they just work but the points above are useful to know when writing variadics according to the current set of rules about when they work and when they don't.

Conclusion:

So, now I infer that variadic functions are quite specific to C. You cannot use non-POD C++ types with them. For manipulating non-POD types, you should use the C++ techniques. You are quite restricted to using variadics in C++ but still they are sometimes needed and they should be carefully used with POD types only. The article links (the two that I have above) illustrate the points further in detail.

Here are a few alternatives (one of the below or they together with each other) to these functions in C++:

1. Functions with Default Arguments
2. USage of Function Templates
3. Packing Function Arguments in a Container
4. Overloading operator <<

You could also refer to the codeguru thread that is the base for this post - that helped me digest the above as a rule - Destruction (variadic woes).

P.S. - Please report comments, corrections, and suggestions at this blog. I am learning.

auto_ptr and their usability with STL containers

Aaaahh... Smart pointers..aren't they one of the best things that has happened to C++. They are also sometimes called Managed pointers. I am not going to talk about them right from introduction, so if you are unaware what they are and what are their uses, then try figuring them out through the web-searches or @ codeguru... my fav place as far as C++ is concerned.

Ok..Ok..not ready to search for them...fine.. I will try giving a very brief description. Remember when you use pointers in C++ with dynamic memory management, it's such a headache to get them going and finish them off once you are done? If you did a new or new[], you need to have a corresponding delete or delete[], so that the allocated memory is freed up and the destructor for the new-ed object is called. Also, when you are done with the delete/delete[], freed-up the memory, you need to cautiously set the pointer to NULL, so that you won't try dereferencing it after the de-allocation assuming it points to a valid object. (Recall Dangling pointers. They could be disastrous if dereferenced!)

But just imagine that you could use pointers in the same way you used to do and forget about the headache of the deleting (and optionally NULLing it)? How would that be? Wouldn't that be cool and care-free? ...and that is what is made possible by these managed pointers/smart pointers. They are really smart and they exist in wide varieties.

For now, I would limit my post to just one of that category which is the standard auto_ptr (read auto-pointers). They are a part of C++. They own the dynamically allocated object and then perform the automatic cleanup whenever the object goes out of scope or is not needed. Now, if at some stage you want the manual ownership back they have this function member - release(), make a call to it and all the headache is back yours.

[CODE]
//Example showing a bad situation with naked pointers
void MyFunction()
{
        MyClass* ptr( new MyClass);
        /*.some more code.*/
        delete ptr;
        ptr=NULL;
}

In this scenario, just in case of some exception it's possible that somehow the delete ptr; did not happen...Disasterous..a memory leak! There's more - suppose, in the destructor of MyClass, you call for some resource release like close database connections, releasing file handles or release semaphores, locks etc. All resources are blocked and there's no way out. There could be many more aweful situations.

Now, lets use an auto_ptr and see how it makes life easy:

[CODE]
//Situation above tackled using auto_ptr
void MyFunction()
{
        auto_ptr<MyClass> ptr(new MyClass);
        /*.some more code.*/
}

There is no need to explicitly call a delete; as soon as ptr goes out of scope the destructor of MyClass is called and the object is freed. You should note that auto_ptr only handles allocations with new and not those done with new[] or malloc or any other memory allocation routine for that matter. For those, refer to the following posts - Handling dynamic array allocations, Custom deleters with smart pointers, Free New, Delete Malloc

You can even transfer the ownership of an auto_ptr to another auto_ptr, to another function or free/reset it to use it again.

Here's an example showing the transfer of ownership from one auto_ptr to another.

[CODE]
        //Example showing transfer of ownership.
        auto_ptr<MyClass> autoptr1(new MyClass);
        auto_ptr<MyClass> autoptr2;
        autoptr2 = autoptr1;
        //Now autoptr2 owns the pointer & autoptr1 doesn't
        autoptr1->MyFunction(); // ERROR !!!
        //autoptr1, now is a null pointer

However, one very interesting and important fact about auto_ptr's is that their copies are not equivalent as is the case with naked pointers.
  • Consider STL containers or some generic algorithms/functions like sort. There is no restriction by the standard on the vendors of the STL implementers that the containers won't make a copy of the members being added into it (and probably do nothing with it!). In fact, for example, the implementations of the vector class make a copy of the original object and store inside them. We know auto_ptr copies are not equivalent due to the strict ownership semantics. You might be safe in just having those auto_ptrs stored inside a vector but you get a few examples around this in the Gotw link below that show how the problem comes out in the open, for example, with say, a sort algorithm that holds a copy of an element as a pivot? There is nothing to guarantee or prevent that.

  • Another disastrous situation would be when you are initializing (setting/assigning) another auto_ptr object with an object held by the vector. You would think that the object inside the vector is okay and retains the same state but it will not. The ownership by this time would get transferred to the external object just initialized/assigned.

  • What if there is a member function that returns the contained vectors element is returned by value?

  • What if you make another copy of the vector? Or for that matter, create some other container out of its elements?

  • Use of member functions of vector like - constructor, assign, insert, resize - will they succeed? Will they definitely succeed?

It just gets too messy to handle. Sure some operations will work out fine but quite a few will not and you would need to keep worrying about 'em.

To help us out of this disaster, the C++ standards did some tweaking. The copy constructor and the copy assignment operator of auto_ptr take a reference to a non-const right hand side objects and the standard containers' insert() takes a reference to a const and hence auto_ptr cannot be used. It will just not allow you to create a copy of auto_ptr inside the vector (standard containers) members. That will cause you compilation errors on a compliant compiler. Nice solution..isnt it? But still, as a strict guideline..we should not use the auto_ptr wherever a copy of theirs is expected to be made.

For more information, visit these : Using auto_ptr effectively by Herb Sutter, Smart Pointers - What, Why and Which, Smart pointers

Cya!

Firefox Browser


The Firefox browser is an excellent browser among the availables today. I found an interesting article that compares the Firefox browser and the IE browser (Internet Explorer).

So of the interesting features are;
- Tabbed browsing
- Popup blocking
- Prevent scripts from doing various things
- More control over text zooming
- Block images from third party sites
- Cross-platform
- Open Source
- Huge range of extensions and ease of installing extensions

Read all the 101 things that the Mozilla browser can do that IE cannot.

I installed some more extensions for Firefox today which are listed below.

- CustomizedGoogle
Adds a selected set of search sites like yahoo, ask jeeva,.. to your google search result page. Also provide an easy customization.
- Tab X
This is an extension I was looking for. This adds a close button to each browser tab which is not availble in default Firefox.
- Gmail Notifier
Browser notifies for new mails. Still only the new mail arrival is shown, but showing the mail headings would improve the extensions popularity.
- Resize Search Box
Another feature that I was expecting from the default Firefox installation, how ever now I can resize the search box at the top right corner.
- Show IP
This shows the IP of the site.
- Flash Block
Allows the user to decide whether to play or stop the flash contents in the site.

What is your idea on these extensions?

Microsoft sued Google

As the search engine competition is in a top level with google, yahoo and microsoft competing, I heard a news today as follows.

Microsoft sued Google yesterday (07.19.2005), for hiring one of their top employer to head a new research lab in China. As Microsoft argued that taking such a position in a direct competitor is illegal. And also Microsoft point the finger towards Google for encouraging him to do so.

As news expalined, Dr. Lee is a well known character in the industry and he has worked for Silicon Graphics and Apple.

When google is growing so fast while offering new wide range of services, losing Dr. Lee will be a huge issue for Microsoft to retain in the competition.

So we'll look forward to see the continuation.

One interesting point I noticed was the demand that Bill Gates have given to the qualified professional in this industry, as he says that the major problem is talented computer science graduates.

Read More...
www.forbes.com
www.pcpro.co.uk

Koenig look-up and namespaces

I was running through some of the posts on codeguru and then suddenly saw this name referenced in Andreas Masur's post - "Koenig Lookup". I had heard it for the first time since I started with C++ and to be specific namespaces. So, I though of starting a look-up for myself and find what it really was! This post would be an introduction to the concept which we frequently use knowingly and most of the times unknowingly. Here it goes:

Keonig look-up is an algorithm devised by Andrew Koenig. This algorithm is also sometimes known as Argument-dependent Lookup. These days, it is used in all the standard conforming compilers in C++ which handle cases as shown in the example code below:

[CODE]
namespace MyNamespace{
class A {};
void func(A);
}

MyNamespace::A a; // global object of MyNamespace::A class.

//main method.
int main(){
func(a); // OK - MyNamespace::func is called.
}

Neither a using-declaration nor a using-directive appears in code above. And yet, the compiler will do the needful and that is correctly identifying the unqualified name "func" as the function declared in namespace MyNamespace by applying the algorithm we are talking about. How does it work? The algorithm tells the compiler to look at not just the usual places such as local scope, but also the namespaces that contain the argument's type. Thus, in the following line of code, the compiler finds that the object a, which is the argument of the function func, belongs to the namespace MyNamespace. So, it looks at that namespace to locate the declaration of "func", "guessing" what we wish to do.

Without this, namespaces would be imposing an unacceptable burden on the programmer, who would have to repeatedly specify the fully qualified names, or instead, use numerous using-declarations. There is abundant debate on the topic of advantages and disadvantages of this algorithm but lets see this example to support this feature.

[CODE]
#include
using std::cout; //using declaration
int main(){
cout<<"hello world!"; //OK, operator <<>
}

The using declaration puts std::cout into the scope of main(), thereby enabling us to use the non-qualified name "cout". However, the overloaded <<>

[CODE]
std::operator<<(cout, "hello world!");

Isn't it a pain-saving appreciable feature. It's interesting to find out about things that we usually do unknowingly. It add value to our knowledge. Cheers.

Casting cv-qualifier and function pointers to void*

Okay..so this is my first post to this blog of mine. This post is a result of a very fine discussion that I had with some of the Gurus at http://www.codeguru.com. I thought I would compile the stuff from that and present it here.

Before I proceed any further I would like to thank the members of Codeguru who participated with keen interest and helped me get the concept right. Thanks to - Graham, SuperKoko, Smasher/Devourer, Wildfrog, NoHero and Improving.

The question was - Can void pointers point to const, volatile and function pointers? Explain.

The answer is - Quotes from MSDN:
"If a pointer's type is void *, the pointer can point to any variable that is not declared with the const or volatile keyword."
AND
"A void pointer can point to a function, but not to a class member in C++."

Thats pretty much it but lets go through the explanation to get to the basic reasons why MSDN negates the possibilities.

const and volatile are collective named as cv-qualifiers by the standard and a basic principle is that we are not allowed to lessen the amount of cv-qualification of an object. If we were to assign a cv-qualified object to a void pointer, then we could cast them back to a non-cv-qualified pointer to the original object. This steals away the whole essence of the cv-qualification of the objects while the intention of the standard is that only const_cast can remove cv-qualification from an object.

The standard treats const and volatile identically as far as their syntax and restrictions are concerned. The standard intentionally makes it hard for us to lose the cv-qualification of an object, since this is almost always an error in coding, not that its impossible.

You could use this as an example:
[CODE]
volatile int arg = 0;
void * ptr1 = &arg; // Valid but it won't be volatile anymore

A better way to do this could be:
[CODE]
volatile int arg = 0;
volatile void * ptr1 = &arg;

Okay, so that's for the CV-qualifiers. Now lets get back on track with the case of function (class-member functions as well as non-member functions) pointers.

Let's take an example:
[Code]
#include<iostream>
using namespace std;

//This creates a typedef called IntFuncPtr which is a pointer to a function
// that takes no arguments and returns an int.
typedef int (*IntFuncPtr)();

// An example class with a single member function.
class A {
public: int f() { return 1; }
};

//Note this function has the proper signature to be addressed by an IntFuncPtr.
int g() { return 2; }

int main() {
void *pVoid;

pVoid = g; //OK: cast from int (*)() to void*
cout << ((IntFuncPtr) pVoid) () << endl;
pVoid = A::f; //ERROR: can't cast from int (A::*)() to void*
return 0;
}

In this program, Visual C++ 6.0 will allow to make an implicit conversion from a (non-class member) function pointer to a void pointer, in the line pVoid = g. In the following line, we cast that pointer back to its appropriate type and use it to call the function it points to, to demonstrate that it holds the correct value. The line after that, attempting to assign a class member function pointer to a void pointer, does not work.

So, we see that we can use void* to point to non-member functions but not member functions. Is this really true?? Even if we are able to get the non-member functions part going, is it portable??? Comeau compiler is considered to follow the C++ standards to the closest and running this code there did not allow what VC++ allowed easily. It gave the following error message - "A value of type int (*)() cannot be assigned to an entity of type void*."

The reason for this is well explained by Herb Sutter in his More Exceptional C++. He says : "Although a void* is guaranteed to be big enough to hold the value of any object pointer, it is not guaranteed to be suitable to hold a function pointer; for example, on some platforms a function pointer is larger than an object pointer." That is, in general, for a member function pointer or a non-member function pointer.

Here's an example that illustrates this for the case of member function pointers:

[CODE]
#include<iostream>
using namespace std;

class A
{
public:virtual void f();
};

class B
{
public:int x;
};

class C : public B, public A
{
};

int f()
{
return 0;
}

int main()
{
void *p=reinterpret_cast<void *>(f);
cout << sizeof(&A::f) << " "<< sizeof(static_cast<void (C::*)()>(&A::f)) << endl;
return 0;
}

Outputs:
8 8 (With GCC)
12 12 (With BC++)
4 8 (With VC++)

While sizeof(void*) will gives you 4, with above.

You might get better affirmative results for classes with simple inheritance but with multiple inheritance (the case in the program), virtual inheritance, virtual functions and in some more complex scenarios, you could get the size of the function pointers greater than sizeof(void*), may be 4, 8 and sometimes 12 or even greater. They are very compiler dependent and class dependent.

You can't even assign a pointer to non-member functions to a void* for the same reasons (even if some compiler would allow you doing so), they are not guarenteed to be of the same size. These are however relatively portable than the case of member-function pointers and that is why MSDN says you can (for non-member functions) atleast on MS platform. But, you know that's not portable. A work-around could be using reinterpret_cast to cast a function pointer to another function pointer type (say, any one that you can use throughout your code base for consistency) and then cast it back to it's original type. The standard guarantees that to work. But the drawback is that you lose type-safety, which itself is not a very good thing to do in ideal scenarios.

Further reading and references: online Comeau compiler at Comeau online , Recursive Declaration.

Cheers!!!

TechNewsWorld


Today I found a good web site which consists of news on new Techs. That is www.technewsworld.com. Seems it provides news in all most all the techincal fields. I was mainly focused on the Open Source portion.

Some of the interesting news I found today are;

  • Firefox Patch
    Patch releasing has two practices. One is to release patches at the end of each month and the other is to realese as soon as it is ready.
    I feel that patch releasing as soons as possible is the best way since recovery of an attack will be much harder than applying a patch even in a large scale organization.

  • One-in-Ten-Web-Users-Have-a-Taste-for-Spam
    As the news explains 39 percent of the people still reading the messages and clicking on links embedded in the emails. As they says, this is a known method for spammers to detect if an email address is being used, and as a result 57 of the latter group reported that they started receiving more spam.

  • Sun-Open-Sources-Its-Authentication-Technology
    Sun Microsystems moves towards Open source. But I wish the complete java platform not to become Open-Source.
  • Google News

    "Google News" provides a well organized and a customizable view for NEWS.

    You can customize the viewed news by providing key words. And also the news can be prioritize according to your requirements. So news searching and organizing is done by Google, we just have to watch it.



    http://news.google.com/


    I have created a customized News View for me. You can check my configurations and even you can use that as your customized view.

    My Customized News View

    Learning C++

    This blog would be a collection of some quality issues related to the C++ Programming Language. A compilation of my activities on Codeguru. Hope this comes out to be of help to you people and of course me.

    Cheers to my 2nd blog.
    [ http://abnegator.blogspot.com ]

    JASIC?

    Someone recently mentioned a new up and coming BASIC language product called KBASIC and asked me what I thought. I went to Google and found the site. What I discovered there was so complicated that it reminded me of programming in Java using the Eclipse IDE. Eclipse is an excellent IDE, at least in the sense that it makes programming in Java practical (possible?). You need all the power of Eclipse because Java is a big, heavy and complicated way to write software.

    KBASIC seems to emulate Java. Even the style of object orientation presented is very Java-like or C#-like and some syntax is borrowed directly from Java. Why do this? BASIC shouldn't need an industrial strength IDE that is as complicated as the cockpit of an F-15.

    This is the sort of thing I am trying to avoid with the new BASIC programming language I'm working on. Java is a mountain of rules and exceptions that the programmer must navigate, never forgetting to dot i's and cross t's. Why make a BASIC that emulates Java? This is the sort of thing that caused outcry when Microsoft did away with Visual Basic and replaced it with VB.Net.

    I know that some people enjoy mastering complexity, perhaps as a way to find satisfaction in their work. This is incompatible with the way BASIC programming should be. BASIC should be small, simple and fun.

    On Modernizing BASIC

    dave b. responded to my previous post with this (amongst other things):
    I hope this nostalgia over the old BASIC command set and the "small is beautiful” fallacy won't hold LB back from evolving into something really useful (which is what programming languages should be).


    Really useful for what, Dave? Go and ask the Liberty BASIC community if Liberty BASIC is useful and they will answer with a resounding yes. It is useful for getting a quick program together, useful for learning to program, useful for having fun with a computer, and more too. To make a comparison, Java is also a useful programming language, but it isn't necessarily useful for the same things. There is no universally useful programming language.

    I agree with a lot of your ideas, and if you read all of my posts, I think you'll agree that I don't have the simplistic mindset that you seem to imply that I have. I understand abstraction in software better than you apparently think I do.

    Nostalgia has nothing to do with Liberty BASIC's faithfulness to classic BASIC syntax, at least not on my part. This is a matter of marketing. You welcome the C-style of doing things with functions. A lot of other people do not. They want an old-style BASIC. I am marketing to these other people. Your advocacy of mutating BASIC syntax into something that is more "modern" does create a new language that is not BASIC, IMHO. Eliminating old BASIC commands and replacing them with functions turns a lot of people off.

    I am working on a new BASIC in part to break the backwards compatibility chain with Liberty BASIC. That doesn't mean of course that my new language will necessarily take the direction that you advocate. OPEN "filename.ext" for INPUT as #1 will still be there. I agree with your point that the syntax for controlling widgets in Liberty BASIC is bad, and it will be replaced in the new BASIC. I will do things differently and in an unexpected way, and not to be deliberately contrary but for a reason. I intend to lead with this new language, not follow.

    BTW, a lot of people like Liberty BASIC the way it is and don't seem to need anything else. You have decided to move on to another tool that meets your needs better and that's great.

    Don't expect Liberty BASIC to become anything but what it is. This is beginning to feel like you're beating a dead horse. :-/

    Add search facility

    Google, the best search engine provides the ability to add search facility to your own web sites for free. Also they have provided a set of code snippets.

    http://www.google.com/searchcode.html

    I added the search facility to my blog today.

    AMNS - a multiplatform MSN messenger clone


    Since MSN Messenger is only for the Windows platform, this is a good alternative while you are on Linux.
    According to the project description it supports;
    - All 32-bit MS Windows (95/98/NT/2000/XP)
    - All POSIX (Linux/BSD/UNIX-like OSes)
    - Linux
    - OS X

    I tried it on Mandrake Linux 10.0 and it worked fine. AMNS is provided with a variation of plug-ins for the look and feel.

    AMSN - MSN messenger clone

    What is a Blog

    First of all I searched on What a blog is before starting to use my blog. This is how I feel. The way I understood may not be the perfect.

    A blog (shortened from weblog) is a web based method of collecting any information that you prefer. There is no restriction on what you can or can not blog, it is totally upto the owner to decide whether to have some informartion or not. This can be maintained as a diary, as a way of expressing your thoughts to the public, as a way of keeping track of the important information and also as a way of making a discussion with the viewers.

    All the blogs are displyed with the timestamps and are sorted so that the new blogs are at the top. This makes easy for the visitors to view latest blogs. Blogs provide the visitors with the facility to submit comments, so that this can become a discussion.

    A comprehensive description on "What a blog is":
    en.wikipedia.org
    www.answers.com

    Create your own free blogs:
    www.blogger.com
    www.bloglines.com

    Can you suggest some other sites that provide free blogs?

    What's my story?

    As an implementor of BASIC, where am I coming from?

    The home computer, a way back machine - In regards to the BASIC programming language, I think my strongest formative influence comes from working with old home computers. There was something wonderful about these machines that plugged into the family television set. They were simple when compared to computers now, and you could get your mind around them. You could master the whole computer because all of the details fit in a 5x8" spiral bound manual a couple of hundred pages long.

    Personal Mastery - Perhaps similarly, I used to work on my own cars. I loved working on old Volkswagen Beetles, and I owned a bunch of them. I knew pretty much everything about the Beetle, and I loved knowing all about it. It's about that feeling you get when you master something. Nowadays I take my cars to the experts because I simply cannot understand the new cars. If it breaks down, I call a tow truck. It's harder to love cars today. This is how computers have become.

    Interactivity - Let's see. Just like you can take the parts of an old car and flip them over in your hands, see how they fit together and what makes them tick, programming in BASIC on a home computer was like that. You could stop your program, look at variables (flip them over in your hands, so to speak), execute a little line of code on the fly, and resume execution at any point. If you wanted to mess with the video mode, or tweak the sound, or read/write some memory value, you could. The very nature of the machine permitted it. There is was, all laid out before you like clay in your hands and it was not so vast that you were overwhelmed by it all.

    BASIC today - So I really feel that if at all possible BASIC programming should still be like this, but it mostly is not. Most BASIC languages today are compilers. This means that once you start to run your program, you cannot just stop it and tweak it. You can't change the code of a running program without needing to restart the program from scratch. In addition, the huge functionality of modern operating systems inspires programming language implementors to continually make their BASIC languages bigger and bigger. This is an artificial barrier to personal mastery.

    The reverse 80/20 rule - Okay, since only 20 percent of the Windows operating system functionality is needed 80 percent of the time, why create a programming language that tries to embrace all of it? Home computers did most of what a computer is useful for, and compared to computers today they didn't do much of anything. The reality is that an awful lot of useful things can be done with a very small language.

    Small is beautiful - Balance is also beautiful. BASIC should try to strike a balance between being small, and also supporting the most often needed features of Windows, the Mac OS or whatever operating system it runs on.

    Aesthetics matter - How does your BASIC language look, like BASIC? I'm not kidding. Many programming languages today that call themselves BASIC don't look anything like BASIC. Tacking ideas and syntax onto BASIC from other languages only complicates things. If it doesn't look like BASIC, it isn't BASIC. I don't mean this in a snobby way. I just think that the feel of the original language is worth preserving because it had a nice simple down to earth quality. Removing that quality also removes some of the fun, and I don't see why we need to do that. ;-)

    Why languages like BASIC are important today

    I think it is important that most programming can be done with simple tools. BASIC fits well with the idea that it should be as simple as possible, but no simpler. The average person cannot commit to learning programming languages that need several thick books to explain them. Before you can get anywhere, you need a language that's comfortable to start with. How else can QBasic's tremendous staying power be explained? The last version of QBasic rolled out of Microsoft 13 years ago, and a quick Google search for QBasic reveals nearly a half a million hits!

    I also believe that there is a lot of arrogance in the established programming culture. Many software professionals (some of whom aren't especially good at what they do) look with disdain on the users of "hobby languages". Not everyone who writes software does so as their sole profession. Some people need to write small programs for their own use, and so they can be the sole judge as to whether the software is good enough. Other people will only program for fun, and they should not need to answer to anyone.

    Once when I gave a demo of Liberty BASIC to a fellow programmer, his response was, "Who would want to use that?" To him it seemed like a toy. He doesn't understand that not everyone needs or wants all the power and complexity of C++.

    Programming and Love of Learning

    One of the things I really love about programming is that I love learning new things, and programming is a great medium for working in ideas. Once programming becomes simply work, the spark is gone and it's better to go find something else to do.

    Almost 20 years ago I taught myself C, which I really liked a lot at first. That programming language has some ideas that were pretty interesting to me coming from BASIC, but it became clear to me after a while that C programming is more about twiddling the drudgery bits and details than it is about expressing ideas. Don't get me wrong, C is great for certain things. If I were an operating systems builder I probably wouldn't use anything else.

    I don't program in C anymore, but I wouldn't discourage BASIC programmers from learning C or any other language. I learned a lot of ideas from my experiences with C, Forth, Smalltalk and Java. There's no substitute for trying a new language. Even if you still only use BASIC it will change your programming style when you are exposed to new ideas, and you will also have more fun.

    Learning. I heartily recommend it. :-)

    Programming - Is the word worn out?

    You know, I'm wondering if there doesn't need to be a new word for programming. I mean, it's a fine word and all, but it already has too much baggage and history.

    How can we get young people interested in programming? We need a new word. One of those cool (kewl?), hip new words. Something that implies a sense of fun and excitement. When the web was born, the word surf was adopted.

    Obviously we cannot just come up with a fresh new word and apply it to the technically mundane programming languages like Java, C++ (or Fortran). The word has to apply to a new and fresh kind of programming.

    BASIC, not BATAP

    This blog is about BASIC, which means Beginners All purpose Symbolic Instruction Code. If it were about Being All Things to All People, the language would be call BATAP. ;-)

    I'm inspired to write this because of the plight of General Motors. The world's largest auto manufacturer is losing money in droves. The reason is in their name, the first word of which is General. The problem is that there is so much competition in this world today, that being general is not a strength. If you want to get people's attention, you need to specialize.

    BASIC also needs to specialize. The key ideas it needs to specialize in? Easy, simple, approachable, and fun. Does it have power? Yes. It has the kind of power that gives the average person the ability to program computers because of the four qualities I just listed. When Microsoft created Visual Basic (now officially unsupported by the way) they took BASIC out of the domain of the everyday person and tried to make a professional tool out of it. They should have called it Visual BATAP.

    BATAP can never be BASIC.

    BASIC Overloaded?

    One reader posted a comment to my last post on the cult of complexity. He remarked on how the OPEN statement in Liberty BASIC is used to open not only disk files, but windows and DLLs. He expressed his desire for a further extension of OPEN for managing TCP/IP sockets. The thing is, I have been planning to do this for some time, and expect to see it in Liberty BASIC v5.0 when it makes its debut.

    Using a command for many different things is called "overloading" by programming language designers. So, the OPEN statement is overloaded in Liberty BASIC. This is one of the techniques I use to try and keep BASIC small. I could have added more commands. Maybe for opening a window I could have added CREATEWIN and for accessing DLLs I could have added MAPDLL or some similar name. This might have been okay, but it doesn't keep the language small. I think is crucially important to minimize growth because of the ever expanding list of things a programming language is expected to handle. If I don't fight growth, pretty soon Liberty BASIC will be unmanagable.

    If you have ideas that are very close to each other (like opening a file, a window, a socket, etc.) it makes a lot of sense to overload the commands that access them. This can be taken too far, but usually I believe that it isn't taken far enough. Programming languages need to be more general.

    The cult of complexity

    Just the other day I noticed that someone posted a review on Download.com which criticized Liberty BASIC for being a beginner's language. Excuse me? We are talking about BASIC aren't we? Beginner's All purpose Symbolic Instruction Code? Did I miss something?

    This reminds me of a software developer I met a few years back at a developer's conference. He asked me about my product, and I gave him a demo. His reaction was "Why would anyone want to use that?" He missed the point entirely. Not everyone has spent the last decade or more of their life developing cutting edge software 40 or more hours a week. If you have to compete with other people, you may well be forced to master the latest and greatest bells and whistles. He forgets that there are scores of people who need to get something done quickly and easily.

    Anyone who programmed in BASIC 20+ years ago will agree that Liberty BASIC has more bells and whistles than any BASIC did back then. I'm actually dissatisfied about that. We should be trying to make programming simpler, not more complicated. There is a certain level of sophistication which adds value, but then there is a line which get crossed where things get very murky. Does that new feature make programming simpler, or harder? It can be hard to tell. The more stuff you have to remember, the harder it is to see the forest for the trees.

    Aside from getting work done (unless you're programming only for enjoyment), programming is more about becoming smarter and not about proving how smart you are.

    BASIC is Special

    Of course BASIC is special!

    I don't know how many times I've run into programmers who smugly stick their noses up in the air at the mention of BASIC. I know I've done the same thing when I hear the name Perl. :-p But in fact, pretty much all programming languages are particularly good for one or more kinds of programming tasks. They're all special!

    Okay, but what makes BASIC special? Like most programming languages, BASIC can be used to create many kinds of software. But, BASIC is especially great for small games and utilities. If you need to write a tool or if you're playing around, and if you need to get something (anything?)working right now, BASIC is probably just what the doctor ordered. If you've just gotta write that "mega does it all" killer app in BASIC because you love BASIC? Don't let me stop you (especially if you're using my software to do it)! ;)

    I know that people who love BASIC often want to make it good for everything. They add this and that until it has all the features of other languages. They mean well, I think. At a certain point this violates the KISS (keep it simple stupid) philosophy that makes BASIC so great at making computers accessible. After all, sledgehammers are great but they sure are heavy. SledgeBASIC anyone?

    So let's keep BASIC special. I know I will!

    What Defines BASIC?

    When you think of BASIC, what comes to mind?

    What is the core language itself? I implemented Liberty BASIC from what I considered to be the essentials of the language. I am not a VB programmer. My own experience programming in BASIC comes mostly from these influences:

    * Benton Harbor BASIC
    * TRS-80 BASIC
    * Applesoft BASIC
    * Commodore BASIC
    * MBASIC
    * GW-BASIC

    Except for Benton Harbor BASIC, these are early flavors of Microsoft BASIC. They all use line numbers and have these commands in common: LET, PRINT, INPUT, GOTO, GOSUB, RETURN, READ, DATA, IF/THEN, FOR/NEXT, DIM, OPEN, CLOSE, etc. There are also functions like VAL, SIN, LOG, LEN, MID$, LEFT$, RIGHT$, STR$, etc.

    They are also all command line interpreters. This is an important feature that is mostly lost in modern BASICs. The interactivity of the language is one of the things that makes it approachable and easy to learn. Most newer BASICs are not interactive, including my own. I'm working on a new BASIC which adds interactive features.

    So is there a BASIC standard? In fact there is an ANSI standard, developed by a commitee. This standard BASIC is largely ignored by the community of BASIC implementors. Microsoft has been the biggest influencer in the BASIC space, and their QBasic became the defacto standard for BASIC. Visual Basic has not been able to overcome QBasic's popularity for the casual user and hobbiest. Perhaps QBasic's inclusion of an immediate mode (approximating a command line interpreter's interactivity) is one of the reasons why it is Microsoft's last real BASIC?

    I'm interested in your feedback on this. My own thoughts are:

    * BASIC has a small core of classic commands. Learn these commands and you should be able to be productive in any version of BASIC in five minutes, or it isn't BASIC.
    * New commands should be added with reluctance.
    * BASIC programmers should not be required to use GUI elements in their programs.
    * The BASIC coder should not have to understand C data types to write a program.
    * BASIC should be interactive by use of a command line or other innovative features.
    * Extensions to any BASIC should not feel like some completely different language so that someone who knows BASIC looks at code written in that dialect and says, "What the HECK is that?!!"

    Your thoughts?

    BASIC and the Original Personal Computers

    Before the IBM PC there were Home Computers, of which there were many, many brands and models, all completely different from each other. Usually a Home Computer plugged into your television set, even though you could buy a monitor if you wanted a sharper picture. I loved the Home Computers because they were all a little different from each other, each inspired by some designer's whim. That was great because it made you think when you saw something that was a new idea.

    Once the standard IBM PC was introduced, the market began to do nothing but make copies of this machine. This was actually a kind of death to innovation, and at a time when small computers were still very immature. Our industry decided that all computers should be like this 'IBM thing' when we didn't really even know yet how to build computers. In most respects, today's PC is still just a faster and bigger version of that now 25 year old design. :-(

    One key thing that was really great about the Home Computer was its programming language, which was almost always BASIC. Each version of BASIC was a little different, but close enough that you could sit down in front of a computer you've never seen before and start writing something right away.

    Another important quality of the Home Computer was its simplicity. Most of the time you only needed a couple of hundred pages to explain how to make any computer's hardware do whatever you wanted. All the graphics and sound, keyboard, joystick, I/O ports, memory maps, etc. were completely documented. And these things were also simple enough that you didn't need a degree to understand how they worked. BASIC made this even easier because you could use the command line interpreter to interactively play with the hardware. This was really personal computing, in the truest sense of the word.

    IBM PC is a misnomer.

    Aspects

    One of the big buzzwords in programming today is 'aspects'. More and more systems claim to be aspect oriented. Just what does this mean?

    An aspect is like a perspective. If you look at the back of your hand, you will see those things that are about its backside. That is an aspect. If we do the same with software, this gives us a useful tool. If we take a video game for example, we might have several aspects:

    - Display
    - Sound
    - User input
    - Game rules and behavior

    What is the point of all this? If we work hard to write libraries of code about these parts of the game, where these different parts of the program don't refer to each other, this gives us a useful level of interdependence, or decoupling as it's calling in software engineering. This is what aspects are for.

    If we make each aspect of our programs independent from each other, this makes them easier to understand, to re-use in other programs, and to debug.

    Most aspect oriented software use objects as a way to make their aspects work, but this isn't required. You can use the tools at your disposal to do the same thing. The main tool is your brain.

    Some tips:

    - Don't use global variables without good reason
    - Give preference to SUBs and FUNCTIONs over GOSUB/RETURN
    - Name things well so it's easy to answer the question "Does that belong in this area of my program?"

    Finally, don't get hung up on the word 'aspect'. It's a useful word for thinking about software design, but it's just one word. ;-)

    Building Systems in BASIC

    Let say you want to write a program in BASIC that manages sales information for a small store. You need to write code for the following things:

    - Data entry+User Interface
    - Database management
    - Reporting
    - Graphing

    Okay, fine. You create a program called salesmanager.bas and create sections of code for each subsystem. As you build your library of code, you run your program to try it out. When you're done trying out your program, you shut it down and go back to writing more code. Then you try your program again, etc.

    This is the traditional way to create programs, and it works great for small programs. When a program gets large, it takes longer and longer to start up the program and try it out.

    What if your BASIC could *also* do it in the following way?

    - Create a program called salesdatabase.bas and write the simplest possible database manager (one that doesn't really do anything). Start it up and give it a runtime name SALESDB. Leave it running.

    - Now create another program called salesui.bas that implements the simplest GUI. Start that up and leave it running.

    - Write a function to salesdatabase.bas for adding a new sale and save it. It becomes available to the salesdatabase.bas program that is already running!

    - Now add a menu and subroutine to open a simple dialog box for the salesui.bas program. This dialog box code contains a call to the add sale subroutine on the SALESDB program. Without restarting the GUI, the menu is available. You can test it immediately!

    Keep adding more code to these programs and 'grow' them a little at a time. Add the reporting and graphing modules to your system in the same incremental way. You can build a large system in this way by 'growing' it in little bite sized ways.

    Objects and BASIC?

    As an implementor of a BASIC language (http://www.libertybasic.com/) I have a lot of people write me with their suggestions. This is a great thing. Some people ask for object oriented features. I know this is all the rage, and I understand object oriented programming well because I've been programming in Smalltalk since 1988, and Java for 3 years. Smalltalk is the first modern object oriented language, and a darn good one.



    Here's the problem. BASIC was not conceived as an object oriented language. Just as many implementors of contemporary BASICs have made the language unrecognizable by piling the features of C and other languages on top of it, an object oriented BASIC risks becoming some other language entirely.



    Any really good object oriented language is objects all the way down. In these languages (Smalltalk and Self for example) even numbers, strings, and boolean values are objects. Everything is treated uniformly. It would be a supreme challenge to redesign BASIC so that it had this kind of uniformity. It just wouldn't look like BASIC anymore. :-(



    This doesn't mean that BASIC couldn't be extended to have some object oriented ideas. To do so it would be important to identify what the simplest and most useful ideas of objects are, and to invent a very small syntax extension for the BASIC language to support these ideas. I think any object oriented extensions should be simple and consistent enough to be learnable in five minutes. The goal should be maximum bang for minimum buck. Otherwise, why bother when there are already so many other object oriented languages?

    Simplicity Revisited

    In my last post I explained that classic BASIC was implemented as an exploratory programming environment. It occurred to me that my earlier post about simplicity touches on an extremely important aspect of BASIC's exploratory qualities.

    List most software today, programming tools do 101+ things. This reminds me of a Nova documentary I saw about jet fighter planes. The cockpit of a modern jet fighter has more dials than a clock store and more buttons than a sewing shop. The documentary explained was that these were all there so that the pilot would be able to do lots of useful things. As it turns out, not many of the things in the cockpit are useful for flying an airplane in combat.

    As an exploratory programming language, early BASIC was simple to learn. There was no GUI. Windows, icons and other graphical features do not always improve software (although they can). There were only a few commands and ideas that you needed to learn. Was this enough? Maybe not, but its simplicity is one of the essential concepts that made it successful.

    "Perfection is achieved, not when there is nothing left to add, but when there is nothing left to take away." --- Antoine de St. Exupery, Wind, Sand, and Stars, 1939

    Exploratory Programming and BASIC

    One idea that hasn't been written much about lately in the computer press is "exploratory programming." This idea was very popular about a decade ago and it refers to powerful programming tools that make it easy and quick to try out different ideas. Smalltalk is one of the best examples of an exploratory programming environment. Smalltalk lets you make objects that "live" in your programming IDE and then you can play with them to see what happens. You don't need to compile a program at all to build software. Why does this matter? Exploratory programming helps make programming easier, more fun, and less intimidating. You can play around with little pieces of the program you're trying to create until you feel that you understand it well enough to put it all together.



    Okay, what does Smalltalk have to do with BASIC? I'm glad you asked. :-) BASIC was originally conceived as an exploratory programming tool. BASIC has an interpreter loop, just like Smalltalk. Write a little code, use RUN to execute just a piece of your program if you like. Stop a running program, check the value of variables and change them. Rewrite just a line of code if you like. Restart the program. Execute code without even adding it to your program, straight from the command line. Most BASICs on home computers would let you play with the hardware, from graphics to audio to devices connected to an I/O port, again straight from the command line. You were free to explore.



    Sadly BASIC is not like this anymore. Almost all BASIC language software today compiles to a program that cannot stopped, tweaked, modifed and restarted. Even our own Liberty BASIC http://www.libertybasic.com are like this (except that Liberty BASIC you can evaluate code in the debugger and by using the eval() function).



    We are working on a new BASIC to bring exploratory programming back. This will not be an old fashioned line numbered interpreter. This new BASIC will provide a workbench where you can make changes to running programs, and where you can try out small or large BASIC snippets just to see what they do.



    More information coming...

    Check out this stream