Can an Invariant method [ContractInvariantMethod] work inside an Interface Contract? - .net-4.0

I'm creating an Interface Contract as described in § 2.8 Interface Contracts of Feb 4, 2011 Code Contracts User Manual (PDF). This is not a problem.
Additionally I want to mix an Object Invariant (see § 4.2 ContractInvariantMethod) into the same Interface Contract. This is a problem. I cannot find examples of Object Invariants being used on Interface Contracts.
I tried adding an Object Invariant to the Interface Contract seen in the following partial code snippet. It compiles. At runtime it doesn't raise any errors, however it doesn't appear to do anything positive (i.e. be invoked) either.
/* Note: The intention of this snippet is to cause the data implementation
* to fail if it is not initalized before its public data access methods are called.
*/
[ContractClassFor(typeof(IDataProxy))]
abstract class IDataProxyContract : IDataProxy
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(IsInited == true, "Instance not initialized.");
}
I can't find documentation that specifically addresses this scenario or refutes it.
At this point I'm unsure if I'm missing a step to make it work, or if Code Contract technology ignores the Object Invariant in this context altogether. I would like to make it work. Does anybody know the answer?

Apparently the answer is in the DevLabs forum answered by Manuel Fahndrich, Microsoft (MSFT):
Object invariants are not supported on interfaces at the moment. I can
see why they might be handy though.
Full context and code sample here...

They are off by default.
My guess is that the contracts are not enabled by the compiler options, so they don't get weaved into the code.
the solution is to download this package from devlabs
http://msdn.microsoft.com/en-us/devlabs/dd491992
after you install it, go to the project properties, and you'll see another tab.
then, you can enable an option: "Perform runtime contract checking: full"

Invariants provide a mechanism for constraining the internal state of an object.
They are seen as implementation details which is why they are implemented inside a private method. Interfaces obviously have no concept of state (even properties are just syntactic sugar for methods), and consequently cannot have invariants. In their most primitive use, invariants are used on fields. However, the concept of automatic properties has obviously blurred this line, leading to confusion in this case.
I agree there should be a more concise way of contracting properties, simply because your pre and post conditions are invariably going to be the same.

Related

How to write a Base contract extendable by other contracts in Corda

