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

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

Related

Defining own CONTROL exception

The subject says it all: can I define own control exception which would handled by the CONTROL block? Applying the X::Control role is useless:
class CX::Whatever does X::Control {
method message { "<whatever control exception>" }
}
do {
CX::Whatever.new.throw;
CONTROL {
say "CONTROL!!!";
default {
say "CONTROL: ", $_.WHAT;
}
}
}
By looking into the core sources I could guess that only a predefined set of exceptions is considered suitable for CONTROL, but not sure I didn't miss a thing.
This hasn't been possible in the past, however you're far from the first person to ask for it. Custom control exceptions would provide a way for framework-style things to do internal control flow without CATCH/default in user code accidentally swallowing the exceptions.
Bleeding edge Rakudo now contains an initial implementation of taking X::Control as an indication of a control exception, meaning that the code as you wrote it now does as you expect. This will, objections aside, appear in the 2019.01 Rakudo release, however should be taken as a draft feature until it also appears in a language specification release.
Further, a proposed specification test has been added, so unless there are objections then this feature will be specified in a future Perl 6 language release.

Does dependency inversion really work?

I have read about Dependency Inversion (the 'D' in SOLID) and looked at a few examples here.
However, I can't see how the dependency can be totally gotten rid of!
According to the article the relation Consumer --> Utility can be changed to Utility --> Consumer by introducing a contract/interface in the consumer package.
Further more, the reversed dependency can be fully decoupled by moving the contract/interface to a separate package like Consumer --> Contracts <-- Utility.
Now, with the above layout; for Consumer to use the Utility shouldn't there be a factory? Which then brings back the original dependency as follows:
Consumer --> Factory --> Utility
If it helps, I'll describe a place where Dependency Inversion Principle came about where I work.
I do work with a Content Management system - a system that stores images and lets people retrieve them.
Well, here's what our current (bad) C++ code looks like:
Retrieve()
// code to initialize a vendor's API
// code to pass in system credentials
// code to clear the vendor's "current workitem list"
// code to pull the document to the current workitem list
// code to get content files from that document
// code to format those files for passing back to the user
Basically, hooks into the vendor left and right. And this is just one function - it's the same throughout the code.
Now, imagine you're told:
"Sumith, we're moving to a new Imaging system - we're moving from Vendor ABC to Vendor XYZ. Start working on changing the code to work with the new system."
... uh... um.... yeah... you're going to have to redo all that code. In every single function, in every part of your program that interfaces with that vendor. The Dependency Inversion joke basically goes, "You wouldn't sodder your lamp directly into the electrical wiring, would you?" Well, our group has.
Now, here's how Dependency Inversion handles that.
Retrieve()
// Code that initializes an Interface we coded up
// Code that uses that interface, to pull up a doc (which, again, is an interface)
// Code that returns that doc interface's data
... and that interface?
Interface SimpleExample
void Initialize();
DocExample GetDoc();
Interface DocExample
byte[] GetFileData();
So, when the manager says, "Hey, we're moving to Vendor XYZ..."
... all you need to think to yourself is, "Okay, I need to program a new class that implements my 'SimpleExample' interface, and then I can plug it right into my existing code without having to change any of that program's code!"
Right now, I'm working on rewriting the whole thing, and let me tell you, Dependency Inversion Principle is already saving me boatloads of time. I write a "ContentManagement" interface (well, I'm using an abstract class, but it functions similarly) - and all I have to do, is program a class that implements the ContentManagement interface. Then I can have code like this:
ContentManagement vendorToUse;
if (some criteria or such)
vendorToUse = instanceOfNewVendor;
else
vendorToUse = instanceOfOldVendor;
vendor.Initialize();
Document doc = vendor.Retrieve(...);
... etc
... trying to do that without D.I. would be a nightmare - you'd basically have to have two separate versions of the function.

Modular design and intermodule references

