How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries? - visual-studio-2010

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements.
ie. instead of this:
if (fileName == null)
throw new ArgumentNullException("fileName");
use this:
Contract.Requires(fileName != null);
The reason I'm asking is that I know that the static checker is not available to me, so I'm a bit nervous about some assumptions that I make, that the compiler cannot verify. This might lead to the class library not compiling for someone that downloads it, when they have the static checker. This, coupled with the fact that I cannot even reproduce the problem, would make it tiresome to fix, and I would gather that it doesn't speak volumes to the quality of my class library if it seemingly doesn't even compile out of the box.
So I have a few questions:
Is the static checker on by default if you have access to it? Or is there a setting I need to switch on in the class library (and since I don't have the static checker, I won't)
Are my fears unwarranted? Is the above scenario a real problem?
Any advice would be welcome.
Edit: Let me clarify what I mean.
Let's say I have the following method in a class:
public void LogToFile(string fileName, string message)
{
Contracts.Requires(fileName != null);
// log to the file here
}
and then I have this code:
public void Log(string message)
{
var targetProvider = IoC.Resolve<IFileLogTargetProvider>();
var fileName = targetProvider.GetTargetFileName();
LogToFile(fileName, message);
}
Now, here, IoC kicks in, resolves some "random" class, that provides me with a filename. Let's say that for this library, there is no possible way that I can get back a class that won't give me a non-null filename, however, due to the nature of the IoC call, the static analysis is unable to verify this, and thus might assume that a possible value could be null.
Hence, the static analysis might conclude that there is a risk of the LogToFile method being called with a null argument, and thus fail to build.
I understand that I can add assumptions to the code, saying that the compiler should take it as given that the fileName I get back from that method will never be null, but if I don't have the static analyzer (VS2010 Professional), the above code would compile for me, and thus I might leave this as a sleeping bug for someone with Ultimate to find. In other words, there would be no compile-time warning that there might be a problem here, so I might release the library as-is.
So is this a real scenario and problem?

When both your LogToFile and Log methods are part of your library, it is possible that your Log method will not compile, once you turn on the static checker. This of course will also happen when you supply code to others that compile your code using the static checker. However, as far as I know, your client's static checker will not validate the internals of the assembly you ship. It will statically check their own code against the public API of your assembly. So as long as you just ship the DLL, you'd be okay.
Of course there is a change of shipping a library that has a very annoying API for users that actually have the static checker enabled, so I think it is advisable to only ship your library with the contract definitions, if you tested the usability of the API both with and without the static checker.
Please be warned about changing the existing if (cond) throw ex calls to Contracts.Requires(cond) calls for public API calls that you have already shipped in a previous release. Note that the Requires method throws a different exception (a RequiresViolationException if I recall correctly) than what you'd normally throw (a ArgumentException). In that situation, use the Contract.Requires overload. This way your API interface stays unchanged.

First, the static checker is really (as I understand it) only available in the ultimate/academic editions - so unless everyone in your organization uses it they may not be warned if they are potentially violating an invariant.
Second, while the static analysis is impressive it cannot always find all paths that may lead to violation of the invariant. However, the good news here is that the Requires contract is retained at runtime - it is processed in an IL-transformation step - so the check exists at both compile time and runtime. In this way it is equivalent (but superior) to a regular if() check.
You can read more about the runtime rewriting that code contract compilation performs here, you can also read the detailed manual here.
EDIT: Based on what I can glean from the manual, I suspect the situation you describe is indeed possible. However, I thought that these would be warninings rather than compilation errors - and you can suppress them using System.Diagnostics.CodeAnalysis.SuppressMessage(). Consumers of your code who have the static verifier can also mark specific cases to be ignored - but that could certainly be inconvenient if there are a lot of them. I will try to find some time later today to put together a definitive test of your scenario (I don't have access to the static verifier at the moment).
There's an excellent blog here that is almost exclusively dedicated to code contracts which (if you haven't yet seen) may have some content that interests you.

No; the static analyzer will never prevent compilation from succeeding (unless it crashes!).
The static analyzer will warn you about unproven pre-/post-conditions, but doesn't stop compilation.

Related

D / DLang : Inhibiting code generation of module-private inlined functions

