Help naming a class that has a single public method called Execute() - c#

I have designed the following class that should work kind of like a method (usually the user will just run Execute()):
public abstract class ??? {
protected bool hasFailed = false;
protected bool hasRun = false;
public bool HasFailed { get { return hasFailed; } }
public bool HasRun { get { return hasRun; } }
private void Restart() {
hasFailed = false;
hasRun = false;
}
public bool Execute() {
ExecuteImplementation();
bool returnValue = hasFailed;
Restart();
return returnValue;
}
protected abstract void ExecuteImplementation();
}
My question is: how should I name this class? Runnable? Method(sounds awkward)?

Naming a class is all about a good design. You have to know which use cases this class will be part of, which responsibility it will take and what collaborations will this class take part in. Naming class without context can only do harm. Naming class after a pattern just because the pattern uses similar names is even worse, because it might confuse any reader who knows something about patterns, whcih is exactly opposite of what patterns try to achieve - name common decisions/solutions/designs/etc... Your class can be Runnable, Executable, Method, Procedure, Job, Worker, RestartableExecutor, Command, Block, Closure, Functor and virtually pretty much anything without further information.

Possibilities:
action
command
worker
method
I like action, personally.

I guess a good question to ask yourself would be what you are executing. Then you might get an idea of what to name it.
For example, if you are executing a file and folder scan, you could name the class FileAndFolderScan.
FileAndFolderScan.Execute();

It sure looks like a Task to me.

Usually the Command pattern uses classes with an Execute() method. Is that more or less what you're trying to accomplish? I guess it's close enough for me; I would call it a Command or Worker or something similar.
Do you know about BackgroundWorker?

The .NET Framework already has a class that does this (several, actually). They're called delegates.
If it's really doing a lot more than just executing a method - performing error handling or that sort of thing - then name it for what it actually does, not how it's implemented.
If you absolutely have to implement a totally generic and abstract class that does nothing but encapsulate an arbitrary method and some sort of success/failure status (why?), then... task, worker, command, instruction, request, activity, etc... pick any of the above, they all mean pretty much the same thing in this context.

At my work we were stuck on .NET 2.0 for a while (pre-Action and Func delegates) and I had been using a bunch of overloaded generic delegates with the same signatures called Runner and Returner. Seems to me you could go with Runner and have a pretty clear self-describing class.
Alternately, why not just go with something like Executable or Executor?

Task
Client code should look good with this.
//create instance of Task implementation
Task myTask = TaskFactory.CreateTask();
//Execute the task
myTask.Execute()

You could call it an Executioner. :)

Quick Answer:
You already have several suggestions like "Task", "Process", "Job", even "Command".
Complementary comments:
Any object has a life cycle, a "start" operation, usually the constructor, a "finish" operation, usually a "Dispose" or destructor, and unleast a single main operation like your "Execute()", but there can be more.
In you code, the constructor or destructor are internally managed by your compiler, but sometimes do some other stuff like open and closing files.
You may want to learn more about the Command Design pattern, as mention by previous answers, it seems to fit your case.

Related

Static Initializing pattern

What is the best way to initialize static fields via a static init method and afterwards make sure that the method is never called again? (no more than once during the lifetime of the program)
This is an example of what I currently thought of, it seems pretty simple to me but I couldn't find any examples of similar patterns that deal with this:
class Entity
{
static Manager manager;
static bool isInitialized;
public static void Initialize(Manager manager)
{
if (isInitialized)
throw Exception("Class Entity already initialized."
+ "Do not call Entity.Initialize() twice.");
isInitialized = true;
Entity.manager = manager;
}
}
What is the best way to initialize static fields via a static init method and afterwards make sure that the method is never called again?
Do you really have to do this? Why do you not want to create an instance of Manager and make it available to code which relies on it through dependency injection? That would make your code much cleaner:
You'd allow it to be testable with different initialization paths
You wouldn't need any checking for "bad" duplicate initialization
You wouldn't need to structure your calling code to specify a single initialization point for this class. (You may need to do something similar for the IoC container of course...)
You'd allow your code which depends on it to be more testable too
The code which depends on Manager would be express that dependency in a clearer way
I suspect you haven't found any similar examples because it's an anti-pattern.
If you do go for your current approach, you should really try to make it thread-safe, too...
Don't over think it, if that pattern works for you, go with it. There isn't always a "right" answer, and trying to stick to rigid patterns and practices just for the sake of sticking to them is not a good idea either. IMHO.
Sorry for stating the obvious, but you could use the object initializer or the static constructor. Besides that, you can just not call the method. Seriously. Why would someone call a method called initialize anyway.
What you could do is this. You can hide the method from IntelliSense and similar with this attribute. Stops it from cluttering up the dropdown too
Your implementation is not thread-safe, but is otherwise reasonable. If it's intended for use in a multithreaded environment, add locking.
In your sample, the open question is what should happen if multiple callers (possibly from multiple threads) call the initialization method with different parameters. This is what makes your pattern unusual, and prevents you from using the obvious static constructor or object initializer.
Can't you just use a static constructor?
Of course, you do not have control over when this constructor is called, but don't know if this is a requirement.
http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx
You might want to use a singleton pattern with parameters to only expose certain functionality of the Manager variable.
class Entity
{
private Manager _manager = null;
public Manager manager
{
get
{
return _manager;
}
set
{
if (manager == null)
{
_manager = value;
}
}
}
/* rest of class */
}
Now you can use the manager object as any variable, but repeated sets will not modify the value.
this.manager = new Manager(0); // sets the manager
this.manager = new Manager(1); // does nothing
Now to complete the pattern in your constructor somewhere or at some reset function you might want to do a
this._manager = null;

