Single-use object: yea or nay? - c#

I'm thinking about creating some classes along a "single-use" design pattern, defined by the following features:
Instances are used for performing some task.
An instance will execute the task only once. Trying to call the execute method twice will raise an exception.
Properties can be modified before the execute method is called. Calling them afterward will also raise an exception.
A minimalist implementation might look like:
public class Worker
{
private bool _executed = false;
private object _someProperty;
public object SomeProperty
{
get { return _someProperty; }
set
{
ThrowIfExecuted();
_someProperty = value;
}
}
public void Execute()
{
ThrowIfExecuted();
_executed = true;
// do work. . .
}
private void CheckNotExcecuted()
{
if(_executed) throw new InvalidOperationException();
}
}
Questions:
Is there a name for this?
Pattern or anti-pattern?

This looks like a form of a balking pattern.
If it appears logical for your specific object to behave in this way, I don't see a problem with it.

Streams behave in somewhat similar way (also their use Dispose/Close to lock them for most operations). So it is not exactly surprising pattern.

Related

Is there a way to mark code as non-threadsafe in C#?

Im trying to hunt down a race condition, and I come across a lot of suspecious functions. Most of them are not allowed to be called from two threads at the same time, but its hard to make sure they don't.
Is there some keyword to instruct the runtime to throw an exception as soon as a function is executing in parallel? I know I sometimes get an exception when another thread modifies a collection which im enumerating, but are safeguards like that enough to rely on?
The runtime can halt execution using the lock instruction, so all I need is a lock which throws an error.
You can use Monitor.TryEnter for this:
bool entered = !Monitor.TryEnter(someLockObject);
try
{
if (!entered)
throw Exception("Multi-thread call!");
// Actual code
}
finally
{
if (entered)
{
Monitor.Exit(someLockObject);
}
}
And it would be good to wrap that code in its own class:
public sealed class MultiThreadProtector : IDisposable
{
private object syncRoot;
public MultiThreadProtector(object syncRoot)
{
this.syncRoot = syncRoot;
if (!Monitor.TryEnter(syncRoot))
{
throw new Exception("Failure!");
}
}
public void Dispose()
{
Monitor.Exit(this.syncRoot);
}
}
This way you can execute it as follows:
using (new MultiThreadProtector(someLockObject))
{
// protected code.
}

Ensuring that a call is made to end a chain of methods