I have a D module which I hope contains public and private parts. I have tried using the keywords private and static before function definitions. I have a function that I wish to make externally-callable / public and ideally I would like it to be inlined at the call-site. This function calls other module-internal functions that are intended to be private, i.e. not externally callable. Calls to these are successfully inlined within the module and a lot of the cruft is disposed of by CTFE plus known-constant propagation. However the GDC compiler also generates copies of these internal routines, even though they have been inlined where needed and they are not supposed to be externally callable. I'm compiling with -O3 -frelease. What should I be doing - should I expect this even if I use static and/or private?
I have also taken a brief look at this thread concerning GCC hoping for insight.
As I mentioned earlier, I've tried both using private and static on these internal functions, but I can't seem to suppress the code generation. I could understand this if a debugger needed to have copies of these routines to set breakpoints in. I need to stress that this could perhaps be sorted out somehow at link-time, for all I know. I haven't tried linking the program, I'm just looking at the generated code in the Matt Godbolt D Compiler Explorer using GDC. Everything can be made into templates with a zero-length list of template parameters (e.g. auto my_fn()( in arg_t x ) ), tried that, it doesn't help but does no harm.
A couple of other things to try: I could try and make a static class with private parts, as a way of implementing a package, Ada-style. (Needs to be single-instance strictly.) I've never done any C++, only massive amounts of asm and C professionally. So that would be a learning curve.
The only other thing I can think of is to use nested function definitions, Pascal/Ada-style, move the internal routines to be inside the body of their callers. But that has a whole lot of disadvantages.
Rough example
module junk;
auto my_public_fn() { return my_private_fn(); }
private
static // 'static' and/or 'private', tried both
auto my_private_fn() { xxx ; return whatever; }
I just had a short discussion with Iain about this and implementing this is not as simple as it seems.
First of all static has many meanings in D, but the C meaning of translation unit local function is not one of them ;-)
So marking these functions as private seems intuitive. After all, if you can't access a function from outside of the translation unit and you never leak an address to the function why not remove it? It could be either completely unused or inlined into all callers in this case.
Now here's the catch: We can't know for sure if a function is unused:
private void fooPrivate() {}
/*template*/ void fooPublic()()
{
fooPrivate();
}
When compiling the file GDC knows nothing about the fooPublic template (as templates can only be fully analyzed when instantiated), so fooPrivate appears to be unused. When later using fooPublic in a different file GDC will rely on fooPrivate being already emitted in the original source - after all it's not a template so it's not being emitted into the new module.
There might be workarounds but this whole problem seems nontrivial. We could also introduce a custom gcc.attribute attribute for this. It would cause the same problems with templates, but as it's a specific annotation for one usecase (unlike private) we could rely on the user to do the right thing.

How to give warning message in Visual Studio when passed an unappropriate parameter to a method?

I know that it is nonsense (or there is no chance) for variables that its value is unknowable until the runtime.
Let's assume that you have a method like this:
public void Foo (BarEnum barVal)
{
//...
if(barVal == BarEnum.UnappropriateForFooMethod)
throw new BlaBlaException("Invalid barVal for Foo method ->" + barVal);
//...
}
This method will already throw an exception for unappropriate parameter. But I intend to warn developer that before run code and get an exception. Main idea is that. It is not important that if she/he do not care about warnings or turned off the warning messages, her/him code will get an exception anyway.
I guess that it is possible with built-in attributes. Like Obsolete. But I could not find anything...
If there is no attribute for this purpose, I am open to suggestions for custom solutions.
From .NET Framework 4 and later there's something called Code Contracts (on GitHub). Never tried it, but looks like what you seek.
There's also Roslyn. Also haven't work with it, but probably does at least something that you want. Being a super-tool, it is probably a bit unwieldy and verbose for your needs.
One workaround to this problem, without using external tools, is to thoroughly review the code.

Is There Any Overhead Difference Between Protobuf Runtime and Static Tag Methods?