C#: using type of "self" as generic parameter?

This may seem a bit odd, but I really need to create a workaround for the very complicated duplex - communication - handling in C#, especially to force other developers to observe the DRY - principle.
So what I'm doing is to have a type based multiton that looks like this:
internal sealed class SessionManager<T> where T : DuplexServiceBase
which is no problem at all - so far.
However, as soon as I want to have the services (I'm going with one instance per session) register themselves with the SessionManager, the hassle starts:
internal abstract class DuplexServiceBase : MessageDispatcherBase<Action>
(MessageDispatcherBase being a class of mine that creates a thread and asynchronously sends messages).
I want to have a method that looks like this:
protected void ProcessInboundMessage()
{
// Connect
SessionManager<self>.Current.Connect(this);
}
...but the problem is - how would I get to the "self"?
I really NEED separate session managers for each service class, because they all have their own notifications (basically it's the very annoying "NotifyAllClients" - method that makes we want to pull my own hair out for the last hours) and need to be treated separately.
Do you have ANY ideas?
I don't want to use "AsyncPattern = true", btw... this would require me to give up type safety, enforced contract compliance (this would lead to very bad abuse of the communication system I'm setting up here) and would require abandoning the DRY - principle, there would be a lot of repetitive code all over the place, and this is something I seriously frown upon.
Edit:
I have found the best possible solution, thanks to the answers here - it's an EXTENSION METHOD, hehe...
public static SessionManager<T> GetSessionManager<T>(this T sessionObject)
where T : DuplexServiceBase
{
return SessionManager<T>.Current;
}
I can use this like this:
GetSessionManager().Connect(this);
Mission accomplished. :-D
This method (belongs to DuplexServiceBase) gives me the session manager I want to work with. Perfect! :-)
I'd write a helper method:
static class SessionManager { // non-generic!
static void Connect<T>(T item) where T : DuplexServiceBase {
SessionManager<T>.Current.Connect(item);
}
}
and use SessionManager.Connect(this) which will figure it out automatically via generic type inference.
You could wrap the call in a generic method, thereby taking advantage of the compiler's type inference:
private static void ConnectSessionManager<T>(T service)
{
SessionManager<T>.Current.Connect(service)
}
protected void ProcessInboundMessage()
{
// Connect
ConnectSessionManager(this);
}

What design pattern will you choose?