I need to build a cordapp with reusable/extendable contract (interface)
I have decided to build a re-usable Cordapp platform that will serve the need of multiple co-operates with minimal updates (per co-operate) when necessary.
I plan to achieve this by creating base classes for the States and Contracts which shall contain every possible common properties for each kind of Payment Instrument and will be extended by other regular States and Contracts. As for the flows, I can have all basic generic flows ready. Customized flows can then be written upon requirement and this (hopefully) would only be minimal additions to be made upfront.
In order to achieve the above plans, I recently tried it out with a test Cordapp.
For States, I observed that I could possibly have a base (Interface) State with all possible common parameters (for a particular Payment Instrument), which can then be extended by other regular States as planned.
For Contracts, I had a bit of challenge.
While having an Interface Contract IXContract being extended (by an open class) XContract, I got a transaction error “Contract verification failed: Required com.template.contracts.IXContract.Commands command, contract: com.template.contracts.XContract”. This seem to be caused by a conflict in contracts being used by a single XState.
I also modified the code to having IXContract as an open class and and XContract as abstract class. This returned a successful transaction, however the invalid rule in the IXContract was not caught and this is not the expected behavior of the project.
To avoid contract conflicts, I tried the usual programming style of simple classes. With base class IXContract, this time not extending the Contract interface (which makes it not a contract class), but contains a BaseContract method with contract rules. I then autowired this class in the regular XContract class (still extending the contract interface) and called the BaseContract method to apply the contract rule within it. This was tested successfully and the contract rules were caught as required. For more assurance, the flow was adjusted to align with the contract rules and the test transaction was then successful.
I however noted that this would obviously lead to us having a huge file of BaseContract class in future, but these have been
our test trials so far.
Is this a good route towards implementing a reliable project with no possible risk upfront?
Kindly advice on a best way to achieve it if you can already foresee a disadvantage in our test trials.
I would recommend against creating sub contract interfaces only because you may run into problems in corda that you don't expect. Almost all the cordapps I've ever seen do not have a need for a more specific contract interface that can still apply to multiple state types. I'd just go through the pain of having a larger contract class, there may be plenty of other ways.
Assuming you still want to do this, then just watch the abstractions carefully, but kotlin will let you do this, just make sure to implement the contract interface correctly and you should be able to get it to work without too much pain.
interface Named {
val name: String
}
interface Person : Named {
val firstName: String
val lastName: String
override val name: String get() = "$firstName $lastName"
}
So in the case of a corda contract you should be good just doing this for the contract interface.
class IOUContract : Contract {
companion object {
#JvmStatic
val IOU_CONTRACT_ID = "net.corda.training.contracts.IOUContract"
}
You may want to also get the command interface as well.
good luck!

Dbc - anyone actually dare not to check preconditions in the called routines?

I know that DbC mandates that the caller is responsible for the precondition (parameters or maybe values of member variables) and I have just read, in one of the books, that actually few people are bold enough to really leave all the responsibility up to the calling code and do not check the input in the called routine.
But I am thinking, doesn't it also lead to duplication? What if I need to call a method from several places.. in all those places I would need to make sure the preconditions are met..
bool AddEmployee(Employee e)
{
//precondition: List of employees is not full, employee is not empty...
EmployeeList.Add(e);
}
I could call it from several modules (Employee management, HR module..) so I do not get whether I truly should check for preconditions in all those places.
The contract states that it is the callers responsibility to ensure that the pre-conditions are met.
The contract states clearly who is responsible for a bug. If you fail to meet a pre-condition its the caller. If you fail to meet a post-condition its the callee. That is useful enough alone that its worth documenting the contract.
Sometimes you can write your code so that the pre-conditions don't need to be checked. For example:
Foo()
{
int x = 1;
Bar(x);
}
Bar(int x) [[expects: x>0]]
{
}
You set x so you know it can't be less than zero.
At other times you do need to check them. It does sometimes create duplication . I have not found this to be a significant problem often but you may sometimes see patterns like:
SafeBar(int x)
{
if (x <= 0) throw SomeException();
else Bar(x);
}
This assumes of course that errors can be handled in the same way for each use, which is not always the case.
Removing pre-condition checks is a performance optimisation. As we know premature optimisation is the root of all evil, so it should only be done when necessary.
Now another factor is implementation. Few languages support checking contracts at compile time. It was recently voted into C++20 but at the time of writing there is only an experimental implementation.
C++20 uses attributes as above. Attributes are not supposed to change runtime behaviour.
If you don't have compile time support you will typically find implementations using some sort of assertion macro. Personally I use one that throws an exception. You are then using standard exception handling mechanism for handling bugs (some consider this inappropraite) but you don't necessarily need to check the contract at the call site.
Why might it be inappropriate? It is worth remembering that a contract violation is a bug. If you run the function without meeting the pre-condition you are invoking undefined behaviour. In principle anything could happen. It could even format your hard-drive (though that is unlikely). Checking the pre-condition at runtime is like defensive coding. If the assertion causes an exception then undefined behaviour never occurs. That is safer and makes it easier to debug. But from one point of view you've modified the contract.
In general checking contracts at compile time is undecidable. Quoting the linked answer:
If the Theorem Prover can prove that a contract will always be
violated, that's a compile error. If the Theorem Prover can prove that
a contract will never be violated, that's an optimization.
Proving contracts in general is equivalent to solving the Halting Problem and
thus not possible. So, there will be a lot of cases, where the Theorem
Prover can neither prove nor disprove the contract.
In that case, a runtime check is emitted
A slight aside as the question is marked language agnostic but an issue I have with the C++20 proposal is that it seems to omit the runtime check for the other cases. It also says explicitly that it should not be possible to set the violation handler at run time:
There should be no programmatic way of setting or modifying the violation handler
It also mandates default choice of calling std::terminate() on contract violation to end the whole process. This would be a bad thing(tm) for something like a multithreaded fault tolerant task scheduler. A bug in one task should not kill the whole process.
I think the reasoning is that C++20 contracts are intended as a compile time feature only. That includes evaluating them in compile time meta-pograms using constexpr and consteval. The feature allows compiler venders to start adding theorem provers to check contracts which was not possible before. This is important and opens up many new opportunities.
Hopefully a pragmatic modification considering the runtime possibilities will follow.
The downside is that in the short term you will need to retain your assertions. If, like me, you use Doxygen for documentation (which does not yet understand contracts) you have triple redundancy. For example:
///
/// #brief
/// Bar does stuff with x
///
/// #pre
/// #code x > 0 #endcode
///
void Bar(int x) [[expects: x > 0]]
{
{ //pre-conditions
assertion(x>0);
}
...do stuff
}
Note that the C assert() macro doesn't throw. Hence we use our own assertion() macro that does. The CppCoreGuidelines support library includes Expects() and Ensures(). I'm not sure if they throw or call std::terminate().

Check if a class implements an interface at run-time

Say FrameworkA consumes a FrameworkA.StandardLogger class for logging. I want to replace the logging library by another one (the SuperLogger class).
To make that possible, there are interfaces: FrameworkA will provide a FrameworkA.Logger interface that other libraries have to implement.
But what if other libraries don't implement that interface? FrameworkA might be a not popular enough framework to make SuperLogger care about its interface.
Possible solutions are:
have a standardized interface (defined by standards like JSR, PSR, ...)
write adapters
What if there is no standardized interface, and you want to avoid the pain of writing useless adapters if classes are compatible?
Couldn't there be another solution to ensure a class meets a contract, but at runtime?
Imagine (very simple implementation in pseudo-code):
namespace FrameworkA;
interface Logger {
void log(message);
}
namespace SuperLoggingLibrary;
class SupperLogger {
void log(message) {
// ...
}
}
SupperLogger is compatible with Logger if only it implemented Logger interface. But instead of having a "hard-dependency" to FrameworkA.Logger, its public "interface" (or signature) could be verified at runtime:
// Something verify that SupperLogger implements Logger at run-time
Logger logger = new SupperLogger();
// setLogger() expect Logger, all works
myFrameworkAConfiguration.setLogger(logger);
In the fake scenario, I expect the Logger logger = new SupperLogger() to fail at run-time if the class is not compatible with the interface, but to succeed if it is.
Would that be a valid thing in OOP? If yes, does it exist in any language? If no, why is it not valid?
My question stands for statically-typed languages (Java, ...) or dynamically typed languages (PHP, ...).
For PHP & al: I know when there is no type-check you can use any object you want even if it doesn't implement the interface, but I'd be interested in something that actually checks that the object complies with the interface.
This is called duck typing, a concept that you will find in Ruby ("it walks like a duck, it quacks like a duck, it must be a duck")
In other dynamically typed languages you can simulate it, for example in PHP with method_exists. In statically typed languages there might be workarounds with reflection, a search for "duck typing +language" will help to find them.
This is more of a statically typed issue than a OOP one. Both Java and Ruby are OO languages, but Java woudlnt allow what you want (as its statically typed) but Ruby would (as its dynamically typed).
From a statically typed language point of view one of the major (if not the major) advantage is knowing at compile time if an assignment is safe and valid. What you're looking for is provided by dynamically typed languages (such as Ruby), but isnt possible in a statically typed language - and this is by design (compile time safety).
You can, but it is ugly, do something like (in Java):
Object objLogger = new SupperLogger();
Logger logger = (Logger)objLogger;
This would pass at compile time but would fail at runtime if the assignment was invalid.
That said, the above is pretty ugly and isnt something I would do - it doesnt give you much and risks an unpleasant (and possibly suprising) exception at runtime.
I guess the best you could hope for in a language like Java would be to abstract the creation away from where you want to use it:
Logger logger = getLogger();
With the internals of getLogger deciding what to return. This however just defers the actual creation to further down - you'll still have to do so in a statically typed safe way.

FxCop (/VS2010 Code Analysis), possible to flag method result as "callers responsibility now" for IDisposable?

If I write the following code:
public void Execute()
{
var stream = new MemoryStream();
...
}
then code analysis will flag this as:
Warning 1 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()', call System.IDisposable.Dispose on object 'stream' before all references to it are out of scope. C:\Dev\VS.NET\DisposeTest\DisposeTest\ServiceUser.cs 14 DisposeTest
However, if I create a factory pattern, I still might be required to dispose of the object, but now FxCop/Code Analysis doesn't complain. Rather, it complains about the factory method, not the code that calls it. (I think I had an example that did complain about the factory method, but the one I post here doesn't, so I struck that out)
Is there a way, for instance using attributes, to move the responsibility of the IDisposable object out of the factory method and onto the caller instead?
Take this code:
public class ServiceUser
{
public void Execute()
{
var stream = StreamFactory.GetStream();
Debug.WriteLine(stream.Length);
}
}
public static class StreamFactory
{
public static Stream GetStream()
{
return new MemoryStream();
}
}
In this case, there are no warnings. I'd like FxCOP/CA to still complain about my original method. It is still my responsibility to handle that object.
Is there any way I can tell FxCOP/CA about this? For instance, I recently ventured into the annotation attributes that ReSharper has provided, in order to tell its analysis engine information it would otherwise not be able to understand.
So I envision something like this:
public static class StreamFactory
{
[return: CallerResponsibility]
public static Stream GetStream()
{
return new MemoryStream();
}
}
Or is this design way off?
There is a difference between FxCop 10 (which ships with the Windows 7 and .NET 4.0 SDK) and Code Analysis 2010 (which ships with Visual Studio Premium and higher). Code Analysis 2010 has a set of additional rules, which includes a highly improved version of the IDisposable rules.
With Code Analysis 2010 under Visual Studio Premium, the Factory isn't being flagged (as the rule now sees the IDisposable variable is returned to the calling method). The Receiving method, however, isn't flagged either, due to one of the corner case exceptions to the rule. There is a list of method names that will cause the rule to trigger. If you rename your GetStream method to CreateStream, suddenly the rule will trigger:
Warning 4 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()',
call System.IDisposable.Dispose on object 'stream' before all references to it are out
of scope. BadProject\Class1.cs 14 BadProject
I was unable to locate the list of method pre-fixes that will work. I've tried a few and Create~, Open~ trigger the rule, many others that you might expect to work, don't, including Build~, Make~, Get~.
Additionally there is a long list of bugs surrounding this rule. The rule was altered in Visual Studio 2010 to trigger fewer false positives, but now it sometimes misses items it should have flagged (and would have flagged in the previous version). There wasn't enough time to fix the rules in the Visual Studio 2010 time frame (check the bug report comments).
With the upcoming Roslyn compilers, Code Analysis will probably see a major upgrade, until then there are only minor updates to be expected. The current build of Visual Studio Dev11 does not trigger where you want it.
So concluding, no your attribute wouldn't help much, as the rule already detects that you're passing the IDisposable as a return value. Thus Code Analysis knows it's not good to dispose it before returning. If you're using the undocumented naming rules, the rule will trigger. Maybe an attribute could extend the naming rules, but I'd rather have Microsoft would actually fix the actual rule.
I created a connect bug requesting the naming guideline to be documented in the rules documentation.
Comment from Microsoft:
Posted by Microsoft on 1/19/2012 at 10:41 AM
Hello,
Thank you for taking the time to investigate this and file the request for the documentation update. However after some discussion with our documentation team, we have decided to not document the naming convention as you requested.
As you indicated on the stackoverflow thread, there have historically been a lot of reliability issues with this rule, and keying off of the names was an internal implementation detail added to try to reduce the number of false positives. However this is not considered prescriptive guidance for how developers should name their methods, it was added after a survey of common coding practices. We believe the long-term fix is to improve the reliability of the rule, not add naming guidance to our public documentation based on internal implementation details that will continue to change as the rule is improved.
Best Regards,
Visual Studio Code Analysis Team

