How does Contract.Ensures work? - c#

I'm starting to use Code Contracts, and whilst Contract.Requires is pretty straight forward, I'm having trouble seeing what Ensures actually does.
I've tried creating a simple method like this:
static void Main()
{
DoSomething();
}
private static void DoSomething()
{
Contract.Ensures(false, "wrong");
Console.WriteLine("Something");
}
I never see the message "wrong" though, nor does it throw exceptions or anything else.
So what does it actually do ?

It's odd for it to not throw anything - if you're running the rewriter tool with the appropriate settings. My guess is that you're running in a mode which doesn't check postconditions.
The confusing thing about Contract.Ensures is that you write it at the start of the method, but it executes at the end of the method. The rewriter does all the magic to make sure it executes appropriately, and is given the return value if necessary.
Like many things about Code Contracts, I think it's best to run Reflector on the results of the rewriter tool. Make sure you've got the settings right, then work out what the rewriter has done.
EDIT: I realise I haven't expressed the point of Contact.Ensures yet. Simply put, it's to ensure that your method has done something by the end - for example, it could ensure that it's added something to a list, or (more likely) that the return value is non-null, or positive or whatever. For example, you might have:
public int IncrementByRandomAmount(int input)
{
// We can't do anything if we're given int.MaxValue
Contract.Requires(input < int.MaxValue);
Contract.Ensures(Contract.Result<int>() > input);
// Do stuff here to compute output
return output;
}
In the rewritten code, there will be a check at the point of return to ensure that the returned value really is greater than the input.

Related

C# Cancel Method via calling a Method

Hello StackOver Community,
I have the following c#-code
void foo(int x)
{
if(x<=0)
{
return;
}
do something more...
.
.
.
}
I want to get rid of the if statement by calling a function which will "return" my foo function if the condition x<= 0 is met.
That is
void foo(int x)
{
TerminateIfNegative(x);
do something more...
.
.
.
}
private ???? TerminateIfNegative(int a)
{
if (a<=0)
{
"Make the method which called me "return" at the place I was called"
}
}
I hope it is somehow clear what I want to do. Does someone have an idea?
Cheers,
Florian
When a method's return type is void, this method does not return anything. There are only the following options to stop the execution of commands inside a void method:
Throw an exception
Use return; (which is the most common way)
If a negative value should not be passed as an argument to your method, then it is valid to throw an exception and document that, in order callers of this method to be aware of this from the very beggining.
The behaviour you´re asking for is common in procedural programming where you have a common linear program-flow from the very first line to the very last. This will apply to a line-by-line execution, which isn´t what OOP is about. There are good reasons we usually discourage use of goto and other stuff that controls program-flow as it will make it very hard to follow your code, e.g. when debugging. In fact this leads to spaghetti-code.
Imagine you want to debug your app in a few months. You step through your code until you reach Foo, step into it to sea what it does and - woaah, what is this - your debuger jumps out of Foo for whatever reason. It´s completely unclear why the method simply stops its execution.
What you seem to want actually is performing some checks on your user-input. So if your user types in a negative number your program should stop. It´s pure fine to throw an exception in this case, which basically indicates that a method cannot do what it is supposed to do. You could just create some Validate-method that throws an exception on ivalid input:
void Validate(int x)
{
if(x <= 0)
throw new InvalidArgumentException("x must not be negative");
}
This leaves it to the caller of the method how to handle an error. This way your Validate-method just validates the input. It should not terminate the calling method, which would break the single-responsibility-principle, wouldn´t it?
However throwing an exception in your case seems a bit like taking a a sledgehammer to crack a nut. The most simple and cleanest way is to do exactly what you want to avoid. Have an if-statement that terminates foo if the input is invalid:
void foo()
{
if(!Validate(x))
return;
}
bool Validate(int x)
{
return x > 0;
}
Actually there is a solution for this. And a pretty ugly one.
I'm aware that probably nobody will agree that this should be used, but I will present it anyway. Here you have the infamous goto solution:
void foo(int x)
{
TerminateIfNegative(x);
do something more...
.
.
.
EndOfFoo:
}
private void TerminateIfNegative(int a)
{
if (a<=0)
{
goto EndOfFoo;
}
}

Is removing unreachable code always safe?