I want to design a class, which contains a procedure to achieve a goal.
And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly.
in such a case, what design patter will you use ?
which can make sure that the user must call the public method according some ordering.
If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?
I believe you are looking for the Template Method pattern.
Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.
http://en.wikipedia.org/wiki/Template_method_pattern
or as in this code sample:
abstract class AbstractParent // this is the template class
{
// this is the template method that enforces an order of method execution
final void executeIt()
{
doBefore(); // << to be implemented by subclasses
doInTheMiddle() // also to be implemented by subclasses
doLast(); // << the one you want to make sure gets executed last
}
abstract void doBefore();
abstract void doInTheMiddle();
final void doLast(){ .... }
}
class SubA extends AbstractParent
{
void doBefore(){ ... does something ...}
void doInTheMiddle(){ ... does something ...}
}
class SubB extends SubA
{
void doBefore(){ ... does something different ...}
}
But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.
Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.
Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.
Don't use them as cookie cutters. That is the last thing you want to do.
Its basically not a pattern, but: If you want to make sure, the code/methods are executes in a specific order, make the class having only one public method, which then calls the non-public methods in the right sequence.
The simple and pragmatic approach to enforcing a particular sequence of steps in any API is to define a collection of classes (instead of just one class) in such way that every next valid step takes as a parameter an object derived from the previous step, i.e.:
Fuel coal = CoalMine.getCoal();
Cooker stove = new Cooker (gas);
Filling apple = new AppleFilling();
Pie applePie = new Pie(apple);
applePie.bake(stove);
That is to say that to bake a pie you need to supply a Cooker object that in turn requires some sort of a suitable fuel to be instantiated first. Similarly, before you can get an instanse of a Pie you'd need to get some Filling ready.
In this instance the semantics of the API use are explicitly enforced by its syntax. Keep it simple.
I think you have not to really execute nothing, just prepare the statements, resources and whatever you want.
This way whatever would be the order the user invokes the methods the actual execution would be assured to be ordered; simply because you have the total control over the real execution, just before execute it.
IMHO Template Method as very little to do with your goal.
EDIT:
to be more clear. Make your class to have one public method Execute, and a number of other public methods to tell your class what to do (when to do it is a responsibility of you and not of the user); then make a number of private methods doing the real job, they will be invoked in the right order by your Execute, once the user has finished settings things.
Give the user the ability of setting, keep execution for your self. He tells what, you decide how.
Template Method is rational, if you have a class hierarchy and base class defines protected operation steps in its public template method. Could you elaborate your question?
As general concept you should choose a pattern as a standard solution to a standard problem so, I agree with Oded, the "Template Method" seems to fit your needs (but what you explained is too few maybe).
Don´t use pattern as "fetish", what you have to keep in mind is:
How can I figure my problem in a standard way?
There is a pattern for this?
Is this the simplest way?

thoughts on configuration through delegates

i'm working on a fork of the Divan CouchDB library, and ran into a need to set some configuration parameters on the httpwebrequest that's used behind the scenes. At first i started threading the parameters through all the layers of constructors and method calls involved, but then decided - why not pass in a configuration delegate?
so in a more generic scenario,
given :
class Foo {
private parm1, parm2, ... , parmN
public Foo(parm1, parm2, ... , parmN) {
this.parm1 = parm1;
this.parm2 = parm2;
...
this.parmN = parmN;
}
public Bar DoWork() {
var r = new externallyKnownResource();
r.parm1 = parm1;
r.parm2 = parm2;
...
r.parmN = parmN;
r.doStuff();
}
}
do:
class Foo {
private Action<externallyKnownResource> configurator;
public Foo(Action<externallyKnownResource> configurator) {
this.configurator = configurator;
}
public Bar DoWork() {
var r = new externallyKnownResource();
configurator(r);
r.doStuff();
}
}
the latter seems a lot cleaner to me, but it does expose to the outside world that class Foo uses externallyKnownResource
thoughts?
This can lead to cleaner looking code, but has a huge disadvantage.
If you use a delegate for your configuration, you lose a lot of control over how the objects get configured. The problem is that the delegate can do anything - you can't control what happens here. You're letting a third party run arbitrary code inside of your constructors, and trusting them to do the "right thing." This usually means you end up having to write a lot of code to make sure that everything was setup properly by the delegate, or you can wind up with very brittle, easy to break classes.
It becomes much more difficult to verify that the delegate properly sets up each requirement, especially as you go deeper into the tree. Usually, the verification code ends up much messier than the original code would have been, passing parameters through the hierarchy.
I may be missing something here, but it seems like a big disadvantage to create the externallyKnownResource object down in DoWork(). This precludes easy substitution of an alternate implementation.
Why not:
public Bar DoWork( IExternallyKnownResource r ) { ... }
IMO, you're best off accepting a configuration object as a single parameter to your Foo constructor, rather than a dozen (or so) separate parameters.
Edit:
there's no one-size-fits-all solution, no. but the question is fairly simple. i'm writing something that consumes an externally known entity (httpwebrequest) that's already self-validating and has a ton of potentially necessary parameters. my options, really, are to re-create almost all of the configuration parameters this has, and shuttle them in every time, or put the onus on the consumer to configure it as they see fit. – kolosy
The problem with your request is that in general it is poor class design to make the user of the class configure an external resource, even if it's a well-known or commonly used resource. It is better class design to have your class hide all of that from the user of your class. That means more work in your class, yes, passing configuration information to your external resource, but that's the point of having a separate class. Otherwise why not just have the caller of your class do all the work on your external resource? Why bother with a separate class in the first place?
Now, if this is an internal class doing some simple utility work for another class that you will always control, then you're fine. But don't expose this type of paradigm publicly.