Note/Disclaimer: After a few searches, the nearest thing I have I have seen to this post is a post on SO (Method chaining and the finishing problem) which is similar to my question, but doesn't really answer it - but anyway, I hope this is not a duplicate question.
What I am doing:
I have created a fluent interfaceas a facade over an existing logging framework for a bunch of method calls - so my syntax looks a bit like this:
Logger.Debug().Message("Debug message!").WriteToLog();
Logger.Error().Message("An exception occured").Exception(ex).WriteToLog();
I am passing an internal object from one method call to the next object so that when the final call is made (the WriteToLog method); the message is written to a log file somewhere.
The bit I think smells
In order to verify (only when the application is built in debug mode), I have a property on a context class (just a property bag object) which gets passed from method call to the returned object until the chain terminates; it is a boolean and defaults to false.
This property is evaluated in the context class destructor using a Debug.Assert to determine if the final method to end the chain is called so any logging errors can be picked up during development.
(the property, the code which sets the property and the destructor itself are all created in the context of a #if DEBUG pre-processor directive, so if it is built in release or if the symbol doesn't exist, the code will not get compiled.)
I know using a destructor is bad in c#2.0 and above, and that I may not have access to properties because I believe there are no guarantees about the finalization order. This is why it only happens when built in Debug mode, and why I would like to get away from it.
The reason I am trying to build an assertation in is because it is very easy to forget and end up writing code like
Logger.Debug().Message("Debug message!");
which means that nothing gets logged, though at a cursory glance it looks like it should.
My Question
What I want to know is - can anyone think of another way of verifying that the final method is always called? These messages are just required during development to highlight to the developer that a method chain hasn't finished - I don't want the end users finding error messages related to logging in the end product.
First of all I would question the need for a fluent interface in this case at all, seems you can easily get by with a much simpler interface:
Logger.Debug.Message("Test");
or even just:
Logger.Debug("Test");
However, if you really need/want a fluent interface, a different way to do this would be to make the fluent interface work on a parameter to the method, instead of upon the return value.
So instead of doing this:
Method1().Method2().Method3();
and then forgetting the final call:
Method1().Method2().Method3().Execute();
you would instead organize the code, perhaps like this:
Method1(o => o.Method2().Method3());
To do this, you would define an object upon which you will call all the fluent methods:
public class LoggerOptions
{
public LoggerOptions Debug() { LoggerType = LoggerType.Debug; return this; }
public LoggerOptions Error() { LoggerType = LoggerType.Error; return this; }
public LoggerOptions Message(string message) { ...; return this; }
public LoggerType Type { get; set; }
...
}
Every method call here would modify the LoggerOptions object, and then return the same instance back, to continue the fluent interface.
and then:
public static class Logger
{
public static void Log(Func<LoggerOptions, LoggerOptions> options)
{
LoggerOptions opts = options(new LoggerOptions());
// do the logging, using properties/values from opts to guide you
}
}
You would then call it like this:
Logger.Log(opts => opts.Debug().Message("Debug message"));
If you have some terminal methods you absolutely need to call before finalizing setting up the options object, you can make different objects:
public class LoggerOptions
{
public LoggerOptions Debug() { LoggerType = LoggerType.Debug; return this; }
public LoggerOptions Error() { LoggerType = LoggerType.Error; return this; }
public LoggerOptions Message(string message) { ...; return this; }
public LoggerType Type { get; set; }
...
public LoggerFinalOptions ToEventLog() { ...; return new LoggerFinalOptions(this); }
public LoggerFinalOptions ToFile(string fileName) { ...; return new LoggerFinalOptions(this); }
}
and then:
public static class Logger
{
public static void Log(Func<LoggerOptions, LoggerFinalOptions> options)
{
LoggerFinalOptions opts = options(new LoggerOptions());
// do the logging, using properties/values from opts to guide you
}
}
This would then guarantee that you could not compile the code without ending the chain of methods with a call to something that returns the explicit final options object:
// will not compile
Logger.Log(opts => opts.Debug().Message("Test"));
// will compile
Logger.Log(opts => opts.Debug().Message("Test").ToFile("log.log"));

Collecting errors within a process and send them back to the caller - best approach?

I have a method in a class that performs several tasks (calling other methods, etc). The whole process can have along the way some errors or problems, but this doesn't mean that the process is aborted. I want that after the method finished, it returns to the caller a list of all of this problems so that he can decide what to do with them.
what's the best approach to implement this?
The first thing that comes to my mind is to make the method return a List of some kind of error class, but i may need to return something else with it, so that would be a problem. Also, throwing exceptions isn't good, because that would stop the flow, and i need to collect the errors along the way, not stop execution and go back to the caller.
I was also thinking of raising some kind of event that the caller listens to, but that would mean several events (for each error), and i just want that to happen once.
ideas?
My first idea is to create a class that would be an accumulator for these errors, e.g.
class ProcessingErrors
{
public void ReportError(...) { store the errror};
}
which you would pass in as a parameter:
MyResult DoProcessing(RealArgs a, ProcessingErrors e)
{
....
if(error) e.ReportError(...);
...
return result;
}
A few approaches
Your method will receive a delegate to an "error function" that will be called to report each error. The problem is that you need to pass this delegate around to all other methods.
Return a Tuple<RealResult, ErrorsList> so that the caller can examine both the result and the errors list.
If this is a repeated functionality and there are many methods that need to report errors - you can write a special class named, say, ErrorReportable and write LINQ operators that sequence objects of this type (if you know what a Monad is - then LINQ is just a simple monad and SelectMany is its "bind" operator). The code is cleaner but you need to do some work.
Create a delegate for errorcollecting along the way. Pass that to all classes in use, and let them report errors through this along the way. Let the calling class collect and handle the errors, or create a separate class for that. Something like below:
public delegate void ErrorCollector(string errorDescription);
public class MainControl
{
public void Execute()
{
new DoA(CollectErrors).DoStuff();
new DoB(CollectErrors).DoStuff();
//Display Errors encountered during processing in DoA and DoB
foreach (string s in _errorList)
{
Console.WriteLine(s);
}
}
public IList<string> ErrorList
{ get {return _errorList;} }
private void CollectErrors(string errorDescription)
{
_errorList.Add(errorDescription);
}
private readonly IList<string> _errorList = new List<string>();
}
public class DoA
{
private readonly ErrorCollector _errorCollector;
public DoA(ErrorCollector errorCollector)
{
_errorCollector = errorCollector;
}
public void DoStuff()
{
//Do something
//Perhaps error occurs:
_errorCollector("ERROR IN DoA!!!");
}
}
public class DoB
{
private readonly ErrorCollector _errorCollector;
public DoB(ErrorCollector errorCollector)
{
_errorCollector = errorCollector;
}
public void DoStuff()
{
//Do something
//Perhaps error occurs:
_errorCollector("ERROR IN DoB!!!");
}
}

Differences between test spy implementations

I am having some trouble defining which kind of test doubles these two classes are.
They both contain (basic) behaviour.
Their difference is that the first in a real context would not run, while the second would (it'd be basically a does-nothing class, but it'd work! The second would crash).
They both seem like Test Spies to me. They both provide a way to get whether the Run() method was called or not. (that is these classes' reason of being!).
I can't use the second one as it is in all the contexts, as I can't also use just the first one in all contexts.
I could refactor both of them into one, but maybe that'd turn things less clear when reading the code.
class FilterTestSpy : IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
hasBeenRan = true;
}
}
class FilterTestSpy2: IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
...some logic...
hasBeenRan = true;
}
}
I know there are mocking frameworks, blablabla, that is not what I am asking about here.
Thanks!
Could you create a strategy to delegate to in the Run() method? That way you will be able to have just one spy class, with a single responsibility, i.e, tell whether the method was called. So, for different contexts, you can inject different strategies.