Assume I have a tool that automatically removes C# code that is detected by the compiler as unreachable. Is there a situation in which such operation can get me into trouble? Please share interesting cases.
Here's the interesting example. Consider a function like this:
public static IEnumerable<int> Fun()
{
if (false)
{
yield return 0;
}
}
The line with yield is detected as unreachable. However, removing it will make the program not compilable. yield contained in the function gives the compiler information to reorganize the function so that not doing anything just returns the empty collection. With yield line removed it looks just like ordinary function with no return while it's required.
As in the comment, the example is contrived, however instead of false we could have a constant value from other, generated project etc (i.e. such piece of code wouldn't look so obvious as in this case).
Edit:
Note that the yield construct is actually very similar to async/await. Yet with the latter creators of the language took a different (IMO better) approach that prevents such scenarios. Iterator blocks could be defined in the same way (using some keyword in function signature instead of detecting it from the function body).
I wouldn't do this automatically, for reasons mentioned in other answers, but I will say here that I'd have a strong bias towards removing unused code over keeping it. After all, tracking obsolete code is what source control is for.
This example is contrived, but this will get flagged for removal (in default DEBUG settings) and produce different behaviors when removed.
public class Baz { }
public class Foo
{
public void Bar()
{
if (false)
{
// Will be flagged as unreachable code
var baz = new Baz();
}
var true_in_debug_false_in_release =
GetType()
.GetMethod("Bar")
.GetMethodBody()
.LocalVariables
.Any(x => x.LocalType == typeof(Baz));
Console.WriteLine(true_in_debug_false_in_release);
}
}
In Release mode (with default settings), the "unreachable code" will optimized away and produce the same result as if you deleted the if block in DEBUG mode.
Unlike the example using yield, this code compiles regardless of whether or not the unreachable code is removed.
Further to Dan Bryant's answer, here's an example of a program whose behaviour will be altered by a tool that's smarter than the C# compiler in finding and removing unreachable code:
using System;
class Program
{
static bool tru = true;
static void Main(string[] args)
{
var x = new Destructive();
while (tru)
{
GC.Collect(2);
}
GC.KeepAlive(x); // unreachable yet has an effect on program output
}
}
class Destructive
{
~Destructive()
{
Console.WriteLine("Blah");
}
}
The C# compiler does not try very hard to prove that GC.KeepAlive is unreachable, so it doesn't eliminate it in this case. As a result, the program loops forever without printing anything.
If a tool proves that it's actually unreachable (fairly easy in this example) and removes it, the program behaviour is changed. It will print "Blah" straight away and then loop forever. So it has become a different program. Try it if you have doubts; just comment out that unreachable line and see the behaviour change.
If GC.KeepAlive was there for a reason then this change would, in fact, be unsafe, and will make the program misbehave at some point (probably just crash).
One rare boundary case is if the unreachable code contains a GC.KeepAlive call. This very rarely comes up (as it is related to particular hacky use cases of unmanaged/managed interop), but if you are interoperating with unmanaged code that requires this, removing it could cause intermittent failures if you're unlucky enough to have GC trigger at just the wrong moment.
UPDATE:
I've tested this and I can confirm that Servy is correct; the GC.KeepAlive call does not take effect due to the fact that the compiler proves it can never actually use the reference. This is not because the method is never executed (the method doesn't have to execute it for it impact the GC behavior), but because the compiler ignores the GC.KeepAlive when it is provably not reachable.
I'm leaving this answer up because it's still interesting for the counter case. This is a mechanism for breaking a program if you modify your code to make it unreachable, but don't move the GC.KeepAlive to make sure it still keeps the reference alive.

Knowing in what part the method returned

