Can Checkstyle return lines of code for a project - metrics

I am about to employ Checkstyle on a project to improve coding standards and discovered in my research that I can also setup Checkstyle to return some coding metrics as well as some other useful checks. However there seems to be a glaring omission, which is Lines of Code. I know its a horrible metric but I've been asked to produce it! Does anyone know if Checkstyle can return lines of code on the project and if so how?
Cheers

Checkstyle calculates mutiple LOC-like metrics:
FileLength (com.puppycrawl.tools.checkstyle.checks.sizes) The default maximum is 2000.
ExecutableStatementCount and JavaNCSS, i.e., Non Commenting Source Statements. In a way, it is close to SLOC (source lines of code) or even better LLOC (logical lines of code). LLOC, ExecutableStatementCount and JavaNCSS are aware of the fact that one statement can be spread over multiple physical lines of code and that one physical line of code can contain multiple statements. JavaNCSS adheres to the specification for the JavaNCSS-Tool written by Chr. Clemens Lee. The specification can be found on http://www.kclee.de/clemens/java/javancss/#specification

The HONEST answer is that Checkstyle simply doesn't offer LOC or LLOC.
In fact, as far as I can see, no Eclipse Juno Plugin for Java offers this eminently useful feature.
I wonder why so is that now . . .
Even very crude IDEs like GPS gives a full catalogue of all the usual metrics.
It seems to say something about the people at IBM and Oracle.

Related

Measure the percentage of usage of a code formatter

When we are coding it is really important to maintain our code base while preserving coding standards. There are plenty of code formatting tools which are matched with the respective IDE. By using them we can format our code while preserving line indentation. So is there any tool to measure that usage of a code formatting in our code base. I already heard there are some tools to measure the test coverage. There that tool gives a percentage of test cases for actual methods in the code. By using that tool we can find the places where we do not implement test cases. Like that I want to catch the places where I do not use the code formatting. When code base has so many source files and number of lines, it's a tedious task to test if we were forgotten to run the code formatting tool. As I know there's no way to run the tool in all the files at once. So guys, if you know a solution to my problem please let me know.

Handling comments in code when doing i18n

I'm in the process of translating a Open Source project from Chinese to English, and I've used i18n (in this case babel) to separate the code from both English and Chinese translations.
Everything's done, except for a rather large number of inline comments in the code.
Obviously, babel can't translate comments inline (and it would be rather obnoxious if it did, anyway. Since code would not be unique across languages and therefore less easily verifiable.)
The way I see it, there are a number of options:
Leave comments in -
Pro: Helps original author, etc.
Con: Makes it distracting for ongoing translation and anyone who doesn't speak the language
Strip out all the comments -
Pro: Code is native-language-agnostic, so it makes sense. Who needs comments anyway? Use the source, Luke!
Con: Goes against SE principles. Could lose something important in understanding how the code works - maybe something's been done to avoid a security risk, etc.
Place English comments near Chinese comments
(Possibly moved to lines above and prefixed with "EN" and "ZH", for example).
Pro: Best of both worlds, comments kept close to code
Con: Not conducive to dictionary-style translation. Can get bulky with more languages.
Create a comment dictionary / notes
Pro: Keeps the comments in a separate file for easy translation.
Con: Difficult to keep synced with code. Not intuitive to remember to update comments related to code when changing coe.
Use a different preprocessor for i18n before/after each development cycle.
Pro: Comments et al would be in your language. Could link this to git pull/push so you only ever see the code in your language.
Con: Bulky, non-obvious process. Could result in code-verification or even compilation errors.
None of these seem like really great solutions.
If you do alot of this, and the code is shared publicly between developers who don't share a native tongue, is there a recommended way to handle translating (or not) comments in the code itself?
I am not sure I understand... You say you separated the code from the languages part. So now you should have code (with comments) + English resources + Chinese resources (i used resources for whatever your programming language use to store localizable content)
Translators only see the resources, not the code, nor the comments. The comments stay untranslated, for the developers.
Short Answer
It seems to be a mixture of:
Strip out all the comments, and
Place English comments near Chinese comments.
Inline comments are almost always trivial - Strip them
Functional comments are not as intrusive - Translate them (possibly with a i18n prefix e.g. "[cn]:" or "[en]:").
Explanation
My meagre amount of research tends to suggest that larger projects make strong attempts to reduce comments and let the code explain itself, instead focusing on code quality which reduces the need for comments.
e.g. From the Linux Kernel Coding guidelines:
NEVER try to explain HOW your code works in a comment: it's much
better to write the code so that the working is obvious, and it's
a waste of time to explain badly written code.
...and from the MySQL coding standards:
Comment your code when you do something that someone else may think is
not trivial.
Both of these standards (and others) recommend minimal function descriptions also, so that's not as obtrusive to understanding the code, and, since function descriptions are generally multi-lined and above the code itself, multiple languages can be included as necessary.
Maybe someone, somewhere has built an interface that can isolate comments into the readers language, but I couldn't (yet) find any that do so.
I always think that API comments exported in the project and private comments in open source projects should be internationalized, which is very convenient for developers in other countries.
On Github, there are actually many developers who use their own national language to comment on some well-known open source projects and some of their own annotations. Most of the reason is that if they do not translate, the efficiency of developers reading comments very low.
Similar to .d.ts in TypeScript, I think function annotation translation can also take a similar form, which is more convenient for the community to feedback translation content, because in fact many developers are willing to do so.