We are using Probuf on a .netcf target. Everything works well. I started out using the static [ProtoContract], [ProtoMember, 1].. etc. My colleage was concerned about adding potential overhead to the class object so I switched to a runtime model with .add(# , " ") which seemed more "disconnected" from the class in question. I actually prefer the static tags in the class since names are inherently updated if variable names are refactored later. Since I do not know how or what protobuf does under the hood, is there any advantage or disadvantage to using the static tags vs. the runtime model in terms of overhead, speed, etc.
Thanks!
I haven't profiled this aspect extensively - mainly because any overhead from reflection on the attributes is done once and once only. There might be a slight difference in cold-start performance, but: if the ultimate in startup performance is your aim you should ideally try to use the precompiler available in the google-code download. This only works with the attribute model but has the advantage that when using a precompiled model no reflection whatsoever occurs at runtime. It will also generate pure IL, where-as CF is usually very restricted so IIRC the runtime usage is forced to use some reflection even for things like member access. Finally, it means you can use the "CoreOnly" rather than "Full" build, which is smaller and less complex.
http://marcgravell.blogspot.co.uk/2012/07/introducing-protobuf-net-precompiler.html

Have Code Analysis ignore methods that throw a NotImplementedException

I know there are rules available that fire when a NotImplementedException is left in the code (which I can understand for a release build) (see this answer, or this question), but I would like to have the opposite: have Code Analysis ignore methods that throw a NotImplementedException, as they are known to be unfinished.
Background:
When I develop a block of code, I'd like to test what I have so far, before I'm completely done. I also want CA to be on, so I can correct errors early (like: didn't dispose of resources properly). But as I'm stil developing that code, there are still some stubs that I know will not be used by my test. The body of such a stub usually consists of no more than a throw new NotImplementedException();.
When I build the code, CA complains that the method could be 'static' and that parameters are unused. I know I can suppress the CA-errors, but that means I will have to remember to take those suppressions out when those methods are built and it's an extra build (one to get the messages so I can suppress them and one to really run the code).
My question:
Is there a way to have CA ignore methods that end in a NotImplementedException along (at least) one of the code paths? It would be extra nice if that could be set to only work in debug mode, so you can get warnings about that exception in a release build.
For the record, I'm using VS2010.
No. There is no such option in Code Analysis.
What you could do is write a custom rule which flags the throwing of a NotImplementedException and then process the Code Analysis outcome and remove any entry with the same target method as the NotImplemented custom rule. This rule should be pretty simple to implement. It would probably suffice to search for any Constructor call on the NotImplementedException class.
But this will only work if you run Code Analysis from the commandline and then post-process the xml file.
You could also mark the method using the GeneratedCodeAttribute, as these will be ignored by default.

Benefits of Assertive Programming

What is the point of putting asserts into our code ? What are the benefits of assertive programming ?
private void WriteMessage(string message)
{
Debug.Assert(message != null, "message is null");
File.WriteAllText(FILE_PATH, message);
}
For example we can check the message variable and throw an exception here. Why do I use assert here ? Or is this a wrong example to see benefits of asserts ?
They also support the philosophy of fail fast, explained in this article by Jim Shore.
Where some people would write:
/*
* This can never happen
*/
Its much more practical to write:
assert(i != -1);
I like using asserts because they are easily turned off with a simple compile time constant, or made to do something else like prepare an error report. I don't usually leave assertions turned on (at least, not in the usual way) when releasing something.
Using them has saved me from making very stupid mistakes on other people's computers .. those brave souls who enjoy testing my alpha code. Using them plus tools like valgrind helps to guarantee that I catch something awful before committing it.
An important distinction to consider is what sorts of errors you would like to catch with assertions. I often use assertions to catch programming errors (i.e., calling a method with a null parameter) and a different mechanism to handle validation errors (e.g., passing in a social security number of the wrong length). For the programming error caught with the assertion, I want to fail fast. For the validation error, I want to respond less drastically because it may be normal for there to be errors in the data (e.g. a user doing data entry of some sort). In those cases the proper handling might be to report the error back to the user and continue functioning.
If there is a specified pre-condition for the method to take a non-null message parameter, then you want the program to FAIL as soon as the pre-condition doesn't hold and the source of the bug must then be fixed.
I believe assertions are more important when developing safety-critical software. And certainly you would rather use assertions when the software has been formally specified.
For an excellent discussion of assertions (and many other topics related to code construction), check out Code Complete by Steve McConnel. He devotes an entire chapter to effective use of assertions.
I use them to verify that I have been supplied valid dependent class. for exmaple in constructor DI, you usually are accepting some sort of external class that you are dependent on to provide some action or service.
so you can assert(classRef !- null,"classRef cannot be null"); instead of waiting for you to pass a message to classRef and getting some other exception such as exception : access violation or something equally ambiguous that might not be immediately obvioius from looking at the code.
It is very useful to test our assumptions. The asserts constantly make sure that the invariant holds true. In short it is used for the following purposes,
It allows to implement fail-fast system.
It reduces the error propagation because of side-effects.
It forbids(kind of sanity-check) the system to enter an inconsistent state because of user-data or by subsequent code changes.
Sometimes, I favor the use of assert_return() when we do not want to use try/catch/throw.
private void WriteMessage(string message)
{
assert_return(message != null, "message is null"); // return when false
File.WriteAllText(FILE_PATH, message);
}
I suggest assert_return() to halt the application by reporting an error in test build. And then in the production system, it should log and error and return from the function saying it cannot do that.

Resources