13 tips on how to comment your source code

Posted by Shashank Krishna Thursday, May 28, 2009

Following are 13 tips on how to comment your source code so that it is easier to understand and maintain over time.

1. Comment each level

Comment each code block, using a uniform approach for each level. For example:

  • For each class, include a brief description, author and date of last modification
  • For each method, include a description of its purpose, functions, parameters and results

Adopting comment standards is important when working with a team. Of course, it is acceptable and even advisable to use comment conventions and tools (such as XML in C# or Javadoc for Java) to facilitate this task.

2. Use paragraph comments

Break code blocks into multiple “paragraphs” that each perform a single task, then add a comment at the beginning of each block to instruct the reader on what is about to happen.

// Check that all data records
// are correct
foreach (Record record in records)
{
if (rec.checkStatus()==Status.OK)
{
. . .
}
}
// Now we begin to perform
// transactions
Context ctx = new ApplicationContext();
ctx.BeginTransaction();
. . .

3. Align comments in consecutive lines

For multiple lines of code with trailing comments, align the comments so they will be easy to read.

const MAX_ITEMS = 10; // maximum number of packets
const MASK = 0x1F; // mask bit TCP

Some developers use tabs to align comments, while others use spaces. Because tab stops can vary among editors and IDEs, the best approach is to use spaces.

4. Don’t insult the reader’s intelligence

Avoid obvious comments such as:

if (a == 5) // if a equals 5
counter = 0; // set the counter to zero

This wastes your time writing needless comments and distracts the reader with details that can be easily deduced from the code.

5. Be polite

Avoid rude comments like, “Notice the stupid user has entered a negative number,” or “This fixes the side effect produced by the pathetically inept implementation of the initial developer.” Such comments do not reflect well upon their author, and you never know who may read these comments in the future: your boss, a customer, or the pathetically inept developer you just insulted.

6. Get to the point

Don’t write more in comments than is needed to convey the idea. Avoid ASCII art, jokes, poetry and hyperverbosity. In short, keep the comments simple and direct.

7. Use a consistent style

Some people believe that comments should be written so that non-programmers can understand them. Others believe that comments should be directed at developers only. In any event, as stated in Successful Strategies for Commenting Code, what matters is that comments are consistent and always targeted to the same audience. Personally, I doubt many non-developers will be reading code, so comments should target other developers.

8. Use special tags for internal use

When working on code as a team, adopt a consistent set of tags to communicate among programmers. For example, many teams use a “TODO:” tag to indicate a section of code that requires additional work:




int Estimate(int x, int y)
{
// TODO: implement the calculations
return 0;
}

Tag comments don’t explain code; rather they seek attention or deliver a message. But if you use this technique, remember to follow up and actually do what the message is asking.

9. Comment code while writing it

Add comments while you write code and it’s fresh in your memory. If you leave comments until the end, it will take you twice as long, if you do it at all. “I have no time to comment,” “I’m in a hurry,” and “The project is delayed” are all simply excuses to avoid documenting your code. Some developers believe you should write comments before code as a way to plan out your ultimate solution. For example:

public void ProcessOrder()
{
// Make sure the products are available
// Check that the customer is valid
// Send the order to the store
// Generate bill
}

10. Write comments as if they were for you (in fact, they are)

When it comes to commenting code, think not only about the developers who will maintain your code in the future, but also think about yourself. In the words of the great Phil Haack:

“As soon as a line of code is laid on the screen, you’re in maintenance mode on that piece of code.”

As a result, we ourselves will be the first beneficiaries (or victims) of our good (or bad) comments.

11. Update comments when you update the code

There is no point in commenting correctly on code if the comments are not changed with the code. Both code and comments must move in parallel, otherwise the comments will actually make life more difficult for developers who maintain your code. Pay special attention to refactoring tools that automatically update code but leave comments unchanged and hence obsolete in the same instant.

12. The golden rule of comments: readable code

One of the basic principles for many developers: Let your code speak for itself. Although one suspects this movement is led by programmers who do not like to write comments, it is true that self-explanatory code can go a long way toward making code that’s easier to understand and can even render comments unnecessary. For example, the code in my Fluid Interfaces article shows how clear self-explanatory code can be:

Calculator calc = new Calculator();
calc.Set(0);
calc.Add(10);
calc.Multiply(2);
calc.Subtract(4);
Console.WriteLine( “Result: {0}”, calc.Get() );

In this example, comments are not needed and would likely violate tip #4. To facilitate readable code, you might consider using proper names (as described in the classic Ottinger’s Rules), ensure correct indentation, and adopt coding style guides. Failure to comply with this tip may result in comments that seem to apologize for bad code.

13. Share these tips with your colleagues

Although tip #10 shows how we ourselves benefit immediately from good comments, these tips will benefit all developers, especially in the context of team working together. Therefore, feel free to share these commenting tips with your colleagues to create code that is easier to understand and maintain.

21 Laws of Computer Programming:

Posted by Shashank Krishna

As any experienced computer programmer knows, there are unwritten laws that govern software development. However there are no penalties for breaking these laws; rather, there is often a reward. Following are 21 Laws of Computer Programming:

  1. Any given program, once deployed, is already obsolete.
  2. It is easier to change the specification to fit the program than vice versa.
  3. If a program is useful, it will have to be changed.
  4. If a program is useless, it will have to be documented.
  5. Only ten percent of the code in any given program will ever execute.
  6. Software expands to consume all available resources.
  7. Any non-trivial program contains at least one error.
  8. The probability of a flawless demo is inversely proportional to the number of people watching, raised to the power of the amount of money involved.
  9. Not until a program has been in production for at least six months will its most harmful error be discovered.
  10. Undetectable errors are infinite in variety, in contrast to detectable errors, which by definition are limited.
  11. The effort required to correct an error increases exponentially with time.
  12. Program complexity grows until it exceeds the capabilities of the programmer who must maintain it.
  13. Any code of your own that you haven’t looked at in months might as well have been written by someone else.
  14. Inside every small program is a large program struggling to get out.
  15. The sooner you start coding a program, the longer it will take.
  16. A carelessly planned project takes three times longer to complete than expected; a carefully planned project takes only twice as long.
  17. Adding programmers to a late project makes it later.
  18. A program is never less than 90% complete, and never more than 95% complete.
  19. If you automate a mess, you get an automated mess.
  20. Build a program that even a fool can use, and only a fool will want to use it.
  21. Users truly don’t know what they want in a program until they use it.

101 Great Computer Programming Quotes

Posted by Shashank Krishna

“People always fear change. People feared electricity when it was invented, didn’t they? People feared coal, they feared gas-powered engines. There will always be ignorance, and ignorance leads to fear. But with time, people will come to accept their silicon masters.”

As Bill Gates once warned, computers have indeed become our silicon masters, pervading nearly every aspect of our modern lives. As a result, some of the greatest minds of our time have pondered the significance of computers and software on the human condition. Following are 101 great quotes about computers, with an emphasis on programming, since after all this is a software development site.


Computers

  1. “Computers are useless. They can only give you answers.”
    (Pablo Picasso)
  2. Computers are like bikinis. They save people a lot of guesswork.”
    (Sam Ewing)
  3. “They have computers, and they may have other weapons of mass destruction.”
    (Janet Reno)
  4. “That’s what’s cool about working with computers. They don’t argue, they remember everything, and they don’t drink all your beer.”
    (Paul Leary)
  5. “If the automobile had followed the same development cycle as the computer, a Rolls-Royce would today cost $100, get a million miles per gallon, and explode once a year, killing everyone inside.”
    (Robert X. Cringely)

Computer Intelligence

  1. “Computers are getting smarter all the time. Scientists tell us that soon they will be able to talk to us. (And by ‘they’, I mean ‘computers’. I doubt scientists will ever be able to talk to us.)”
    (Dave Barry)
  2. “I’ve noticed lately that the paranoid fear of computers becoming intelligent and taking over the world has almost entirely disappeared from the common culture. Near as I can tell, this coincides with the release of MS-DOS.”
    (Larry DeLuca)
  3. “The question of whether computers can think is like the question of whether submarines can swim.”
    (Edsger W. Dijkstra)
  4. “It’s ridiculous to live 100 years and only be able to remember 30 million bytes. You know, less than a compact disc. The human condition is really becoming more obsolete every minute.”
    (Marvin Minsky)

Trust

  1. “The city’s central computer told you? R2D2, you know better than to trust a strange computer!”
    (C3PO)
  2. “Never trust a computer you can’t throw out a window.”
    (Steve Wozniak)

Hardware

  1. “Hardware: The parts of a computer system that can be kicked.”
    (Jeff Pesis)

Software

  1. “Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.”
    (Alan Kay)
  2. “I’ve finally learned what ‘upward compatible’ means. It means we get to keep all our old mistakes.”
    (Dennie van Tassel)

Operating Systems

  1. “There are two major products that come out of Berkeley: LSD and UNIX. We don’t believe this to be a coincidence.”
    (Jeremy S. Anderson)
  2. “19 Jan 2038 at 3:14:07 AM”
    (End of the word according to Unix–2^32 seconds after January 1, 1970)
  3. “Every operating system out there is about equal… We all suck.”
    (Microsoft senior vice president Brian Valentine describing the state of the art in OS security, 2003)
  4. “Microsoft has a new version out, Windows XP, which according to everybody is the ‘most reliable Windows ever.‘ To me, this is like saying that asparagus is ‘the most articulate vegetable ever.‘ “
    (Dave Barry)

Internet

  1. “The Internet? Is that thing still around?”
    (Homer Simpson)
  2. “The Web is like a dominatrix. Everywhere I turn, I see little buttons ordering me to Submit.”
    (Nytwind)
  3. “Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is nothing like Shakespeare.”
    (Blair Houghton)

Software Industry

  1. “The most amazing achievement of the computer software industry is its continuing cancellation of the steady and staggering gains made by the computer hardware industry.”
    (Henry Petroski)
  2. “True innovation often comes from the small startup who is lean enough to launch a market but lacks the heft to own it.”
    (Timm Martin)
  3. “It has been said that the great scientific disciplines are examples of giants standing on the shoulders of other giants. It has also been said that the software industry is an example of midgets standing on the toes of other midgets.”
    (Alan Cooper)
  4. “It is not about bits, bytes and protocols, but profits, losses and margins.”
    (Lou Gerstner)
  5. “We are Microsoft. Resistance Is Futile. You Will Be Assimilated.”
    (Bumper sticker)

Software Demos

  1. “No matter how slick the demo is in rehearsal, when you do it in front of a live audience, the probability of a flawless presentation is inversely proportional to the number of people watching, raised to the power of the amount of money involved.”
    (Mark Gibbs)

Software Patents

  1. “The bulk of all patents are crap. Spending time reading them is stupid. It’s up to the patent owner to do so, and to enforce them.”
    (Linus Torvalds)

Complexity

  1. “Controlling complexity is the essence of computer programming.”
    (Brian Kernigan)
  2. “Complexity kills. It sucks the life out of developers, it makes products difficult to plan, build and test, it introduces security challenges, and it causes end-user and administrator frustration.”
    (Ray Ozzie)
  3. “There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”
    (C.A.R. Hoare)
  4. “The function of good software is to make the complex appear to be simple.”
    (Grady Booch)

Ease of Use

  1. “Just remember: you’re not a ‘dummy,’ no matter what those computer books claim. The real dummies are the people who–though technically expert–couldn’t design hardware and software that’s usable by normal consumers if their lives depended upon it.”
    (Walter Mossberg)
  2. “Software suppliers are trying to make their software packages more ‘user-friendly’… Their best approach so far has been to take all the old brochures and stamp the words ‘user-friendly’ on the cover.”
    (Bill Gates)
  3. “There’s an old story about the person who wished his computer were as easy to use as his telephone. That wish has come true, since I no longer know how to use my telephone.”
    (Bjarne Stroustrup)

Users

  1. “Any fool can use a computer. Many do.”
    (Ted Nelson)
  2. “There are only two industries that refer to their customers as ‘users’.”
    (Edward Tufte)

Programmers

  1. “Programmers are in a race with the Universe to create bigger and better idiot-proof programs, while the Universe is trying to create bigger and better idiots. So far the Universe is winning.”
    (Rich Cook)
  2. Most of you are familiar with the virtues of a programmer. There are three, of course: laziness, impatience, and hubris.”
    (Larry Wall)
  3. “The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.”
    (Seymour Cray)
  4. “That’s the thing about people who think they hate computers. What they really hate is lousy programmers.”
    (Larry Niven)
  5. “For a long time it puzzled me how something so expensive, so leading edge, could be so useless. And then it occurred to me that a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match.”
    (Bill Bryson)
  6. “Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.”
    (Eric Raymond)
  7. “A programmer is a person who passes as an exacting expert on the basis of being able to turn out, after innumerable punching, an infinite series of incomprehensive answers calculated with micrometric precisions from vague assumptions based on debatable figures taken from inconclusive documents and carried out on instruments of problematical accuracy by persons of dubious reliability and questionable mentality for the avowed purpose of annoying and confounding a hopelessly defenseless department that was unfortunate enough to ask for the information in the first place.”
    (IEEE Grid newsmagazine)
  8. “A hacker on a roll may be able to produce–in a period of a few months–something that a small development group (say, 7-8 people) would have a hard time getting together over a year. IBM used to report that certain programmers might be as much as 100 times as productive as other workers, or more.”
    (Peter Seebach)
  9. “The best programmers are not marginally better than merely good ones. They are an order-of-magnitude better, measured by whatever standard: conceptual creativity, speed, ingenuity of design, or problem-solving ability.”
    (Randall E. Stross)
  10. “A great lathe operator commands several times the wage of an average lathe operator, but a great writer of software code is worth 10,000 times the price of an average software writer.”
    (Bill Gates)


Programming

  1. “Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.”
    (Mosher’s Law of Software Engineering)
  2. “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”
    (Bill Gates)
  3. “Writing code has a place in the human hierarchy worth somewhere above grave robbing and beneath managing.”
    (Gerald Weinberg)
  4. “First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack.”
    (George Carrette)
  5. “First, solve the problem. Then, write the code.”
    (John Johnson)
  6. “Optimism is an occupational hazard of programming; feedback is the treatment.”
    (Kent Beck)
  7. “To iterate is human, to recurse divine.”
    (L. Peter Deutsch)
  8. “The best thing about a boolean is even if you are wrong, you are only off by a bit.”
    (Anonymous)
  9. Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration.”
    (Stan Kelly-Bootle)

Programming Languages

  1. “There are only two kinds of programming languages: those people always bitch about and those nobody uses.”
    (Bjarne Stroustrup)
  2. “PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.”
    (Jon Ribbens)
  3. “The use of COBOL cripples the mind; its teaching should therefore be regarded as a criminal offense.”
    (E.W. Dijkstra)
  4. “It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.”
    (E. W. Dijkstra)
  5. “I think Microsoft named .Net so it wouldn’t show up in a Unix directory listing.”
    (Oktal)
  6. “There is no programming language–no matter how structured–that will prevent programmers from making bad programs.”
    (Larry Flon)
  7. “Computer language design is just like a stroll in the park. Jurassic Park, that is.”
    (Larry Wall)

C/C++

  1. “Fifty years of programming language research, and we end up with C++?”
    (Richard A. O’Keefe)
  2. “Writing in C or C++ is like running a chain saw with all the safety guards removed.”
    (Bob Gray)
  3. “In C++ it’s harder to shoot yourself in the foot, but when you do, you blow off your whole leg.”
    (Bjarne Stroustrup)
  4. “C++ : Where friends have access to your private members.”
    (Gavin Russell Baker)
  5. “One of the main causes of the fall of the Roman Empire was that–lacking zero–they had no way to indicate successful termination of their C programs.”
    (Robert Firth)

Java

  1. “Java is, in many ways, C++–.”
    (Michael Feldman)
  2. “Saying that Java is nice because it works on all OSes is like saying that anal sex is nice because it works on all genders.”
    (Alanna)
  3. “Fine, Java MIGHT be a good example of what a programming language should be like. But Java applications are good examples of what applications SHOULDN’T be like.”
    (pixadel)
  4. If Java had true garbage collection, most programs would delete themselves upon execution.”
    (Robert Sewell)

Open Source

  1. “Software is like sex: It’s better when it’s free.”
    (Linus Torvalds)
  2. “The only people who have anything to fear from free software are those whose products are worth even less.”
    (David Emery)

Code

  1. “Good code is its own best documentation.”
    (Steve McConnell)
  2. Any code of your own that you haven’t looked at for six or more months might as well have been written by someone else.”
    (Eagleson’s Law)
  3. “The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.”
    (Tom Cargill)

Software Development

  1. “Good programmers use their brains, but good guidelines save us having to think out every case.”
    (Francis Glassborow)
  2. “In software, we rarely have meaningful requirements. Even if we do, the only measure of success that matters is whether our solution solves the customer’s shifting idea of what their problem is.”
    (Jeff Atwood)
  3. “Considering the current sad state of our computer programs, software development is clearly still a black art, and cannot yet be called an engineering discipline.”
    (Bill Clinton)
  4. “You can’t have great software without a great team, and most software teams behave like dysfunctional families.”
    (Jim McCarthy)

Debugging

  1. “As soon as we started programming, we found to our surprise that it wasn’t as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.”
    (Maurice Wilkes discovers debugging, 1949)
  2. “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are–by definition–not smart enough to debug it.”
    (Brian Kernighan)
  3. “If debugging is the process of removing bugs, then programming must be the process of putting them in.”
    (Edsger W. Dijkstra)

Quality

  1. “I don’t care if it works on your machine! We are not shipping your machine!”
    (Vidiu Platon)
  2. “Programming is like sex: one mistake and you’re providing support for a lifetime.”
    (Michael Sinz)
  3. “There are two ways to write error-free programs; only the third one works.”
    (Alan J. Perlis)
  4. “You can either have software quality or you can have pointer arithmetic, but you cannot have both at the same time.”
    (Bertrand Meyer)
  5. “If McDonalds were run like a software company, one out of every hundred Big Macs would give you food poisoning, and the response would be, ‘We’re sorry, here’s a coupon for two more.’ “
    (Mark Minasi)
  6. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
    (Martin Golding)
  7. “To err is human, but to really foul things up you need a computer.”
    (Paul Ehrlich)
  8. “A computer lets you make more mistakes faster than any invention in human history–with the possible exceptions of handguns and tequila.”
    (Mitch Radcliffe)

Predictions

  1. “Everything that can be invented has been invented.”
    (Charles H. Duell, Commissioner, U.S. Office of Patents, 1899)
  2. “I think there’s a world market for about 5 computers.”
    (Thomas J. Watson, Chairman of the Board, IBM, circa 1948)
  3. “It would appear that we have reached the limits of what it is possible to achieve with computer technology, although one should be careful with such statements, as they tend to sound pretty silly in 5 years.”
    (John Von Neumann, circa 1949)
  4. “But what is it good for?”
    (Engineer at the Advanced Computing Systems Division of IBM, commenting on the microchip, 1968)
  5. “There is no reason for any individual to have a computer in his home.”
    (Ken Olson, President, Digital Equipment Corporation, 1977)
  6. “640K ought to be enough for anybody.”
    (Bill Gates, 1981)
  7. “Windows NT addresses 2 Gigabytes of RAM, which is more than any application will ever need.”
    (Microsoft, on the development of Windows NT, 1992)
  8. “We will never become a truly paper-less society until the Palm Pilot folks come out with WipeMe 1.0.”
    (Andy Pierson)
  9. “If it keeps up, man will atrophy all his limbs but the push-button finger.”
    (Frank Lloyd Wright)

Caches

Caches are a simple way to improve the performance of an application that reads data from a "slow" source such as files on disk or rows of data from a database table, but may need to re-read the same data multiple times. The idea is simple: instead of discarding the data after using it, keep it in memory so that it doesn't have to be re-read later.

For example, a simple way to organize this for files might be to create a HashMap that maps the file names to objects containing the file data. When your application needs a particular file it first checks the map to see if it already has the data; if it doesn't, it reads the file and places it in the map in case it needs it again later.

LRU caches

The problem with this simple method is that your application could use a vast amount of memory. Once read in, a file is in the cache for the lifetime of the application whether or not it is ever used again. For an application such as a server that is intended to stay up and running for weeks or months at a time, this is probably not acceptable.

What's needed is a cache that automatically discards entries that haven't been accessed for some time so as to limit the amount of space being used. Such as cache is called an LRU Cache. LRU stands for "Least Recently Used", which refers to the policy of removing the oldest, or least-recently used entries to make space for new data.

LRU caches have a maximum number of data items that they will hold and these items are usually arranged in a list. When an item is added to the cache, and every time it is accessed after that, it is automatically moved to the head of the list. If the cache is full and a slot is required for a new item, the cache makes room by discarding the entry at the tail of the list - the least-recently used item.

The java.util.LinkedHashMap class

LinkedHashMap is a subclass of java.util.HashMap that adds a couple of useful features. One is that by default the iteration order reflects the order that entries are added to the map, rather than the rather haphazard order of a HashMap.

The other feature - the one we're interested in here - is that LinkedHashMap has an option to use access-order instead of insertion order, and includes a way to remove the least-recently accessed entries automatically. This makes it well suited for creating LRU caches.

Creating a cache class

The simplest way to create a cache using LinkedHashMap is to extend it. Here is an example:


public class Cache extends LinkedHashMap
{
private final int capacity;

public Cache(int capacity)
{
super(capacity + 1, 1.1f, true);
this.capacity = capacity;
}

protected boolean removeEldestEntry(Entry eldest)
{
return size() > capacity;
}
}



Note that the constructor takes as an argument the maximum number of entries we want a Cache object to hold. The superclass constructor has three arguments: the initial capacity of the map, the load factor, and a boolean argument that tells the LinkedHashMap constructor to keep entries in access order instead of the default insertion order. (See the java.util.HashMap API documentation for a description of the initial capacity and load factor.) In this case we set the initial capacity to be one more than our required cache size - this is because new entries are added before any are removed, so for example if we want to hold 100 entries the cache will actually contain 101 for an instant when new data is added. Setting the load factor to 1.1 ensures that the rehashing mechanism of the underlying HashMap class isn't triggered - this isn't a vital point but helps a little with efficiency at run-time.

The removeEldestEntry() method overrides a default implementation in LinkedHashMap and is where we determine the policy for removing the oldest entry. In this case, we return true when the cache has more entries than our defined capacity.

Using the cache

Using the cache is simple - just use a suitable key to access the cache; if the data is in the cache we can read it from there. If it's not there we pull it from the slow medium and add it to the cache so that it's in place if needed later:


Cache cache = new Cache(100);
// ...

String filename = "file.txt";
String filedata = (String) cache
.get(filename);
if (filedata == null)
{
// Read filedata from file system here...
cache.put(filename, filedata);
}

How does it perform?

Our basic implementation should work just fine but we may need to know how effective it is in a given application. One measure of how well a cache is performing is Hit Rate, which tells us how many cache accesses are "hits" - that is, how many times the required data was found in the cache for a given number of accesses. Hit rate is usually expressed as a percentage - a hit rate above 80% is usually pretty good.

We can add a few things to our Cache class to make it possible to monitor performance so that we can tune the cache by setting an optimum size. We need a counter for the number of accesses and another for the number of hits. We will need getter methods to allow us to retrieve those values after the cache has been running for a time, and finally we must override the get() method to update the counts. Here is our Cache class complete with these new members:

public class Cache extends LinkedHashMap
{
private final int capacity;
private long accessCount = 0;
private long hitCount = 0;

public Cache(int capacity)
{
super(capacity + 1, 1.1f, true);
this.capacity = capacity;
}

public Object get(Object key)
{
accessCount++;
if (containsKey(key))
{
hitCount++;
}
Object value = super.get(key);
return value;
}

protected boolean removeEldestEntry(Entry eldest)
{
return size() > capacity;
}

public long getAccessCount()
{
return accessCount;
}

public long getHitCount()
{
return hitCount;
}
}


One point to note is that calls to the containsKey() method don't update the access counts; we may want to override that method also, so that the hit rate isn't skewed by code such as this:

 
if (cache.containsKey(filename))
{
filedata = (String) cache
.get(filename);
}
else
{
// Read filedata from file system here...
cache.put(filename, filedata);
}

Omegle....Anonymous chatting..

Posted by Shashank Krishna Monday, May 4, 2009


What is Omegle? It’s a chat room that pairs you randomly with someone else. Both chatters are anonymous, identified only by the handle “Stranger.” You can chat about anything you like. You can share data or talk about the weather. You can make a new friend or frustrate a stranger until he or she chooses to disconnect from the conversation. It’s pretty much a free-for-all.

Either party can disconnect from the conversation at any point. If the conversation isn’t going anywhere or the other chatter goes idle, you can skip out and try again. You may end up chatting with a curious Web celebrity. It might even be yours truly, so be nice.Founded by an 18 yr old Leif K-Brooks this site provides no profiles for its chat users....

CHECK OUT THE BLOG
Reblog this post [with Zemanta]

Are You Planning on Quitting Facebook? Why?

@Flickr

www.flickr.com

About Me

My Photo
Shashank Krishna
Bangalore, up, India
nothin much to say.........doin B.tech in IIIT allahabad loves bloggingn hacking.... :) and loooves blogging
View my complete profile

ads2

topads