Configuration Management - History in Code Comments

Let me pose a bit of background information before asking my question:
I recently joined a new software development group that uses Rational tools for configuration management, including a source control and change management system.
In addition to these tools, the team has a standard practice of noting any code changes as a comment in the code, such as:
///<history>
[mt] 3/15/2009 Made abc changes to fix xyz
///</history>
Their official purpose for the commenting standard is that "the comments provide traceability from requirement to code modification".
I am preparing to pose an argument that this practice is unnecessary and redundant; that the team should get rid of this standard immediately.
To wit - the change management system is the place to build traceability from requirement to code modification, and source control can provide detailed history of changes by performing a Diff between versions. When source code is checked in, the corresponding change management ticket is noted. When a CM ticket is resolved, we note which source code files were modified. I believe this provides a sufficient cross-reference for the desired traceability.
I would like to know if anyone disagrees with my argument. Am I missing some benefit of commented source code history that change management and source control systems cannot provide?
For myself, I have always found such comments to be more trouble than they're worth: they can cause merge conflicts, can appear as 'false positives' when you're trying to isolate the diffs between two versions, and may reference code changes that have since been obsoleted by later changes.
It's often (not always, but often) possible to change version-control systems without losing metadata. If you were to move your code to a system that doesn't support this, it would not be hard to write a script to convert the change history into comments before the cutover.
A comment allows you to find all the changes and their reasons in the code right where they are relevant without having to dig into diffs and version control system intricacies. Furthermore, should you decide to change of version control system, the comments will stay.
I worked on a large project with similar practice that had changed of source control system twice. There wasn't a day when I wasn't glad to have these comments.
Is it redundant? Yes.
Is it unnecessary? No.
I've always thought that code should be, of course, under version control, and that the current source code (the one that you can open and read today) should be valid only in present tense.
It doesn't matter if a report could have up to 3 axis in the past and last month you updated it to support up to 6 axis. It doesn't matter if you expanded some function or fixed some bug, as long as the current version can be easily understood. When you fix a bug, just leave the fixed code.
There's an exception, though. If (and only if) the fixed code looks less intuitive to you than the previous, incorrect one; if you feel that someone might come tomorrow and, just by reading the code, be tempted to change it back to what "seems more correct", then it's good to add a comment: "This is done this way to avoid... blah blah blah." Also, if the problem behind is an infamous war story inside the team's culture, or if for some reason the bug report database contains very interesting information about this part of the code, I wouldn't find it incorrect to add "(see Bug Id 10005)" to the explaining comment.
The one that jumps to mind to me is vendor lockin. If you ever moved away from Rational, you'd need to make sure that the full change history was maintained during the migration - not just the version of the artifacts.
When you're in the code you need to know why it's structured like that, hence in code commenting. Tools that sit outside the code, good though they may be, require far too much of a context shift in your brain to be useful. As well as that, trying to reverse engineer the code intent from documentation and a diff is pretty damn hard, I'd much rather read a line of comment any day.
There was a phase in the code I work on, back in the 1994-96 time frame, where there was a tendency to insert change history comments at the top of the file. Those comments are now meaningless and useless, and one of the many standard cleanups I perform when editing files containing such comments is to remove them.
In contrast, there are also some comments with a bug number at the location where the change is made, typically explaining why the ridiculous code is as it is. These can be very helpful. The bug number gives you somewhere else to look for information, and fingers the culprit (or victim - it varies).
On the other hand, items like this one - genuine; cleaned up last week - make me grit my teeth.
if (ctab->tarray && ctab->tarray[i])
#ifndef NT
prt_theargs(*(ctab->tarray[i]));
#else
/* Correct the parameter type mismatch in the line above */
prt_theargs(ctab->tarray[i]);
#endif /* NT */
The NT team got the call correct; why they thought it was a platform-specific fix is beyond me. Of course, if the code had used prototypes instead of just parameterless declarations before now, then the Unix team would have had to fix the code too. The comment was a help - assuring me that the bug was genuine - but exasperating.