Is it a code smell for one method to depend on another?

I am refactoring a class so that the code is testable (using NUnit and RhinoMocks as testing and isolations frameworks) and have found that I have found myself with a method is dependent on another (i.e. it depends on something which is created by that other method). Something like the following:
public class Impersonator
{
private ImpersonationContext _context;
public void Impersonate()
{
...
_context = GetContext();
...
}
public void UndoImpersonation()
{
if (_context != null)
_someDepend.Undo();
}
}
Which means that to test UndoImpersonation, I need to set it up by calling Impersonate (Impersonate already has several unit tests to verify its behaviour). This smells bad to me but in some sense it makes sense from the point of view of the code that calls into this class:
public void ExerciseClassToTest(Impersonator c)
{
try
{
if (NeedImpersonation())
{
c.Impersonate();
}
...
}
finally
{
c.UndoImpersonation();
}
}
I wouldn't have worked this out if I didn't try to write a unit test for UndoImpersonation and found myself having to set up the test by calling the other public method. So, is this a bad smell and if so how can I work around it?
Code smell has got to be one of the most vague terms I have ever encountered in the programming world. For a group of people that pride themselves on engineering principles, it ranks right up there in terms of unmeasurable rubbish, and about as useless a measure, as LOCs per day for programmer efficiency.
Anyway, that's my rant, thanks for listening :-)
To answer your specific question, I don't believe this is a problem. If you test something that has pre-conditions, you need to ensure the pre-conditions have been set up first for the given test case.
One of the tests should be what happens when you call it without first setting up the pre-conditions - it should either fail gracefully or set up it's own pre-condition if the caller hasn't bothered to do so.
Well, there is a bit too little context to tell, it looks like _someDepend should be initalized in the constructor.
Initializing fields in an instance method is a big NO for me. A class should be fully usable (i.e. all methods work) as soon as it is constructed; so the constructor(s) should initialize all instance variables. See e.g. the page on single step construction in Ward Cunningham's wiki.
The reason initializing fields in an instance method is bad is mainly that it imposes an implicit ordering on how you can call methods. In your case, TheMethodIWantToTest will do different things depending on whether DoStuff was called first. This is generally not something a user of your class would expect, so it's bad :-(.
That said, sometimes this kind of coupling may be unavoidable (e.g. if one method acquires a resource such as a file handle, and another method is needed to release it). But even that should be handled within one method if possible.
What applies to your case is hard to tell without more context.
Provided you don't consider mutable objects a code smell by themselves, having to put an object into the state needed for a test is simply part of the set-up for that test.
This is often unavoidable, for instance when working with remote connections - you have to call Open() before you can call Close(), and you don't want Open() to automatically happen in the constructor.
However you want to be very careful when doing this that the pattern is something readily understood - for instance I think most users accept this kind of behaviour for anything transactional, but might be surprised when they encounter DoStuff() and TheMethodIWantToTest() (whatever they're really called).
It's normally best practice to have a property that represents the current state - again look at remote or DB connections for an example of a consistently understood design.
The big no-no is for this to ever happen for properties. Properties should never care what order they are called in. If you have a simple value that does depend on the order of methods then it should be a parameterless method instead of a property-get.
Yes, I think there is a code smell in this case. Not because of dependencies between methods, but because of the vague identity of the object. Rather than having an Impersonator which can be in different persona states, why not have an immutable Persona?
If you need a different Persona, just create a new one rather than changing the state of an existing object. If you need to do some cleanup afterwards, make Persona disposable. You can keep the Impersonator class as a factory:
using (var persona = impersonator.createPersona(...))
{
// do something with the persona
}
To answer the title: having methods call each other (chaining) is unavoidable in object oriented programming, so in my view there is nothing wrong with testing a method that calls another. A unit test can be a class after all, it's a "unit" you're testing.
The level of chaining depends on the design of your object - you can either fork or cascade.
Forking:
classToTest1.SomeDependency.DoSomething()
Cascading:
classToTest1.DoSomething() (which internally would call SomeDependency.DoSomething)
But as others have mentioned, definitely keep your state initialisation in the constructor which from what I can tell, will probably solve your issue.

Categories

Resources