Coverity Prevent: how to handle "checked return" warning when I deliberately don't check the return? - coverity-prevent

As the title suggest, for example, in 85% of the situation, I'd like to check the return code of foo(), but sometimes I really don't care about it, but this will raise Coverity warning.
What's the best way to deal with this problem?
Changing Coverity settings doesn't count. :)

The correct way to suppress CHECKED_RETURN defect is to cast the return value you don't care about to a void. This has the additional advantage of making it clear to anyone reading the code that you don't care about return value, rather than that you forgot to check it.

Related

Suppress warning:deleting 'void*' is undefined

I know what is this warning and need to suppress this warning. Is there any way using pragma or compiler options are available to suppress this warning?
Better to change the code to avoid this warning rather than suppressing it!
If not handled correctly, it may cause runtime surprises which will be much harder to find.
[Note: To answer your question, which should be taken with a grain of salt, you may use free() instead of delete, as it converts any pointer to void* before deallocating it. Make sure that the destructors are called correctly before it.]
Just cast it before the delete.
delete[] (char*)item_to_del;

Can I have VS 2013 ignore certain syntax errors until I build?

For example, I could pretty much always do without the "not all code paths return a value" error squiggly. This generally means I'm in the process of writing the method. I don't need to be told it doesn't return a value. If I forget to add a return value, VS can tell me that when it builds. But I never want that while I'm working; it's annoying and usually tells me something I already know.
For another example, I could do without the errors that show up while I'm in the process of writing a switch statement, such as the one that tells me I don't have a break statement yet, as I'm still working on whatever case.
You can try to disable "Show live semantic errors",
http://www.devcurry.com/2011/01/disable-squiggly-or-wavy-lines-in.html

Is it acceptable to have useless code?