Do you have coding standards? If so, how are they enforced? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've worked on a couple of projects where we spent a great deal of time discussing and writing elaborate coding standards covering everything from syntax layout to actual best practices. However, I have also found that these are rarely followed to the full extent. Many developers seem to hesitate to reject a code review based on coding standard violations alone. I.e. violations are committed to the repository on a regular basis.
My questions are: Do you have coding standards? What do they cover? Are they followed by everyone? And what do you do (if anything) to make sure everybody is following the standards?
I'm aware that there is a similar question here, but my concern is not so much how you could do it, but how you are actually going about it and what are the perceived benefits?
I've worked in places with barely-followed coding practices, and others where they're close to being enforced - or at least easily checked.
A few suggestions:
The most important thing is to get buy-in to the idea that consistency trumps your personal preferred style. There should be discussion of the coding standard both before and after it's instituted, but no-one should be allowed to just opt out of it.
Code reviews should be mandatory, with the checkin comment including the username of the reviewer. If you're using a suitably powerful SCM, consider not allowing checkins which don't have a valid reviewer name.
There should be a document which everyone knows about laying out the coding standards. With enough detail, you shouldn't get too much in the way of arguments.
Where possible, automate checking of the conventions (via Lint, CheckStyle, FXCop etc) so it's easy for both the committer and the reviewer to get a quick check of things like ordering import/using directives, whitespace etc.
The benefits are:
Primarily consistency - if you make it so that anyone can feel "at home" in any part of the codebase at any time, it gives you more flexibility.
Spreading best practice - if you ban public fields, mutable structs etc then no-one can accidentally plant a time bomb in your code. (At least, not a time bomb that's covered by the standard. There's no coding standard for perfect code, of course :)
EDIT: I should point out that coding standards are probably most important when working in large companies. I believe they help even in small companies, but there's probably less need of process around the standard at that point. It helps when all the developers know each other personally and are all co-located.
Do you have coding standards?
Yes, differs from project to project.
What does it cover?
Code(class, variable, method, constant), SQL naming and formatting convention
Is it being followed by everyone?
Yes, every new entrant in project could be asked to create a demo project following organization coding convention then it gets reviewed. This exercise makes developer feel at ease before starting real job.
And what do you do (if anything) to make sure everybody is following the standard?
Use StyleCop and FxCop to ensure they are religiously followed. It would show up as warning/error if code fails to comply with organization coding convention.
Visual Studio Team system has nice code anlysis and check-In policies which would prevent developers checking in code that does not comply
Hope, it helps
Thanks,
Maulik Modi
We take use of the Eclipse's save actions and formatters. We do have a suggested standard, but nobody is actually enforcing it, so there are some variations on what is actually formatted, and how.
This is something of a nuisance (for me), as various whitespace variations are committed as updates to the SVN repository...
StyleCop does a good job of enforcing coding layout practices and you can write custom rules for it if something isn't covered in the base rules that is important to you.
I think coding standards are very important. There is nothing more frustrating than trying to find the differences between two revisions of a file only to find that the whole file has been changed by someone who reformatted it all. And I know someone is going to say that that sort of practice should be stamped out, but most IDEs have a 'reformat file' feature (Ctrl-K Ctrl-D in Visual Studio, for example), which makes keeping your code layed out nicely much easier.
I've seen projects fail through lack of coding standards - the curly-brace wars at my last company were contributary to a breakdown in the team.
I've found the best coding standards are not the standards made up by someone in the team. I implemented the standards created by iDesign (click here) in our team, which gets you away from any kind of resentment you might get if you try to implement your own 'standard'.
A quick mention of Code Style Enforcer (click here) which is pretty good for highlighting non-compliance in Visual Studio.
I have a combination of personal and company coding standards that are still evolving to some extent. They cover code structure, testing, and various documents describing various bits of functionality.
As it evolves, it is being adopted and interpreted by the rest of my team. Part of what will happen ultimately is that if there is concensus on some parts then those will hold up while other parts may just remain code that isn't necessarily going to be up to snuff.
I think there may be some respect or professional admiration that act as a way of getting people to follow the coding standards where some parts of it become clear after it is applied, e.g. refactoring a function to be more readable or adding tests to some form, with various "light bulb moments" to borrow a phrase from Oprah.
Another part of the benefit is to see how well do others work, what kinds of tips and techniques do they have and how can one improve over time to be a better developer.
I think the best way to look at coding standards is in terms of what you hope to achieve by applying, and the damage that they can cause if mis-applied. For example, I see the following as quite good;
Document and provide unit tests that illustrate all typical scenarios for usage of a given interface to a given routine or module.
Where possible use the following container classes libraries, etc...
Use asserts to validate incoming parameters and results returned (C & C++)
Minimise scope of all variables
Access object members through methods
Use new and delete over malloc and free
Use the prescribed naming conventions
I don't think that enforcing style beyond this is a great idea, as different programmers are efficient using differing styles. Forcing programmers to change style can be counter productive and lead to lost time and reduced quality. Standards should be kept short and easy to understand.
Oh yes, I'm the coding standard police :) I just wrote a simple script to periodically check and fix the code (my coding standard is simple enough to implement that.) I hope people will get the message after seeing all these "coding convention cleanups" messages :)
We have a kind of 'loose' standard. Maybe because of our inability to have agreement upon some of those 'how many spaces to put there and there', 'where to put my open brace, after the statement or on the next line'.
However, as we have main developers for each of the dedicated modules or components, and some additional developers that may work in those modules, we have the following main rule:
"Uphold the style used by the main developer"
So if he wants to do 3 space-indentation, do it yourself also.
It's not ideal as it might require retune your editor settings, but it keeps the peace :-)
Do you have coding standards?
What does it cover?
Yes, it has naming conventions, mandatory braces after if, while ... , no warning allowed, recommendations for 32/64 bits alignment, no magic number, header guards, variables initialization and formatting rules that favor consistency for legacy code.
Is it being followed by everyone?
And what do you do (if anything) to make sure everybody is following the standard?
Mostly, getting the team agreement and a somewhat lightweight coding standard (less than 20 rules) helped us here.
How it is being enforced ?
Softly, we do not have coding standard cop.
Application of the standard is checked at review time
We have template files that provide the standard boilerplate
I have never seen a project fail because of lack of coding standards (or adherence to them), or even have any effect on productivity. If you are spending any time on enforcing them then you are wasting money. There are so many important things to worry about instead (like code quality).
Create a set of suggested standards for those who prefer to have something to follow, but leave it at that.
JTest by ParaSoft is decent for Java.
Our coding standards are listed in our Programmer's Manual so everyone can easily refer to them. They are effective simply because we have buy in from all team members, because people are not afraid to raise standards and style issues during code reviews, and because they allow a certain level of flexibility. If one programmer creates a new file, and she prefers to place the bracket on the same line as an if statement, that sets the standard for that file. Anyone modifying that file in the future must use the same style to keep things consistent.
I'll admit, when I first read the coding standards, I didn't agree with some of them. For instance, we use a certain style for function declarations that looks like this:
static // Scope
void // Type declaration
func(
char al, //IN: Description of al
intl6u hash_table_size, //IN/OUT: Description of hash_table_size
int8u s) //OUT: Description of s
{
<local declarations>
<statements>
}
I had never seen that before, so it seemed strange and foreign to me at first. My gut reaction was, "Well, that's dumb." Now that I've been here a while, I have adjusted to the style and appreciate how I can quickly comprehend the function declaration because everyone does it this way.