Is it possible to get run-time information about where a method has returned?
I mean, if the method returned after running all its lines of code, or because of an earlier
return statement that occurred due to some condition.
The scenario is using interceptor for creating UnitOfWork that should exists in method scope.
For example, lets consider this code:
[UnitOfWork]
public void Foo()
{
// insert some values to the database, using repositories interfaces...
DoSomeChangesInTheDataBaseUsingRepositories();
var result = DoSomethingElse();
if (!result) return;
DoMoreLogicBecuseTheResultWasTrue();
}
I have interceptor class that opens thread static unit of work for methods that are flagged with [UnitOfWork] and when the scope of the method ends it run commit on the UoW and dispose it.
This is fine, but lets consider the scenario above, where for some reason a programmer decided to return in the middle of the method due to some condition, and in that scenario the changes made by the repositories should not be persisted.
I know that this can indicate wrong design of the method, but be aware that it is a possible scenario to be written by a programmer and I want to defend my database from these kind of scenarios.
Also, I don't want to add code to the method itself that will tell me where it ended. I want to infer by the method info somehow its returned point, and if it is not at the end of its scope the interceptor will know not to commit.
The simple answer is use BREAKPOINTS and Debugging.
Edit:- As mentioned by Mels in the comments. This could be a useful suggestion.
If your application is very timing-sensitive, set conditional breakpoints such that they never actually stop the flow of execution. They do keep track of Hit Count, which you can use to backtrace the flow of execution.
Just for your attention. From the microsoft site:-
For those out there who have experience debugging native C++ or VB6
code, you may have used a feature where function return values are
provided for you in the Autos window. Unfortunately, this
functionality does not exist for managed code. While you can work
around this issue by assigning the return values to a local variable,
this is not as convenient because it requires modifying your code. In
managed code, it’s a lot trickier to determine what the return value
of a function you’ve stepped over. We realized that we couldn’t do the
right thing consistently here and so we removed the feature rather
than give you incorrect results in the debugger. However, we want to
bring this back for you and our CLR and Debugger teams are looking at
a number potential solutions to this problem. Unfortunately this is
will not be part of Visual Studio 11.
There are a couple ways that normally indicate that a method exited early for some reason, one is to use the actual return value, if the value is a valid result that then your method probably finished correctly, if its another value then probably not, this is the pattern that most TryXXX methods follow
int i;
//returns false as wasn't able to complete
bool passed = int.TryParse("woo", out i);
the other is to catch/trhow an exception, if an exception is found, then the method did not complete as you'd expect
try
{
Method();
}
catch(Exception e)
{
//Something went wrong (e.StackTrace)
}
Note: Catching Exception is a bad idea, the correct exceptions should be caught, i.e NullReferenceException
EDIT:
In answer to your update, if your code is dependant on the success of your method you should change the return type to a boolean or otherwise, return false if unsuccessful
Generally you should use trace logs to watch you code flow if you cant debug it.
You could always do something like this:
private Tuple<int, MyClass> MyMethod()
{
if (condition)
{
return new Tuple<int, MyClass>(0,new MyClass());
}
else if(condition)
{
return new Tuple<int, MyClass>(1, new MyClass());
}
return new Tuple<int, MyClass>(2,new MyClass());
}
This way you´ll have an index of which return was returning your MyClass object. All depends on what you are trying to accomplish and why - which is at best unclear. As someone else mentioned - that is what return values are for.
I am curios to know what you are trying to do...

C# Boilerplate code

I'm thinking of building some generic extensions that will take a way all these null, throw checks and asserts and instead use fluent APIs to handle this.
So I'm thinking of doing something like this.
Shall() - Not quite sure about this one yet
.Test(...) - Determines whether the contained logic executed without any errors
.Guard(...) - Guards the contained logic from throwing any exception
.Assert(...) - Asserts before the execution of the code
.Throw(...) - Throws an exception based on a certain condition
.Assume(...) - Similar to assert but calls to Contract.Assume
Usage: father.Shall().Guard(f => f.Shop())
The thing is that I don't want these extra calls at run-time and I know AOP can solve this for me, I want to inline these calls directly to the caller, if you have a better way of doing that please do tell.
Now, before I'm researching or doing anything I wonder whether someone already done that or know of a tool that is doing it ?
I really want to build something like that and release it to public because I think that it can save a lot of time and headache.
Some examples.
DbSet<TEntity> set = Set<TEntity>();
if (set != null)
{
if (Contains(entity))
{
set.Remove(entity);
}
else
{
set.Attach(entity);
set.Remove(entity);
}
}
Changes to the following.
Set<TEntity>().Shall().Guard(set =>
{
if (Contains(entity))
{
set.Remove(entity);
}
else
{
set.Attach(entity);
set.Remove(entity);
}
});
Instead of being funny and try to make fun of other people, some people can really learn something about maturity, you can share your experience and tell me what's so good or bad about it, that I'll accept.
I'm not trying to recreate Code Contracts, I know what it is I'm using it everyday, I'm trying to move the boilerplate code that is written to one place.
Sometimes you have methods that for each call you have to check the returned object and is not your code so you can't ensure that the callee won't result a null so in the caller you have to perform null checks on the returned object so I thought of something that may allow me to perform these checks easily when chaining calls.
Update: I'll have to think about it some more and change the API to make the intentions clear and the code more readable.
I think that the idea is not polished at all and that indeed I went too far with all these methods.
Anyways, I'll leave it for now.
It sounds like you're describing something like Code Contracts: http://msdn.microsoft.com/en-us/devlabs/dd491992
If I understand what you're looking for, then the closest thing I've come up with is the extension method:
public static Chain<T>(this T obj, Action<T> act)
{
act(obj);
return obj;
}
This allows you to do the following:
Set.Remove(Set.FirstOrDefault(entity) ?? entity.Chain(a => Set.Add(a)));
As you can see, though, this isn't the most readable code. This isn't to say that Chain extension method is bad (and it certainly has its uses), but that Chain extension method can definitely be abused, so use cautiously or the ghost of programming past will come back to haunt you.