I see that some programmers add code that, after all, does not do anything useful. For instance (C#):
[Serializable]
class Foo {
// ...
string SerializeMe() {
return new XmlSerializer(typeof(this)).Serialize(this).ToString(); // serialize to xml (syntax wrong, not important here)
}
}
The class is marked as Serializable, but the only way it is serialized is by means of XmlSerialization, which does not require that class attribute at all.
I personally hate this kind of useless code, but I see it quite often and I'm curious as to what others think about it. Is this not so serious a flaw after all? Is it common practice in the industry? Or is this just plain bad and should be removed no matter what?
Good Source Control means that useless code or code that is no longer required should be removed. It can always be retrieved from the source control at a later date.
My rule of thumb,
If its not used get rid of it.
All surplus comments, attrributes are just noise and help your code to become unreadable. If left there they encourage more surplus code in your code base. So remove it.
I try to follow the YAGNI principle, so this bothers me as well.
Does it take even a minimal effort to read that additional (useless, as you added) code?
If yes (and I think it is so) then it should not be in the code. Code like this is polluted with extra snippets that are not useful, they are there "just in case".
The "later on refactoring" of these things can be painful, after 6 o 12 months, who is going to remember if that was really used?
Really don't like it.
Because I then spend valuable time trying to figure out why it's there. Assuming that if it's there, it's there for a reason, and if I don't see the reason, then there's a chance I'm missing something important that I should understand before I start messing with the code. It irritates me when I realize that I've just wasted an hour trying to understand why, or what, some snippet of code is doing, that was just left there by some developer too lazy to go back and remove it.
Useless one-liner code can and should be removed.
Useless code that took time to write can and should be removed...but people in charge tend to get queasy about this. Perhaps the best solution is to have a ProbablyUselessButWhoKnows project where everyone can check in pointless code that might be used again in two or three years. If nothing else, this way people don't have to feel nervous about deleting it.
(Yes, in theory you can get it out of source control, but old deleted code in source control is not exactly highly discoverable.)
In a commercial project - I'd say no, especially if someone can de-assemble it for reading and then has a WTF moment.
In a home-project - sure why not, I often keep some snippets for later use.
Well I can't comment this particular piece of code without knowing your background but I personally follow strictly a rule not to have anything in code unless I really need it. Or at least know that it may be useful some day for something I have in mind already now.
This is bad code.
Bad code is common practice.
That being said sometimes it is not worth the effort in changing stuff that isn't "broken".
It would seem that perfection is attained not when no more can be added, but when no more can be removed. — Antoine de Saint-Exupéry
Is think the meaning of useless is that it cannot and will not be used. I also think that an open door is very open.
If there is an active plan to use this additional feature, then keep it in.
If you know it will never be used, or if that plan stopped being relevant 6 months ago, then pull it out. I'd comment it out first, then remove it fully later.
I'm in the midst of rescoping a lot of variables that were public but really only need to be protected or private, simply because they don't make sense from an API perspective to be exposed--that and nothing uses them.

What types of coding anti-patterns do you always refactor when you cross them?

I just refactored some code that was in a different section of the class I was working on because it was a series of nested conditional operators (?:) that was made a ton clearer by a fairly simple switch statement (C#).
When will you touch code that isn't directly what you are working on to make it more clear?
I once was refactoring and came across something like this code:
string strMyString;
try
{
strMyString = Session["MySessionVar"].ToString();
}
catch
{
strMyString = "";
}
Resharper pointed out that the .ToString() was redundant, so I took it out. Unfortunately, that ended up breaking the code. Whenever MySessionVar was null, it wasn't causing the NullReferenceException that the code relied on to bump it down to the catch block. I know, this was some sad code. But I did learn a good lesson from it. Don't rapidly go through old code relying on a tool to help you do the refactoring - think it through yourself.
I did end up refactoring it as follows:
string strMyString = Session["MySessionVar"] ?? "";
Update: Since this post is being upvoted and technically doesn't contain an answer to the question, I figured I should actually answer the question. (Ok, it was bothering me to the point that I was actually dreaming about it.)
Personally I ask myself a few questions before refactoring.
1) Is the system under source control? If so, go ahead and refactor because you can always roll back if something breaks.
2) Do unit tests exist for the functionality I am altering? If so, great! Refactor. The danger here is that the existence of unit tests don't indicate the accuracy and scope of said unit tests. Good unit tests should pick up any breaking changes.
3) Do I thoroughly understand the code I am refactoring? If there's no source control and no tests and I don't really understand the code I am changing, that's a red flag. I'd need to get more comfortable with the code before refactoring.
In case #3 I would probably spend the time to actually track all of the code that is currently using the method I am refactoring. Depending on the scope of the code this could be easy or impossible (ie. if it's a public API). If it comes down to being a public API then you really need to understand the original intent of the code from a business perspective.
I only refactor it if tests are already in place. If not, it's usually not worth my time to write tests for and refactor presumably working code.
This is a small, minor antipattern but it so irritates me that whenever I find it, I expunge it immediately. In C (or C++ or Java)
if (p)
return true;
else
return false;
becomes
return p;
In Scheme,
(if p #t #f)
becomes
p
and in ML
if p then true else false
becomes
p
I see this antipattern almost exclusively in code written by undergraduate students. I am definitely not making this up!!
Whenever I come across it and I don't think changing it will cause problems (e.g. I can understand it enough that I know what it does. e.g. the level of voodoo is low).
I only bother to change it if there is some other reason I'm modifying the code.
How far I'm willing to take it depends on how confident I am that I won't break anything and how extensive my own changes to the code are going to be.
This is a great situation to show off the benefits of unit tests.
If unit tests are in place, developers can bravely and aggressively refactor oddly written code they might come across. If it passes the unit tests and you've increased readability, then you've done your good deed for the day and can move on.
Without unit tests, simplifying complex code that's filled with voodoo presents a great risk of breaking the code and not even knowing you've introduced a new bug! So most developers will take the cautious route and move on.
For simple refactoring I try to clean up deeply nested control structures and really long functions (more than one screen worth of text). However its not a great idea to refactor code without a good reason (especially in a big team of developers). In general, unless the refactoring will make a big improvement in the code or fix an egregious sin I try to leave well enough alone.
Not refactoring per-say but just as a matter of general housekeeping I generally do this stuff when I start work on a module:
Remove stupid comments
Comments that say nothing more than the function signature already says
Comments that are pure idiocy like "just what it looks like"
Changelogs at the top of the file (we have version control for a reason)
Any API docs that are clearly out-of-sync with the code
Remove commented-out chunks of code
Add version control tags like $Id$ if they are missing
Fix whitespace issues (this can be annoying to others though because your name shows up for a lot of lines in a diff even if all you did was change whitespace)
Remove whitespace at the end of the lines
Change tabs->spaces (for that is our convention where I work)
If the refactor makes the code much easier to read, the most common for me would be duplicate code, e.g. an if/else that only differs by the first/last commands.
if($something) {
load_data($something);
} else {
load_data($something);
echo "Loaded";
do_something_else();
}
More than (arguably) three or four lines of duplicate code always makes me think about refactoring. Also, I tend to move code around a lot, extracting the code I predict to be used more frequently into a separate place - a class with its own well-defined purpose and responsibilites, or a static method of a static class (usually placed in my Utils.* namespace).
But, to answer your question, yes, there are lot of cases when making the code shorter does not necessarily mean making it well structued and readable. Using the ?? operator in C# is another example. What you also have to think about are the new features in your language of choice - e.g. LINQ can be used to do some stuff in a very elegant manner but also can make a very simple thing very unreadable and overly complex. You need to weigh these two thing very carefully, in the end it all boils down to your personal taste and, mostly, experience.
Well, this is another "it depends" answer, but I am afraid it has to be.
I almost always break >2 similar conditionals into a switch... most often with regards to enums. I will short a return instead of a long statement.
ex:
if (condition) {
//lots of code
//returns value
} else {
return null;
}
becomes:
if (!condition)
return null;
//lots of code..
//return value
breaking out early reduces extra indents, and reduces long bits of code... also as a general rule I don't like methods with more than 10-15 lines of code. I like methods to have a singular purpose, even if creating more private methods internally.
Usually I don't refactor the code if I'm just browsing it, not actively working on it.
But sometimes ReSharper points out some stuff I just can't resist to Alt+Enter. :)
I tend to refactor very long functions and methods if I understand the set of inputs and outputs to a block.
This helps readability no end.
I would only refactor the code that I come across and am not actively working on after going through the following steps:
Speak with the author of the code (not always possible) to figure out what that piece of code does. Even if it is obvious to me as to what the piece of code is doing, it always helps to understand the rationale behind why the author may have decided to do something in a certain way. Spending a couple of minutes talking about it would not only help the original author understand your point of view, it also builds trust within the team.
Know or find out what that piece of code is doing in order to test it after re-factoring (A build process with unit tests is very helpful here. It makes the whole thing quick and easy). Run the unit tests before and after the change and ensure nothing is breaking due to your changes.
Send out a heads up to the team (if working with others) and let them know of the upcoming change so nobody is surprised when the change actually occurs
Refactoring for the sake of it is one of the roots of all evil. Please don't ever do it. (Unit tests do somewhat mitigate this).
Is vast swaths of commented out code an antipattern? While not code specifically, (it's comments) I see a lot of this kind of behaviour with people who don't understand how to use source control, and who want to keep the old code around for later so they can more easily go back if a bug was introduced. Whenever I see vast swaths of code that are commented out, I almost always remove them in their entirety.
I try to refactor based on following factors:
Do I understand enough to know whats happening?
Can I easily revert back if this change breaks the code.
Will I have enough time to revert the change back if it breaks the build.
And sometimes, if I have enough time, I refactor to learn. As in, I know my change may break the code, but I dont know where and how. So I change it anyways to find out where its breaking and why. That way I learn more about the code.
My domain has been mobile software (cell phones) where most of the code resides on my PC and wont impact others. Since I also maintain the CI build system for my company I can run a complete product build (for all phones) on the refactored code to ensure it doesnt break anything else. But thats my personal luxury which you may not have.
I tend to refactor global constants and enumerations quite a bit if they can be deemed a low refactor risk. Maybe it's just be, but something like a ClientAccountStatus enum should be in or close to the ClientAccount class rather than being in a GlobalConstAndEnum class.
Deletion/updating of comments which are clearly wrong or clearly pointless.
Removing them is:
safe
version control means you can find them again
improves the quality of the code to others and yourself
It is about the only 100% risk free refactoring I know.
Note that doing this in structured comments like javadoc comments is a different matter. Changing these is not risk free, as such they are very likely to be fixed/removed but not dead certain guaranteed fixes as standard incorrect code comments would be.

Commenting code that is removed [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 5 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.
Is it a good practice to comment code that is removed? For example:
// Code to do {task} was removed by Ajahn on 10/10/08 because {reason}.
Someone in my developer group during a peer review made a note that we should comment the lines of code to be removed. I thought this was a terrible suggestion, since it clutters the code with useless comments. Which one of us is right?
Generally, code that is removed should not be commented, precisely because it clutters the codebase (and, why would one comment on something that doesn't exist?).
Your defect tracking system or source control management tools are where such comments belong.
There are some (rare) situations when commenting code out (instead of deleting) is a good idea. Here's one.
I had a line of code that seemed good and necessary. Later I realized that it is unnecessary and harmful. Instead of deleting the line, I commented it out, adding another comment: "The line below is wrong for such and such reason". Why?
Because I am sure next reader of the code will first think that not having this line is an error and will try to add it back. (Even if the reader is me two years from now.) I don't expect him to consult source control first. I need to add comment to warn him of this tricky situation; and having wrong line and the reason why it is wrong happened to be the best way to do so.
I agree that it is not a good idea to leave code removed in comments.
Code history should be viewed through a version control system, which is where old code can be found, as well as the reason it was removed.
You should delete the code always.
As for being able to see old/removed code, that's what revision control is.
Depends on the reason for removal.
I think of comments as hints for people maintaining the code in the future, if the information that the code was there but was removed can be helpful to someone maintaining the code (maybe as a "don't do that" sign) then it should be there.
Otherwise adding detailed comments with names and dates on every code change just make the whole thing unreadable.
I think it's pretty useless and make the code less readable. Just think what it will be like after some monthes....
// removed because of this and that
/*
removed this stuff because my left leg...
*/
doSomething();
// this piece of has been removed, we don't need it...
You'll spend half an hour to find out what's going on
The question is, why do you remove code?
Is it useless? Was it a mistake to put it there in the first place?
No comments needed from my point of view.
It's useful when debugging, but there's no reason to check in code that way. The whole point of source control is being able to recover old versions without cluttering up the code with commented-out code.
I would suggest that, yes it's good practice to comment on code that has been removed but not in the code itself.
To further clarify this position, you should be using a source code control system (SCCS) that allows some form of check-in comment. That is where you should place the comments about why code was removed. The SCCS will provide the full contextual history of what has happened to the code, including what has been removed. By adding check-in comments you further clarify that history.
Adding comments in the code directly simply leads to clutter.
The recent consensus (from other discussions on here) is that the code should just be removed.
I personally will comment out code and tag it with a date or a reason. If it's old/stale and I'm passing through the file, then I strip it out. Version control makes going back easy, but not as easy as uncommenting...
It sounds like you are trying to get around versioning your code. In theory, it sounds like a great idea, but in practice it can get very confusing very quickly.
I highly recommend commenting code out for debugging or running other tests, but after the final decision has been made remove it from the file completely!
Get a good versioning system in place and I think you'll find that the practice of commenting out changes is messy.
Nobody here has written much about why you shouldn't leave commented-out code, other than that it looks messy. I think the biggest reason is that the code is likely to stop working. Nobody's compiling it. Nobody's running it through unit tests. When people refactor the rest of the code, they're not refactoring it. So pretty soon, it's going to become useless. Or worse than useless -- someone might uncomment it, blindly trusting that it works.
There are times when I'll comment out code, if we're still doing heavy design/development on a project. At this stage, I'm usually trying out several different designs, looking for the right approach. And sometimes the right approach is one I had already attempted earlier. So it's nice if that code isn't lost in the depths of source control. But once the design has been settled, I'll get rid of the old code.
In general I tend to comment very sparsely. I believe good code should be easy to read without much commenting.
I also version my code. I suppose I could do diffs over the last twenty checkins to see if a particular line has changed for a particular reason. But that would be a huge waste of my time for most changes.
So I try comment my code smartly. If some code is being deleted for a fairly obvious reason, I won't bother to comment the deletion. But if a piece of code is being deleted for a subtle reason (for example it performed a function that is now being handled by a different thread) I will comment-out or delete the code and add a banner comment why:
// this is now handled by the heartbeat thread
// m_data.resort(m_ascending);
Or:
// don't re-sort here, as it is now handled by the heartbeat thread
Just last month, I encountered a piece of code that I had changed a year ago to fix a particular issue, but didn't add a comment explaining why. Here is the original code:
cutoff = m_previous_cutofftime;
And here is the code as it was initially fixed to use a correct cutoff time when resuming an interrupted state:
cutoff = (!ok_during) ? m_previous_cutofftime : 0;
Of course another unrelated issue came up, which happened to touch the same line of code, in this case reverting it back to its original state. So the new issue was now fixed, but the old issue suddenly became rebroken. D'oh!
So now the checked-in code looks like this:
// this works for overlong events but not resuming
// cutoff = m_previous_cutofftime;
// this works for resuming but not overlong events
// cutoff = (!ok_during) ? m_previous_cutofftime : 0;
// this works for both
cutoff = (!resuming || !ok_during) ? m_previous_cutofftime : 0;
Of course, YMMV.
As the lone dissenting voice, I will say that there is a place for commenting out code in special circumstances. Sometimes, you'll have data that continues to exist that was run through that old code and the clearest thing to do is to leave that old code in with source. In such a case I'd probably leave little note indicating why the old code was simply commented out. Any programmers coming along after would be able to understand the still extant data, without having to psychically detect the need to check old versions.
Usually though, I find commented out code completely odious and I often delete it when I come across it.
If you are removing code. You should not comment it that you removed it. This is the entire purpose of source control (You are using source control? Right?), and as you state the comment just clutters up the code.
I agree that it's a terrible suggestion. That's why you have Source Control that has revisions. If you need to go back and see what was changed between two revisions, diff the two revisions.
I hate seeing code that's cluttered with commented out code. Delete the code and write a commit message that says why it was removed. You do use source control, don't you?
Don't litter active code with dead code.
I'll add my voice to the consensus: put the comments on why code was deleted in the source control repository, not in the code.
This is one of those "broken" windows thinkgs like compiler hints/warnings left unaddressed. it will hurt you one day and it promotes sloppiness in the team.
The check in comment in version control can track what/why this code was removed - if the developer didnt leave a note, track them down and throttle them.
A little anecdote, for fun: I was in a company, some years ago, knowing nothing of source code version control (they got such tool later...).
So they had a rule, in our C sources: "when you make a change, disable the old code with preprocessor macros":
#ifdef OLD /* PL - 11/10/1989 */
void Buggy()
{
// ...
}
#else
void Good()
{
// ...
}
#end
No need to say, our sources quickly became unreadable! It was a nightmare to maintain...
That's why I added to SciTE the capacity to jump between nested #ifdef / #else / #end and such... It can be still useful in more regular cases.
Later, I wrote a Visual Studio macro to happily get rid of old code, once we got our VCS!
Now, like buti-oxa, sometime I felt the need to indicate why I removed some code. For the same reason, or because I remove old code which I feel is no longer needed, but I am not too sure (legacy, legacy...). Obviously not in all cases!
I don't leave such comment, actually, but I can understand the need.
At worse, I would comment out in one version, and remove everything in the next version...
At my current work, for important local changes, we leave the old code but can reactivate it by properties, in case of emergency. After testing it some time in production, we eventually remove the old code.
Of course, VCS comments are the best option, but when the change is a few lines in a big file with other changes, referencing the little removal can be hard...
If you are in the middle of major changes, and need to make a fix to existing functionality, commenting out the future code is a reasonable thing to do, provided you remark that this is future functionality, at least until we have futures friendly source control systems.
I comment unnused code because you never know when will you have to fallback on the ancient code, and maybe the old code will help other people to understand it, if it was simpler back then.
I agree with you Andrew; IMO this is why you use version control. With good checkin/commit comments and a diff tool you can always find out why lines were removed.
If you are using any form of Source Control then this approach is somewhat redundant (as long as descriptive log messages are used)
I also think it's a terrible suggestion :)
You should use source control and if you remove some code you can add a comment when you commit. So you still have the code history if you want...
There's a general "clean code" practice that says that one should never keep removed code around as commented out since it clutters and since your CVS/SVN would archive it anyway.
While I do agree with the principle I do not think that it is an acceptable approach for all development situations. In my experience very few people keep track of all the changes in the code and every check-in. as a result, if there is no commented out code, they may never be aware that it has ever existed.
Commenting code out like that could be a way of offering a general warning that it is about to be removed, but of course, there are no guarantees that interested parties would ever see that warning (though if they frequently work with that file, they will see it).
I personally believe that the correct approach is to factor that code out to another private method, and then contact relevant stakeholders and notify them of the pending removal before actually getting rid of the function.
Where I am at we comment out old code for one release cycle and then remove the comments after that. (It gives us quick fix ability if some of the new code is problematic and needs to be replaced with the old code.)
In almost all cases old code should of course be removed and tracked in your RCS.
Like all things though, I think that making the statement 'All deleted code will ALWAYS be removed' is an incorrect approach.
The old code might want to be left in for a miriad of reasons. The prime reason to leave the code in is when you want any developer who is working in that section of code in the future to see the old code.
Relying on source tracking obviously does not give this.
So, I believe the correct answer is:
-Delete old code unless leaving it in provides crucial information that the next developer in the code would require. Ie, remove it 99% of the time but don't make a draconian rule that would remove your ability to provide much needed documentation to the next developer when circumstances warrant it.

Resources