Standards Document

I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.
I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.
I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?
How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.
Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?
What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:
<com|org|...>.<company>.<app>.<layer>.<function>.ClassName
I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.
First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review.
If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.
In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having any standard is the key.
Coming from the automotive industry, here's a few style standards used for concrete reasons:
Always used braces in control structures, and place them on separate lines. This eliminates problems with people adding code and including it or not including it mistakenly inside a control structure.
if(...)
{
}
All switches/selects have a default case. The default case logs an error if it's not a valid path.
For the same reason as above, any if...elseif... control structures MUST end with a default else that also logs an error if it's not a valid path. A single if statement does not require this.
In the occasional case where a loop or control structure is intentionally empty, a semicolon is always placed within to indicate that this is intentional.
while(stillwaiting())
{
;
}
Naming standards have very different styles for typedefs, defined constants, module global variables, etc. Variable names include type. You can look at the name and have a good idea of what module it pertains to, its scope, and type. This makes it easy to detect errors related to types, etc.
There are others, but these are the top off my head.
-Adam
I'm going to second Jason's suggestion.
I just completed a standards document for a team of 10-12 that work mostly in perl. The document says to use "perltidy-like indentation for complex data structures." We also provided everyone with example perltidy settings that would clean up their code to meet this standard. It was very clear and very much industry-standard for the language so we had great buyoff on it by the team.
When setting out to write this document, I asked around for some examples of great code in our repository and googled a bit to find other standards documents that smarter architects than I to construct a template. It was tough being concise and pragmatic without crossing into micro-manager territory but very much worth it; having any standard is indeed key.
Hope it works out!
It obviously varies depending on languages and technologies. By the look of your example name space I am going to guess java, in which case http://java.sun.com/docs/codeconv/ is a really good place to start. You might also want to look at something like maven's standard directory structure which will make all your projects look similar.

Resources