Does C# 6 make it possible to imply type inference (not explicitly use the var keyword)? - c#-6.0

This is an odd question, I know.
Earlier this week, I was browsing hacker news and glossed past an article about the power of C# 6. I meant to 'pocket' the link at the time but I didn't and now I can't find the article again.
Long story short, there was an example of code which looked roughly like this...
using static Variables;
public class Blah
{
public Blah()
{
s = "something"
Console.WriteLine(s);
}
}
... as if to say, somehow it was possible using some magical combination of C# 6 features to remove the 'var' element of that equation and have valid code.
I'm struggling to see how that's possible without some extra Roslyn magic and even then, I'd struggle.
If you know where the article is please let me know. If not, is this even remotely possible? I'm fairly confident it would be an odd thing to do,..I'm just intrigued.
Thanks in advance.

Related

Cleaning Functions containing if statements

I hope that this is the right place to ask (if not please tell me). I am currently trying to create a game while following Robert C. Martins book "Clean Code" in an effort to improve the readability of my code. I am not totally happy with how many of my functions work however, as more often than not I will need to check various variables before I execute a command. For example:
private void checkScoreAndIncreaseDifficulty() {
if(eater.getScore()%400==0){
world.increaseDifficulty();
}
According to the book I am following functions should only do one thing, but when an "if" statement is involved the functions purpose (to me) seems to naturally increase. The name of the above function is checkScoreAndIncreaseDifficulty which is quite clearly two things but I cannot think of how to reduce it. I feel the solution is very simple but it just is not coming to me. Any advice would be appreciated.
Names of functions are supposed to describe what the function does,not how achieves something. So naming checkScoreAndIncreaseDifficulty is wrong imo. It should be something similar to IncreaseDifficulty. Moreover if you do not feel that names of your code elements do not give enough insight on what the function / class/ variable does, you can always comment your code. :)
Also, the "correct" place to write your conditional statement depends entirely on your application : if difficulty will increase only if the user satisfies some condition, then that condition should be included in the function that increases difficulty. If the difficulty might be increased by other means, then the function should only execute actions that increase difficulty and leave the decision whether to increase difficulty or not to the caller.
I don't see any way to make this method cleaner than it is. It checks the score, and then hands of the increaseDifficulty to another method. What more can you ask?
I think there's also a risk in trying to make methods as minimal as they can possibly be. At some point, you need to dig through a dozen methods and functions spread through your entire codebase in order to understand what a single method or function does. That's no good either.
As far as I'm concerned, your code hits the sweet spot. The cumbersome name is indeed an issue, but not a serious one, and easy enough to fix, if you really want to.
Why don't you use two separate functions(you can do it also with only first function) like this:
private bool isScoreEnough() {
if(eater.getScore()%400==0)
return true;
}
private void increaseDifficulty(){
world.increaseDifficulty();
}
and in your program:
if(isScoreEnough())
increaseDifficulty();
You are setting difficulty level in the function. Depending on score you increase/decrease the difficulty level. That is perfectly fine - as long as the function does the job of determining and setting difficulty level only. Function name has scope for improvement:
private void setDifficultyLevel() {
if (eater.getScore()%400 == 0) {
world.increaseDifficulty();
}
}
Obviously you won't find much code without any if statement, programs have to make decisions based on state, input or whatever. Avoiding if statements at all is also not the key message of "Clean Code". What you should avoid are for example endless if-else constructs if one class does the work of three logical cases - you should have three classes then.
Your method is already pretty short, but if you want to apply one of Martin's principles (a good name spares comments etc.) even further you could use something like:
if (scoreRequiresIncreaseInDifficulty()) {
increaseDifficulaty();
}
and then implement the two methods. However, I don't think this makes much sense in your case unless you will need the same calls multiple times and want to maintain the flexibility to change when the score requires a more difficult game in a single place.
You want to increase difficulty every 400 score points gathered by the eater, right?
So, you would need the eater to allow subscribing for score changes:
interface Eater {
void addScoreChangedListener(ScoreChangedListener listener);
}
interface ScoreChangedListener {
public void onScoreChanged(Score previousScore, Score newScore);
}
The implementation of Eater would hold a list of all score change listeners and invoke the onScoreChanged on each of them when the score changes. See the Observer pattern.
And then when bootstrapping your game:
Eater eater = ....
eater.addScorechangedListener(new DifficultyAdjustScoreChangeListener());
And you are done!
The implementation of DifficultyAdjustScoreChangeListener need to have the if, though, but that's ok:
class DifficultyAdjustScoreChangeListener implements ScoreChangedListener {
public void onScoreChanged(Score previousScore, Score newScore) {
if (newScore.value() % 400 == 0) {
world.increaseDifficulty();
}
}
}