"Fluent interfaces" that maintain order in the invokation chain

Is there an elegant/convinient way (without creating many "empty" classes or at least they should be not annoying) to have fluent interfcaes that maintain order on compilation level.
Fluent interfaces:
http://en.wikipedia.org/wiki/Fluent_interface
with an idea to permit this compilation
var fluentConfig = new ConfigurationFluent().SetColor("blue")
.SetHeight(1)
.SetLength(2)
.SetDepth(3);
and decline this
var fluentConfig = new ConfigurationFluent().SetLength(2)
.SetColor("blue")
.SetHeight(1)
.SetDepth(3);
Each step in the chain needs to return an interface or class that only includes the methods that are valid to use after the current step. In other words, if SetColor must come first, ConfigurationFluent should only have a SetColor method. SetColor would then return an object that only has a SetHeight method, and so forth.
In reality, the return values could all be the same instance of ConfigurationFluent but cast to different interfaces explicitly implemented by that class.
I've got a set of three ways of doing this in C++ using essentially a compile time FSM to validate the actions. You can find the code on github.
The short answer is no, there is no elegant or convenient way to enforce an order of constructing a class that properly impelemnts the "Fluent Interface" as you've linked.
The longer answer starts with playing devil's advocate. If I had dependent properties (i.e. properties that required other properties to be set first), then I could implement them something like this:
method SetLength(int millimeters)
if color is null throw new ValidationException
length = millimeters
return this
end
(NOTE: the above does not map to any real language, it is just psuedocode)
So now I have exceptions to worry about. If I don't obey the rules, the fluent object will throw an exception. Now let's say I have a declaration like yours:
var config = new Fluent().SetLength(2).SetHeight(1).SetDepth(3).SetColor("blue");
When I catch the ValidationException because length depends on the color being set first, how am I as the user supposed to know what the correct order is? Even if I had each SetX method on a different line, the stacktrace will just give me the line where the config variable was declared in most languages. Furthermore, how am I supposed to keep the rules of this object straight in my head compared to other objects? It is a cocophony of conflicting ideals.
Such precedence checks violate the spirit of the "Fluent Interface" approach. That approach was designed for conveniently configure complex objects. You take the convenience out when you attempt to enforce order.
To properly and elegantly implement the fluent interface there are a couple of guidelines that are best observed to make consumers of your class thank you:
Provide meaningful default values: minimizes need to change values, and minimizes chances of creating an invalid object.
Do not perform configuration validation until explicitly asked to do so. That event can be when we use the configuration to create a new fully configured object, or when the consumer explicitly calls a Validate() method.
In any exceptions thrown, make sure the error message is clear and points out any inconsistencies.
maybe the compiler could check that methods are called in the same order as they are defined.
this could be a new feature for compilers.
Or maybe by means of annotations, something like:
class ConfigurationFluent {
#Called-before SetHeight
SetColor(..) {}
#Called-After SetColor
SetHeight(..) {}
#Called-After SetHeight
SetLength(..){ }
#Called-After SetLength
SetDepth(..) {}
}
You can implement a state machine of valid sequence of operations and on each method call the state machine and verify if the sequence of operation is allowed or throw an exception if not.
I will not suggest this approach for Configurations though, it can get very messy and not readable