How do I test code that should never be executed?

Following method shall only be called if it has been verified that there are invalid digits (by calling another method). How can I test-cover the throw-line in the following snippet? I know that one way could be to merge together the VerifyThereAreInvalidiDigits and this method. I'm looking for any other ideas.
public int FirstInvalidDigitPosition {
get {
for (int index = 0; index < this.positions.Count; ++index) {
if (!this.positions[index].Valid) return index;
}
throw new InvalidOperationException("Attempt to get invalid digit position whene there are no invalid digits.");
}
}
I also would not want to write a unit test that exercises code that should never be executed.
If the "throw" statement in question is truly unreachable under any possible scenario then it should be deleted and replaced with:
Debug.Fail("This should be unreachable; please find and fix the bug that caused this to be reached.");
If the code is reachable then write a unit test that tests that scenario. Error-reporting scenarios for public-accessible methods are perfectly valid scenarios. You have to handle all inputs correctly, even bad inputs. If the correct thing to do is to throw an exception then test that you are throwing an exception.
UPDATE: according to the comments, it is in fact impossible for the error to be hit and therefore the code is unreachable. But now the Debug.Fail is not reachable either, and it doesn't compile because the compiler notes that a method that returns a value has a reachable end point.
The first problem should not actually be a problem; surely the code coverage tool ought to be configurable to ignore unreachable debug-only code. But both problem can be solved by rewriting the loop:
public int FirstInvalidDigitPosition
{
get
{
int index = 0;
while(true)
{
Debug.Assert(index < this.positions.Length, "Attempt to get invalid digit position but there are no invalid digits!");
if (!this.positions[index].Valid) return index;
index++;
}
}
}
An alternative approach would be to reorganize the code so that you don't have the problem in the first place:
public int? FirstInvalidDigitPosition {
get {
for (int index = 0; index < this.positions.Count; ++index) {
if (!this.positions[index].Valid) return index;
}
return null;
}
}
and now you don't need to restrict the callers to call AreThereInvalidDigits first; just make it legal to call this method any time. That seems like the safer thing to do. Methods that blow up when you don't do some expensive check to verify that they are safe to call are fragile, dangerous methods.
I don't understand why you wouldn't want to write a unit test that exercises "code that should not happen".
If it "should not happen", then why are you writing the code at all? Because you think it might happen of course - perhaps an error in a future refactoring will break your other validation and this code will be executed.
If you think it's worth writing the code, it's worth unit testing it.
It's sometimes necessary to write small bits of code that can't execute, just to appease a compiler (e.g. if a function which always throw an exception, exits the application, etc. is called from a function which is supposed to return a value, the compiler may insist that the caller include a "return 0", "Return Nothing", etc. statement which can never execute. I wouldn't think one should be required to test such "code", since it may be impossible to make it execute without seriously breaking other parts of the system.
A more interesting question comes with code that the processor should never be able to execute under normal circumstances, but which exists to minimize harm from abnormal circumstances. For example, some safety-critical applications I've written start with code something like (real application is machine code; given below is pseudo-code)
register = 0
test register for zero
if non-zero goto dead
register = register - 1
test register for zero
if non-zero goto okay1
dead:
shut everything down
goto dead
okay1:
register = register + 1
if non-zero goto dead
I'm not sure how exactly one would go about testing that code in the failure case. The purpose of the code is to ensure that if the register has suffered electrostatic or other damage, or is otherwise not working, the system will shut down safely. Absent some very fancy equipment, though, I have no idea how to test such code.
Part of the purpose of testing is to test both things that should happen and things that can happen.
If you have code that should never execute, but could under the right (or wrong) conditions, you can verify that the exception occurs in the right conditions (in MS's Unit Test Framework) by decorating your test method with:
[ExpectedException(typeof(InvalidOperationException))]
To rephrase the issue, basically: how do you test an invalid state of your system when you've already gone to a lot of trouble to make sure that the system can't get into that invalid state in the first place?
It will make for slightly slower tests, but I would suggest using reflection to put your system into the invalid state in order to test it.
Also notice that reflection is precisely one of the possible ways for your system to get into that invalid state, which will execute your supposedly impossible to reach code.
If your code was truly impossible to reach, which is not quite the case in your example as far as I see, then you should remove the code. Eg:
public int GetValue() {
return 5;
throw new InvalidOperationException("Somehow the return statement did not work!");
}
I also would not want to write a unit test that exercises code that should never be executed.
What do you mean by "should" here? Like, that it ought not to be executed? Surely it should be ok for the code to be executed in a test. It should be executed in a test.

Categories