Coding-style: How to improve coding-styles and standards at a company

What are the best ways to improve the standards of coding-styles at a company? Let's use C# as an example here.
I guess there are many differences between developers that need to be taken into consideration. The concrete ones could be education, experience and past programming-languages.
How does one justify that something is right over something else?
One person may say "I move my body to the place where I earn my money with my 4-wheeled vehicle". So why is it more "right" to say "I drive to work in my car"?
Some people might like code more explicit with more lines of code. Some might like more tight code.
// Explicit
string text = defaultValue;
if (string.IsNullOrEmpty(text)) {
text = fallbackValue;
}
// Tighter
string text = defaultValue ?? fallbackValue;
Or the old protective programming-style, where you check for error-cases in the beginning and not wrap the whole method body inside a positive if-clause:
public string ChangeText(string text)
{
if (!string.IsNullOrEmpty(text))
{
// Do a lot of stuff
}
else {
throw new Exception();
}
}
// vs.
public string ChangeText(string text)
{
if (string.IsNullOrEmpty(text)) {
throw new Exception();
}
// Do a lot of stuff
}
Is the old "I'm having troubles reading this code" valid here? It's the same situation that was when Generics was introduced to C#, people had an initial trouble reading it.
Where is the line drawn between unreadable code and code that some developers are not used to?
Which part of Phil Haacks "7 Stages of new language keyword grief" has valid points here?
Are there any easy ways to set coding-standards and uphold them in a company?
UPDATE: Take in consideration things like variable-naming, that can't really be defined in a document. Or can it?
The easiest way to set coding-standards at a company:
Create a Standards Document and enforce it.
...people love to complain about code quality, but few will sit down and take the time to create a standards document. It's worth the effort and as long as you can enforce it (code reviews, etc.) then you're bound to notice an improvement in your code.
You always can use free tools like StyleCop from Microsoft.
You can disable or modify rules you don't like
There are two main sides of coding style:
"Where do I put the opening brace?" type issues - These are usually unimportant, i.e. there are no real reasons to prefer one style over the other.
Actual coding rules, like do we use return's in the middle of a function.
The way I see it, for #1 type issues, there is no point in any debate. Just set a standard in a standards document, and enforce it (more on this later).
As for the second issue, I'm honestly not sure whether it should be regulater. I personally love sprinkling functions with return values to check for error conditions, and I know some people who cringe at the practice. But at the end of the day, we can usually read each other's code just fine. These kinds of issues are much more about how you prefer expressing yourself, what is easier for you to write, and I wouldn't want a company making rules that get to this level.
As for how to enforce things, standards documents are good, but in my experience, are just never read or followed closely, and are soon forgotten. The best way is to have some kind of automated tool which tells you that you're violating the standard.
For example, even as a completely new Java programmer, I knew when to uppercase/lowercase my identifiers, simply because Eclipse let me (quietly, unobtrusively) know what the standard is.
First, you will always have to enforce the coding styles - there will never be a consent.
That's, why I would try to automate the check for consistency. Depending on your language you can use StyleCop (for .Net) or something like indent under linux.
Every developer can work with his own code style in his environment (the reformat can be very easy, depending on your environment), but all checked-in code has to be of the company's style.
Which style do you choose? Well, often there are already popular styles - depending on the language. For your example (C#) I would choose the Microsoft style. At last: only the project manager (senior programmer) has the right to adjust it.
Most companies use Coding-Style-Guidelines/Conventions. These are documents telling that you should always do braces around the if body even for one command, that you should indent with tabs/spaces, and so on.
There are a lot of tools for (automatically) check and enforce the coding-style. (An example for the java-world is checkstyle, which can be integrated into eclipse and also in a continuous integration solution like 'hudson'.)
How does one justify that something is
right over something else?
Easy: just don't. Pick a coding style, communicate it, and enforce it.
I think consistency is important here. There's not a lot of point in getting into a semantic debate over which way is better than the other unless the current methodology is particularly bad.
What is important is that the team writes their code consistently so that if someone resigns or gets hit by a bus then his/her colleagues know what is going on with the code when they are forced to work with it.

Should a method parameter name specify its unit in its name?

Of the following two options for method parameter names that have a unit as well as a value, which do you prefer and why? (I've used Java syntax, but my question would apply to most languages.)
public void move(int length)
or
public void move(int lengthInMetres)
Option (1) would seem to be sufficient, but I find that when I'm coding/typing, my IDE can indicate to me I need a length value, but I typically have to break stride and look up the method's doco to determine the units, so that I pass in the correct value (and not kilometres instead of metres for example). This can be an annoying interruption to a thought process. Option (2) alleviates this problem, but can be verbose, particularly if your unit is metresPerSecondSquared or some such. Which do you think is the best?
I would recommend making your parameter (and method) names as clear as possible, even if they become wordy. You'll be glad when you look at or use the code in 6 months time, or when someone else has to look at your code.
If you think the names are becoming too long, consider rewording them. In your example you could use parameter name int Metres that would probably be clear enough. Consider changing the method name, eg public void moveMetres(int length).
In Visual Studio, the XML comments generated when you enter 3 comment symbols above a method definition will appear in Intellisense hints when you use the method in other locations. Other IDEs may have similar functionality.
Abbreviations should be used sparingly. If absolutely necessary only use commonly known and/or relevant industry-standard abbreviations and be consistent, ie use the same abbreviation everywhere.
Take a step back. Write the code then move on to something else. Come back the next day and check to see if the names are still clear.
Peer reviews can help too. Ask someone who knows the programming language (or just thinks logically), but not the specific functionality, if your naming scheme is clear enough or to help brainstorm alternatives. They might be the poor sap who has to maintain your code in the future!
I would prefer the second approach (i.e. lengthInMeters) as it describes the input needed for the method accurately. The fact that you find it confusing to figure out the units when you are just writing the code would imply it would be much more confusing when you (or some one) looks at the same piece of code later. As regard to issue of the variable name being longer you can find ways to abbreviate it (say "mtrsPerSecondSquared").
Also in defence second approach, the book Code Complete mentions a research that indicates, effort required to debug a program was minimized when variables had names averaged to 10 to 16 characters.

Is it possible to write good and understandable code without any comments?

Can any one suggest what is the best way to write good code that is understandable without a single line of comments?
I once had a professor when I was in college tell me that any good code should never need any comments.
Her approach was a combination of very precise logic split out into small functions with very descriptive method/property/variable names. The majority of what she presented was, in fact, extremely readable with no comments. I try to do the same with everything I write...
Read Code Complete, 2nd Edition cover to cover. Perhaps twice.
To give some specifics:
Making code readable
Eliminating code repetition
Doing design/architecture before you write code
I like to 'humanise' code, so instead of:
if (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200){
doSomething();
}
I'll do this:
bool starIsBright;
starIsBright = (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200);
if(starIsBright){
doSomething();
}
In some cases - yes, but in many cases no. The Yes part is already answered by others - keep it simple, write it nicely, give it readable names, etc. The No part goes to when the problem you solve in code is not a code problem at all but rather domain specific problem or business logic problem. I've got no problem reading lousy code even if it doesn't have comments. It's annoying, but doable. But it's practically impossible to read some code without understanding why is it like this and what is it trying to solve. So things like :
if (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200){
doSomething();
}
look nice, but could be quite meaningless in the context of what the program is actually doing. I'd rather have it like this:
// we do this according to the requirement #xxxx blah-blah..
if (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200){
doSomething();
}
Well written code might eliminate the need for comments to explain what you're doing, but you'll still want comments to explain the why.
If you really want to then you would need to be very detailed in your variable names and methods names.
But in my opinion, there is no good way to do this. Comments serve a serious purpose in coding, even if you are the only one coding you still sometimes need to be reminded what part of the code you're looking at.
Yes, you can write code that doesn't need comments to describe what it does, but that may not be enough.
Just because a function is very clear in explaining what it does, does not, by itself, tell you why it is doing what it does.
As in everything, moderation is a good idea. Write code that is explanatory, and write comments that explain why it is there or what assumptions are being made.
I think that the concept of Fluent Interfaces is really a good example of this.
var bob = DB.GetCustomers().FromCountry("USA").WithName("Bob")
Clean Code by Robert C. Martin contains everything you need to write clean, understandable code.
Use descriptive variable names and descriptive method names. Use whitespace.
Make your code read like normal conversation.
Contrast the use of Matchers in Junit:
assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));
with the traditional style of assertEquals:
assertEquals(3, x);
When I look at the assertEquals statement, it is not clear which parameter is "expected" and which is "actual".
When I look at assertThat(x, is(3)) I can read that in English as "Assert that x is 3" which is very clear to me.
Another key to writing self-documenting code is to wrap any bit of logic that is not clear in a method call with a clear name.
if( (x < 3 || x > 17) && (y < 8 || y > 15) )
becomes
if( xAndYAreValid( x, y ) ) // or similar...
I'm not sure writing code that is so expressive that you don't need comments is necessarily a great goal. Seems to me like another form of overoptimization. If I were on your team, I'd be pleased to see clear, concise code with just enough comments.
In most cases, yes, you can write code that is clear enough that comments become unnecessary noise.
The biggest problem with comments is there is no way to check their accuracy. I tend to agree with Uncle Bob Martin in chapter 4 of his book, Clean Code:
The proper use of comments is to compensate for our failure to express ourself in
code. Note that I used the word failure. I meant it. Comments are always failures. We must
have them because we cannot always figure out how to express ourselves without them,
but their use is not a cause for celebration.
So when you find yourself in a position where you need to write a comment, think it
through and see whether there isn’t some way to turn the tables and express yourself in
code. Every time you express yourself in code, you should pat yourself on the back. Every
time you write a comment, you should grimace and feel the failure of your ability of
expression.
Most comments are either needless redundancy, outright fallacy or a crutch used to explain poorly written code. I say most because there are certain scenarios where the lack of expressiveness lies with the language rather than the programmer.
For instance the copyright and license information typically found at the beginning of a source file. As far as I'm aware no known construct exists for this in any of the popular languages. Since a simple one or two line comment suffices, its unlikely that such a construct will be added.
The original need for most comments has been replaced over time by better technology or practices. Using a change journal or commenting out code has been supplanted with source control systems. Explanatory comments in long functions can be mitigated by simply writing shorter functions. etc.
You usually can turn your comment into a function name something like:
if (starColourIsGreaterThanThreshold(){
doSomething();
}
....
private boolean starColourIsGreaterThanThreshold() {
return starColour.red > THRESHOLD &&
starColour.blue > THRESHOLD &&
starColour.green > THRESHOLD
}
I think comments should express the why, perhaps the what, but as much as possible the code should define the how (the behavior).
Someone should be able to read the code and understand what it does (the how) from the code. What may not be obvious is why you would want such behavior and what this behavior contributes to the overall requirements.
The need to comment should give you pause, though. Maybe how you are doing it is too complicated and the need to write a comment shows that.
There is a third alternative to documenting code - logging. A method that is well peppered with logging statements can do a lot to explain the why, can touch on the what and may give you a more useful artifact than well named methods and variables regarding the behavior.
If you want to code entirely without comments and still have your code be followable, then you'll have to write a larger number of shorter methods. Methods will have to have descriptive names. Variables will also have to have descriptive names. One common method of doing this is to give variables the name of nouns and to give methods the names of verbal phrases. For example:
account.updateBalance();
child.givePacifier();
int count = question.getAnswerCount();
Use enums liberally. With an enum, you can replace most booleans and integral constants. For example:
public void dumpStackPretty(boolean allThreads) {
....
}
public void someMethod() {
dumpStackPretty(true);
}
vs
public enum WhichThreads { All, NonDaemon, None; }
public void dumpStackPretty(WhichThreads whichThreads) {
....
}
public void someMethod() {
dumpStackPretty(WhichThreads.All);
}
Descriptive names is your obvious first bet.
Secondly make sure each method does one thing and only one thing. If you have a public method that needs to do many things, split it up into several private methods and call those from the public method, in a way that makes the logic obvious.
Some time ago I had to create a method that calculated the correlation of two time series.
To calculate the correlation you also need the mean and standard deviation. So I had two private methods (well actually in this case they were public as they could be used for other purposes (but assuming they couldn't then they would be private)) for calculating A) the mean, B) the standard deviation.
This sort of splitting up of function into the smallest part that makes sense is probably the most important thing to make a code readable.
How do you decide where to break up methods. My way is, if the name is obvious e.g. getAddressFromPage it is the right size. If you have several contenders you are probably trying to do too much, if you can't think of a name that makes sense you method may not "do" enough - although the latter is much less likely.
I don't really think comments are a good idea in most cases. Comments don't get checked by the compiler so they so often are misleading or wrong as the code changes over time. Instead, I prefer self documenting, concise methods that don't need comments. It can be done, and I have been doing it this way for years.
Writing code without comments takes practice and discipline, but I find that the discipline pays off as the code evolves.
It may not be comments, but, to help someone better understand what it going on you may need some diagrams explaining how the program should work, as, if a person knows the big picture then it is easier to understand code.
But, if you are doing something complex then you may need some comments, for example, in a very math intensive program.
The other place I find comments useful and important, is to ensure that someone doesn't replace code with something that looks like it should work, but won't. In that case I leave the bad code in, and comment it out, with an explanation as to why it shouldn't be used.
So, it is possible to write code without comments, but only if you are limited in what types of applications you are writing, unless you can explain why a decision was made, somewhere, and not call it a comment.
For example, a random generator can be written many ways. If you pick a particular implementation it may be necessary to explain why you picked that particular generator, as the period may be sufficiently long for current requirements, but later the requirements may change and your generator may not be sufficient.
I believe it's possible, if you consider the fact that not everybody likes the same style. So in order to minimize comments, knowing your "readers" is the most important thing.
In "information systems" kind-of software, try using declarative sentence, try to approximate the code line to a line in english, and avoid "mathematical programming" (with the i,j and k for index, and the one-liners-to-do-a-lot) at all costs.
I think code can be self-documenting to a large degree, and I think it's crucial, but reading even well-written code can be like looking at cells of the human body with a microscope. It sometimes takes comments to really explain the big picture of how pieces of the system fit together, especially if it solves a really complex and difficult problem.
Think about special data structures. If all that computer scientists had ever published about data structures were well-written code, few would really understand the relative benefit of one data structure over another -- because Big-O runtime of any given operation is sometimes just not obvious from reading the code. That's where the math and amortized analysis presented in articles come in.

What's the least useful comment you've ever seen? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.
However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are too short, are too cryptic, or are just plain wrong.
As a cautonary tale, could you share something you've seen that was really just that bad, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What should have gone in there instead?
See also:
When NOT to comment your code
How do you like your comments? (Best Practices)
What is the best comment in source code you have ever encountered?
Just the typical Comp Sci 101 type comments:
$i = 0; //set i to 0
$i++; //use sneaky trick to add 1 to i!
if ($i==$j) { // I made sure to use == rather than = here to avoid a bug
That sort of thing.
Unfilled javadoc boilerplate comments are particularly useless. They consume a lot of screen real estate without contributing anything useful. And the worst part is that where one such comment appears, hundreds of others are surely lurking behind.
/**
* Method declaration
*
*
* #param table
* #param row
*
* #throws SQLException
*/
void addTransactionDelete(Table table, Object row[]) throws SQLException {
I've found myself writing this little gem before:
//#TODO: Rewrite this, it sucks. Seriously.
Usually it's a good sign that I've reached the end of my coding session for the night.
// remember to comment code
wtf? :D
Something like this:
// This method takes two integer values and adds them together via the built-in
// .NET functionality. It would be possible to code the arithmetic function
// by hand, but since .NET provides it, that would be a waste of time
private int Add(int i, int j) // i is the first value, j is the second value
{
// add the numbers together using the .NET "+" operator
int z = i + j;
// return the value to the calling function
// return z;
// this code was updated to simplify the return statement, eliminating the need
// for a separate variable.
// this statement performs the add functionality using the + operator on the two
// parameter values, and then returns the result to the calling function
return i + j;
}
And so on.
Every comment that just repeats what the code says is useless. Comments should not tell me what the code does. If I don't know the programming language well enough, to understand what's going on by just reading the code, I should not be reading that code at all. Comments like
// Increase i by one
i++;
are completely useless. I see that i is increased by one, that is what the code says, I don't need a comment for that! Comments should be used to explain why something is done (in case it is far from being obvious) or why something is done that way and not any other way (so I can understand certain design decisions another programmer made that are by far not obvious at once). Further comments are useful to explain tricky code, where it is absolutely not possible to determine what's going on by having a quick look at the code (e.g. there are tricky algorithms to count the number of bits set in a number; if you don't know what this code does, you have no chance of guessing what goes on there).
Thread.Sleep(1000); // this will fix .NET's crappy threading implementation
I once worked on a project with a strange C compiler. It gave an error on a valid piece of code unless a comment was inserted between two statements. So I changed the comment to:
// Do not remove this comment else compilation will fail.
And it worked great.
I don't believe it. I came into this question after it had 22 answers, and no one pointed out the least possibly useful type of comment:
comments that are wrong.
It's bad enough that people write superfluous comments that get in the way of understanding code, but when someone writes a detailed comment explaining how something works, and it's either wrong in the first place, or wrong after the code was changed without changing the comment (much more likely scenario), that is definitely the worst kind of comment.
GhostDoc comes up with some pretty interesting ones on its own.
/// <summary>
/// Toes the foo.
/// </summary>
/// <returns></returns>
public Foo ToFoo()
// secret sauce
// Don't know why we have to do this
try
{
...some code...
}
catch
{
// Just don't crash, it wasn't that important anyway.
}
*sigh
Came across a file once. Thousands of lines of code, most of it quite horrendous. Badly named variables, tricky conditionals on loops and one comment buried in the middle of the file.
/* Hmmm. A bit tricky. */
//' OOOO oooo that smell!! Can't you smell that smell!??!??!!!!11!??/!!!!!1!!!!!!1
If Not Me.CurrentMenuItem.Parent Is Nothing Then
For Each childMenuItem As MenuItem In aMenuItem.Children
do something
Next
If Not Me.CurrentMenuItem.Parent.Parent Is Nothing Then
//'item is at least a grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
do something
Next
Next
If Not Me.CurrentMenuItem.Parent.Parent.Parent Is Nothing Then
//'item is at least a grand grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
For Each grandgrandchildMenuItem As MenuItem In grandchildMenuItem.Children
do something
Next
Next
Next
End If
End If
End If
Default comments inserted by IDEs.
The last project I worked on which used WebSphere Application Developer had plenty of maintenance developers and contractors who didn't seem to be bothered by the hundreds, if not thousands of Java classes which contained the likes of this:
/**
* #author SomeUserWhoShouldKnowBetter
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
There was always that split-second between thinking you'd actually found a well-commented source file and realising that, yup, it's another default comment, which forced you to use SWEAR_WORD_OF_CHOICE.
I saw this comment yesterday in a C# app:
//TODO: Remove this comment.
My favorite all-time comment.
/* our second do loop */
do {
Whoever wrote it - you know who you are.
a very large database engine project in C many many years ago - thousands of lines of code with short and misspelled variable names, and no comments... until way deep in nested if-conditions several thousands of lines into the module the following comment appeared:
//if you get here then you really f**ked
by that time, i think we knew that already!
In a huge VB5 application
dim J
J = 0 'magic
J = J 'more magic
for J=1 to 100
...do stuff...
The reference is obviously THIS ... and yes, the application without those two lines fails at runtime with an unknown error code. We still don't know why.
Taken from one of my blog posts:
In the process of cleaning up some of the source code for one of the projects I manage, I came across the following comments:
/*
MAB 08-05-2004: Who wrote this routine? When did they do it? Who should
I call if I have questions about it? It's worth it to have a good header
here. It should helps to set context, it should identify the author
(hero or culprit!), including contact information, so that anyone who has
questions can call or email. It's useful to have the date noted, and a
brief statement of intention. On the other hand, this isn't meant to be
busy work; it's meant to make maintenance easier--so don't go overboard.
One other good reason to put your name on it: take credit! This is your
craft
*/
and then a little further down:
#include "xxxMsg.h" // xxx messages
/*
MAB 08-05-2004: With respect to the comment above, I gathered that
from the filename. I think I need either more or less here. For one
thing, xxxMsg.h is automatically generated from the .mc file. That might
be interesting information. Another thing is that xxxMsg.h should NOT be
added to source control, because it's auto-generated. Alternatively,
don't bother with a comment at all.
*/
and then yet again:
/*
MAB 08-05-2004: Defining a keyword?? This seems problemmatic [sic],
in principle if not in practice. Is this a common idiom?
*/
AHHHRRRGGHHH Just found this in some ancient code, bet the guy thought he was pretty funny
private
//PRIVATE means PRIVATE so no comments for you
function LoadIt(IntID: Integer): Integer;
The worst comment is one that gives a wrong explanation of what the code does.
That is worse than no comment at all.
I've seen this kind of thing in code with way too many comments (that shouldn't be there because the code is clear enough on its own), and it happens mostly when the code is updated (refactored, modified, etc.) but the comments aren't updated along with it.
A good rule of thumb is: only write comments to explain why code is doing something, not what it does.
Would definitely have to be comments that stand in place of error handling.
if(some_condition){
do_stuff();
}
else{
//An error occurred!
}
I just found this one, written on the line before a commented-out line of code:
//This causes a crash for some reason. I know the real reason but it doesn't fit on this line.
100k LOC application that was ported from vb6 to vb.net. It looks as though a previous developer had put a comment header on one method and then copied and pasted the exact comment onto every method he wrote from then on. Hundreds of methods and each one incorrectly commented...
When i first saw it i laughed... 6 months later the joke is wearing thin.
This is an absolutely real example from a database trigger:
/******************************************************************************
NAME: (repeat the trigger name)
PURPOSE: To perform work as each row is inserted or updated.
REVISIONS:
Ver Date Author Description
--------- ---------- --------------- ------------------------------------
1.0 27.6.2000 1. Created this trigger.
PARAMETERS:
INPUT:
OUTPUT:
RETURNED VALUE:
CALLED BY:
CALLS:
EXAMPLE USE:
ASSUMPTIONS:
LIMITATIONS:
ALGORITHM:
NOTES:
******************************************************************************/
/** function header comments required to pass checkstyle */
The two most unhelpful comments I've ever seen...
try
{
...
}
catch
{
// TODO: something catchy
}
I posted this one at the Daily WTF also, so I'll trim it to just the comment...
// TODO: The following if block should be reduced to one return statememt:
// return Regex.IsMatch(strTest, NAME_CHARS);
if (!Regex.IsMatch(strTest, NAME_CHARS))
return false;
else
return true;
One I've never found very helpful:
<!--- Lasciate ogne speranza, voi ch'intrate --->

Resources