I'm not so sure the title is a good match for this question I want to put on the table.
I'm planning to create a web MVC framework as my graduation dissertation and in a previous conversation with my advisor trying to define some achivements, he convinced me that I should choose a modular design in this project.
I already had some things developed by then and stopped for a while to analyze how much modular it would be and I couldn't really do it because I don't know the real meaning of "modular".
Some things are not very cleary for me, like for example, just referencing another module blows up the modularity of my system?
Let's say I have a Database Access module and it OPTIONALY can use a Cache module for storing results of complex queries. As anyone can see, I at least will have a naming dependency for the cache module.
In my conception of "modular design", I can distribute each component separately and make it interact with others developed by other people. In this case I showed, if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
And so, I was wondering if this is really a modular design yet.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning. To extend functionalities, I could create some structure based on Decorators and Adapters.
To clarify things a little bit, here is an example (in PHP):
Before
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public doComplexOperation();
}
class DbAccess implements DbAccessInterface {
private $cacheManager;
public function __construct(..., CacheManager $cacheManager = null) {
// ...
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
if ($this->cacheManager !== null) {
// return from cache if valid
}
// complex operation
}
}
After
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public function doComplexOperation();
}
class DbAccess implements DbAccessInterface {
public function __construct(...) {
// ...
}
public function doComplexQuery() {
// complex operation
}
}
// And now the integration module
class CachedDbAcess implements DbAccessInterface {
private $dbAccess;
private $cacheManager;
public function __construct(DbAccessInterface $dbAccess, CacheManager $cacheManager) {
$this->dbAccess = $dbAccess;
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
$cache = $this->cacheManager->get("Foo")
if($cache->isValid()) {
return $cache->getValue();
}
// Do complex operation...
}
}
Now my question is:
Is this the best solution? I should do this for all the modules that do not have as a requirement work together, but can be more efficient doing so?
Anyone would do it in a different way?
I have some more further questions involving this, but I don't know if this is an acceptable question for stackoverflow.
P.S.: English is not my first language, maybe some parts can get a little bit confuse
Some resources (not theoretical):
Nuclex Plugin Architecture
Python Plugin Application
C++ Plugin Architecture (Use NoScript on that side, they have some weird login policies)
Other SO threads (design pattern for plugins in php)
Django Middleware concept
Just referencing another module blows up the modularity of my system?
Not necessarily. It's a dependency. Having a dependencies is perfectly normal. Without dependencies modules can't interact with each other (unless you're doing such interaction indirectly which in general is a bad practice since it hides dependencies and complicates the code). Modular desing implies managing of dependencies, not removing them.
One tool - is using interfaces. Referencing module via interface makes a so called soft dependency. Such module can accept any implementation of an interface as a dependency so it is more independant and as a result - more maintainable.
The other tool - designing modules (and their interfaces) that have only single responcibility. This also makes them more granular, independant and maintainable.
But there is a line which you should not cross - blindly applying these tools may leed to a too modular and too generic desing. Making things too granular makes the whole system more complex. You should not solve universe problems, making generic modules, that all developers can use (unless it is your goal). First of all your system should solve your domain tasks and make things generic enough, but not more than that.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning
It is great if you came up with this idea by yourself. The statement itself, is a key to modular programming.
Plugin architecture is the best in terms of extensibility, but imho it is hard to maintenance especially in intra application. And depending the complexity of plugin architecture, it can make your code more complex by adding plugin logics, etc.
Thus, for intra modular design, I choose the N-Tier, interface based architecture. Basically, the architecture relays on those tiers:
Domain / Entity
Interface [Depend on 1]
Services [Depend on 1 and 2]
Repository / DAL [Depend on 1 and 2]
Presentation Layer [Depend on 1,2,3,4]
Unfortunately, I don't think this is achieveable neatly in php projects as it need separated project / dll references in each tier. However, following the architecture can help to modularize the application.
For each modules, we need to do interface-based design. It can help to enhance the modularity of your code, because you can change the implementation later, but still keep the consumer the same.
I have provided an answer similiar to this interface-based design, at this stackoverflow question.
Lastly but not least, if you want to make your application modular to the UI, you can do Service Oriented Architecture. This is simply make your application as bunch of services, and then make the UI to consume the service. This design can help to separate your UI with your logic. You can later use different UI such as desktop app, but still use the same logic. Unfortunately, I don't have any reliable source for SOA.
EDIT:
I misunderstood the question. This is my point of view about modular framework. Unfortunately, I don't know much about Zend so I will give examples in C#:
It consist of modules, from the smallest to larger modules. Example in C# is you can using the Windows Form (larger) at your application, and also the Graphic (smaller) class to draw custom shapes in the screen.
It is extensible, or replaceable without making change to base class. In C# you can assign FormLoad event (extensible) to the Form class, inherit the Form or List class (extensible) or overridding form draw method to create a custom window graphic (replaceable).
(optional) it is easy to use. In normal DI interface design, we usually inject smaller modules into a larger (high level) module. This will require an IOC container. Refer to my question for detail.
Easy to configure, and does not involve any magical logic such as Service Locator Pattern. Search Service Locator is an Anti Pattern in google.
I don't know much about Zend, however I guess that the modularity in Zend can means that it can be extended without changing the core (replacing the code) inside framework.
If you said that:
if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
Then it is not modular. It is integrated, means that your Database Access module will not work without Cache. In reference of C# components, it choose to provide List<T> and BindingList<T> to provide different functionality. In your case, imho it is better to provide CachedDataAccess and DataAccess.

Can an Invariant method [ContractInvariantMethod] work inside an Interface Contract?

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.

Does an isolate / sandbox access modifier exist in any language?

Is there a language which has a feature that can prevent a class accessing any other class, unless an instance or reference is contained?
isolated class Example {
public Integer i;
public void doSomething()
{
i = 5; // This is ok because i belongs to this class
/*
* This is forbidden because this class can only
* access anything contained within, nothing outside
*/
System.out.println("This does not work.");
}
}
[edit]An example use case might be a plugin system. I could define a plugin object with references to certain objects that class can manipulate, but nothing else is permissible. It could potentially make security concerns much easier.[/edit]
I'm not aware of any class-based access modifiers with such intent, but I believe access modifiers to be misguided anyway.
Capability-based security or, more specifically, the object-capability model seems to be what you want.
http://en.wikipedia.org/wiki/Object-capability_model
The basic idea is that in order to do anything with an object, you need to hold a reference to it. Withhold the reference and no access is possible.
Global things (such as System.out.println) and a few other things are problematic features of a language, because anyone can access them without a reference.
Languages such as E, or tools like google caja (for Javascript) allow proper object-capability models. Here an example in JS:
function Example(someObj) {
this.someObj = someObj;
this.doStuff() = function() {
this.someObj.foo(); //allowed, we have been given a reference to it
alert("foobar"); //caja may deny/proxy access to global "alert"
}
}
Any language where you must include headers would probably count: Just don't include any headers.
However, I would wager that there's no language that explicitly forbids external access. What's the point? You can't do anything if you can't access the outside world. And, why would the reference to Integer be okay, but System.out.println not be?
If you clarify the potential use-case, we can probably help you better...
Edit for your Edit:
I thought you might be going there.
If this is for security, it's flawed from the start. Let's examine:
class EvilCode {
void DoNiceThings() {
HardDrive.Format();
}
}
What incentive do I have to voluntarily place a keyword on my class? I'm certainly not going to because I'm nice, since I'm not!
One thing to consider is that any time you're loading native code that's not your own (native, in this case, means not scripted), you're potentially allowing a bad guy to run his code. No language features are going to protect you from that.
The proper answer depends on your target language. Java has Security descriptors, .NET lets you create AppDomains with restricted permissions, etc. Unfortunately, I'm not an expert in these fields.