Firing an event / function on a property? (C#)

I am using a class that I cannot edit, it has a property (a boolean) of which it would be nice to be informed when it changes, I can't edit the properties get or set as I am importing the class from a .dll (which I don't have the code for).
How do I create an event/function that is fired when the property is changed?
Additional
It is only changed within its own class, directly to the underlying private variable.
E.g.
private bool m_MyValue = false;
public bool MyValue
{
get { return m_MyValue; }
}
private void SomeFunction()
{
m_MyValue = true;
}
You can't, basically... not without using something like the debugger API to inject code at execution time and modifying the IL of the original library (and I'm not recommending either of those solutions; aside from anything else it may violate the licence of the library).
Basically if a property doesn't support notification, it doesn't support notification. You should look for a different way of approaching your problem. (Would polling work, for example?)
You cant do this directly [as Jon Skeet said], unless it's virtual, you're in a position to intercept all instance creations of the class and there are no changes to a backing field that influences the real 'value' of the propget.
The only way to brute force this is to use Mono.Cecil or MS CCI to instrument the prop setter a la this DimeCast on Cecil. (Or PostSharp)
However this wouldn't trap internal changes to the backing field (if there even is one). (Which is why wrapping probably wont work).
UPDATE: Given your update that you're definitely trying to trap the underlying field change, the only way to do that is to use PS / CCI / Cecil and analyse the flow to intercept all field updates. In short, not very feasible.
Arguably, the only real way to do this is to create some kind of "watcher" component, running in a separate thread, whose job is to read the property at intervals and raise an event when the property's value changes. Of course this solution sails in the murky waters of threading and synchronization.
On the assumption that your application is single-threaded in respect to this object, your cleanest solution is to make method calls to this object via a proxy object. It would have the job of checking the before and after state of the property and raising an event in the case it has changed.
Here's a simple example of what I'm talking about:
public class SomeProxy
{
public SomeProxy(ExternalObject obj)
{
_obj = obj;
}
public event EventArgs PropertyChanged;
private bool _lastValue;
private ExternalObject _obj;
protected virtual void OnPropertyChanged()
{
if(PropertyChanged != null)
PropertyChanged();
}
protected virtual void PreMethodCall()
{
_lastValue = _obj.SomeProperty;
}
protected virtual void PostMethodCall()
{
if(_lastValue != _obj.SomeProperty)
OnPropertyChanged();
}
// Proxy method.
public SomeMethod(int arg)
{
PreMethodCall();
_obj.SomeMethod(arg); // Call actual method.
PostMethodCall();
}
}
Obviously you can build this proxy pattern into a suitable object - you just have to be aware that all calls have to go through the proxy for the event to be raised when you expect it to be.
As previously mentioned, the most direct method (and that which requires the least change to code) is to use an AOP library such as PostSharp.
However, a solution can be achieved using traditional C#/.NET by using the dependency property pattern, used throughtout WPF to great effect. I suggest to read up on this, and consider implementing such a system (or at least a simplified version of it) for your project, if appropiate.
You will need to create a class that wraps the class in the dll, within the setter property just raise an event there using the normal methods.
Could you inherit from the class and hide the property? Something like this...
class MyClass : BaseClass
{
// hide base property.
public new bool MyProperty
{
get
{
return base.MyProperty;
}
set
{
base.MyProperty = value;
RaiseMyPropertyChangedEvent();
}
}
}
I think Alex' idea of a wrapper is good, however, given that the most important thing to you is that you know that the value is changed before use, you could simply move the notification to the getter, circumventing the worries of internal value change. That way you get something similar to polling, yet reliable:
class MyClass : BaseClass
{
//local value
private bool local;
//first access yet?
private bool accessed = false;
// Override base property.
public new bool MyProperty
{
get
{
if(!accessed)
{
// modify first-get case according to your taste, e.g.
local = base.MyProperty;
accessed = true;
RaiseMyPropertyChangedBeforeUseEvent();
}
else
{
if(local != base.MyProperty)
{
local = base.MyProperty;
RaiseMyPropertyChangedBeforeUseEvent();
}
}
return local;
}
set
{
base.MyProperty = value;
}
}
}
You can try to inherit it and use it's child instead of it.
Override the "set" of the property so it raises the event.
EDIT: ... only if property is virtual in the parent class ...

Categories