I am trying to develop some tests for a Windows 10 UWP application which uses Windows.Devices.Bluetooth.BluetoothLEDevice. I have a plain class that is part of my application which has a private BluetoothLEDevice type field.
class MyDevice
{
private Windows.Devices.Bluetooth.BluetoothLEDevice BluetoothLEDevice;
public string SomeProperty { get; set; }
public MyDevice(Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
{
BluetoothLEDevice = bluetoothLEDevice;
var characteristic = BluetoothLEDevice.GetGattService(...)
.GetCharacteristics(...)
.First();
characteristic.ValueChanged += OnValueChanged;
}
// TODO: Write tests for this method
private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());
// Parse `message`
SomeProperty = parsed;
}
...
}
The methods of said class use the events and methods of bluetoothLEDevice, some are private and others are public. How can I test the public methods of MyDevice?
I have tried something like this which I think could work, but I can see that it will take hundreds of lines of code and quite a few extra classes because I would need to implement a lot of stuff in FakeBluetoothLEDevice in orde for it to work properly.
I changed MyDevice to accept a wrapper instead and then create two implementations of the wrapper. One for testing, and the other for real use.
class MyDevice
{
private MyApp.IBluetoothLEDeviceWrapper bluetoothLEDevice;
}
Then in my test I use the fake.
private void ValueChangedEventDataParsingTest()
{
var device = new FakeBluetoothLEDevice();
var myDevice = new MyDevice(device);
device.InvokeValueChanged("this is the value for a fake ValueChangedEvent");
Assert.Equals(probe.SomeProperty, "expected");
}
Are there any frameworks (available for UWP) that would help me achieve what I want? Or even a better approach that would save me some pain?
In stead of focusing on implementation concerns focus on what functionality you want your abstraction to expose. Using your simplified example I was able to replicate it with some refactors to only interact with the desired functionality.
[TestClass]
public class DeviceTests {
[TestMethod]
public void _ValueChangedEventDataParsingTest() {
//Arrange
var message = "message";
var expected = "expected";
var device = new FakeBluetoothLEDevice(message, expected);
var sut = new MyDevice(device);
//Act
device.InvokeValueChanged(message);
//Assert
Assert.AreEqual(expected, sut.SomeProperty);
}
public interface IBlueToothService {
Action<string> ValueChangedHandler { get; set; }
}
public class FakeBluetoothLEDevice : IBlueToothService {
private string message;
private string parsed;
public FakeBluetoothLEDevice(string message, string expected) {
this.message = message;
this.parsed = expected;
}
public Action<string> ValueChangedHandler { get; set; }
public void InvokeValueChanged(string p) {
var handler = ValueChangedHandler ?? delegate { };
if (p == message) {
ValueChangedHandler(parsed);
}
}
}
public class MyDevice {
private IBlueToothService device;
public string SomeProperty { get; set; }
public MyDevice(IBlueToothService device) {
this.device = device;
device.ValueChangedHandler = handler;
}
private void handler(string parsedValue) {
SomeProperty = parsedValue;
}
}
}
Use separation of concerns and move the heavy lifting of implementation concerns behind the actual implementations. It vastly simplifies the consumers of such functionality.
If the concern is to test he parsing functionality then abstract the out into its own concern as well. Don't have classes doing more than they need to (SRP)
private OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) {
string message = Encoding.ASCII.GetString(args.CharacteristicValue.ToArray());
// Parse `message`
var parsed = parsingServce.Parse(message);
SomeProperty = parsed;
}
That way the parsing service implementation will only need to be tested for ts core functionality.
But from an abstraction perspective the parser is not needed as a dependency when testing higher level functionality.
I advise reviewing the current design and refactoring it to be more SOLID.
Related
I have doubts regarding my implementation of observer pattern, but with complete separation of concerns.
Example below is not a real life code, but just an example of idea how I want to do it.
In my solution I have two project layers:
Desktop layer (views, view models, models)
Service library layer (with observers)
My view model is a subject subscribing the observers.
Code in VM:
interface ISubject
{
void Subscribe(IObserverService observer);
void Unsubscribe(IObserverService observer);
void Notify();
}
public class MainWindowViewModel : ViewModelBase, ISubject
{
private readonly IObserverService _observer1;
private readonly IObserverService _observer2;
private ArrayList _observers;
public MainWindowViewModel(
IObserver1 observer1,
IObserver2 observer2)
{
_observer1 = observer1;
_observer2 = observer2;
ObserverCommand = new DelegateCommand(OnObserverCommand);
InitProgram();
}
private void InitProgram()
{
_observers = new ArrayList();
_observers.Add(_observer1);
_observers.Add(_observer2);
}
public List<IObserverService> Observers { get; set; }
private void OnSwitchCommand(object obj)
{
if (Jeden == true)
{
UiModel = _controlsService.SwitchOff();
}
else
{
UiModel = _controlsService.SwitchOn();
}
}
private void OnObserverCommand(object obj)
{
SomeValue++;
}
public void Subscribe(IObserverService observer)
{
Observers.Add(observer);
}
public void Unsubscribe(IObserverService observer)
{
Observers.Remove(observer);
}
public void Notify()
{
Observers.ForEach(x => x.Update(SomeValue));
}
public ICommand ObserverCommand { get; private set; }
private int _someValue;
public int SomeValue
{
get => _someValue;
set
{
_someValue = value;
InformObservers();
}
}
private void InformObservers()
{
foreach (IObserverService x in _observers)
{
x.Update(SomeValue);
}
}
}
And my observer in service layer is very simple. After Update call from the subject is displaying new MessageBox:
public interface IObserverService
{
void Update(int someValue);
}
public class Observer1 : IObserver1, IObserverService
{
public string ObserverName { get; private set; }
public Observer1(string name)
{
this.ObserverName = name;
}
public void Update(int someValue)
{
MessageBox.Show("New value: " + someValue.ToString() + " for " + ObserverName);
}
}
Observer2 is same as above.
Right now I have doubts how my constructor supposed to look like, if I want to create a new observer with a name parameter, for example: new Observer1("name1") in this case, keeping separation, should my subject's ctor look like:
public MainWindowViewModel()
{
_observerService = observerService;
IObserverService observer1 = new ObserverService("name1");
IObserverService observer2 = new ObserverService("name2");
SwitchCommnad = new DelegateCommand(OnSwitchCommand);
ObserverCommand = new DelegateCommand(OnObserverCommand);
InitProgram();
}
Is it correct approach? Is it going to be testable? Or I have to inject IObserverService somehow?
If you want to test your VM, follow IoC and don't create your ObserverServices inside it but as you say, inject IObserverService; therefore you'll be able to mock the services and test your VM without needing the whole service behavior.
I may suggest you to use Autofac or even Ninject. There are plenty of DI frameworks so look for the one that adjust to what you are looking for.
it makes sense, that MainWindowViewModel will receive some external observers via constructor:
public MainWindowViewModel(IObserver1 observer1, IObserver2 observer2)
{
_observer1 = observer1;
_observer2 = observer2;
ObserverCommand = new DelegateCommand(OnObserverCommand);
InitProgram();
}
when you create an instance of MainWindowViewModel (I assume, it will be used for MainWindowView DataContext), you will pass some real observers:
IObserverService observer1 = new ObserverService("name1");
IObserverService observer2 = new ObserverService("name2");
var vm = new MainWindowViewModel(observer1, observer2);
mainWindow.DataContext = vm;
no need for DI container here if dependencies can be resolved statically
similarly, for test you can have some TestObserverService (or IObserverService mock):
IObserverService observer1 = new TestObserverService("name1");
IObserverService observer2 = new TestObserverService("name2");
var vm = new MainWindowViewModel(observer1, observer2);
MainWindowViewModel might create some IObserverServices, if it has properties worth observing from other objects in the application (e.g. related view models)
I have a project where there is a mostly linear workflow. I'm attempting to use the .NET Stateless library to act as workflow engine/state machine. The number of examples out there is limited, but I've put together the following code:
private StateMachine<WorkflowStateType, WorkflowStateTrigger> stateMachine;
private StateMachine<WorkflowStateType, WorkflowStateTrigger>.TriggerWithParameters<Guid, DateTime> registrationTrigger;
private Patient patient;
public Patient RegisterPatient(DateTime dateOfBirth)
{
configureStateMachine(WorkflowState.Unregistered);
stateMachine.Fire<DateTime>(registrationTrigger, dateOfBirth);
logger.Info("State changed to: " + stateMachine.State);
return patient;
}
private void configureStateMachine(WorkflowState state)
{
stateMachine = new StateMachine<WorkflowState, WorkflowTrigger>(state);
registrationTrigger = stateMachine.SetTriggerParameters<DateTime>(WorkflowTrigger.Register);
stateMachine.Configure(WorkflowState.Unregistered)
.Permit(WorkflowTrigger.Register, WorkflowStateType.Registered);
stateMachine.Configure(WorkflowState.Registered)
.Permit(WorkflowTrigger.ScheduleSampling, WorkflowState.SamplingScheduled)
.OnEntryFrom(registrationTrigger, (dateOfBirth) => registerPatient(dateOfBirth));
}
private void registerPatient(DateTime dateOfBirth)
{
//Registration code
}
As you can see, I'm using the Stateless Fire() overload that allows me to pass in a trigger. This is so I can have the state machine process business logic, in this case, code to register a new patient.
This all works, but now I'd like to move all the state machine code into another class to encapsulate it and I'm having trouble doing this. The challenges I've had in doing this are:
instantiating a StateMachine object requires you to specify state and State is a readonly property that can only be set at instantiation.
my registrationTrigger has to be instantiated during state machine configuration and also has to be available by the calling class.
How can I overcome these items and encapsulate the state machine code?
There is an article by Scott Hanselman with an example and introduction to a library. Also there few examples available on their GitHub including Bug implementation example mentioned in Scott's article that encapsulates the state machine.
Below is an example of how the state can be extracted from behavior:
public class PatientRegistrationState
{
private StateMachine<WorkflowState, WorkflowTrigger> stateMachine;
private StateMachine<WorkflowState, WorkflowStateTrigger>.TriggerWithParameters<DateTime> registrationTrigger;
public PatientRegistrationState(State initialState = default(State)) {
stateMachine = new StateMachine<WorkflowState, WorkflowTrigger>(initialState);
stateMachine.Configure(WorkflowState.Unregistered)
.Permit(WorkflowTrigger.Register, WorkflowStateType.Registered);
stateMachine.Configure(WorkflowState.Registered)
.Permit(WorkflowTrigger.ScheduleSampling, WorkflowState.SamplingScheduled)
.OnEntryFrom(registrationTrigger, (date) => OnPatientRegistered(date));
}
public WorkflowState State => stateMachine.State;
public Action<DateTime> OnPatientRegistered {get; set;} = (date) => { };
// For state changes that do not require parameters.
public void ChangeTo(WorkflowTrigger trigger)
{
stateMachine.Fire<DateTime>(trigger);
}
// For state changes that require parameters.
public void ChangeToRegistered(DateTime dateOfBirth)
{
stateMachine.Fire<DateTime>(registrationTrigger, dateOfBirth);
}
// Change to other states that require parameters...
}
public class PatientRegistration
{
private PatientRegistrationState registrationState;
private Patient patient;
public PatientRegistration()
{
registrationState = PatientRegistrationState(WorkflowState.Unregistered)
{
OnPatientRegistered = RegisterPatient;
}
}
public Patient RegisterPatient(DateTime dateOfBirth)
{
registrationState.ChangeToRegistered(dateOfBirth);
logger.Info("State changed to: " + registrationState.State);
return patient;
}
private void RegisterPatient(DateTime dateOfBirth)
{
// Registration code
}
}
This is how I achieved it in my project.
Separated workflow logic to separate class. I had couple of workflows based on one of the flags present in the request object; below is one of the workflow classes:
public class NationalWorkflow : BaseWorkflow
{
public NationalWorkflow(SwiftRequest request) : this(request, Objects.RBDb)
{ }
public NationalWorkflow(SwiftRequest request, RBDbContext dbContext)
{
this.request = request;
this.dbContext = dbContext;
this.ConfigureWorkflow();
}
protected override void ConfigureWorkflow()
{
workflow = new StateMachine<SwiftRequestStatus, SwiftRequestTriggers>(
() => request.SwiftRequestStatus, state => request.SwiftRequestStatus = state);
workflow.OnTransitioned(Transitioned);
workflow.Configure(SwiftRequestStatus.New)
.OnEntry(NotifyRequestCreation)
.Permit(SwiftRequestTriggers.ProcessRequest, SwiftRequestStatus.InProgress);
workflow.Configure(SwiftRequestStatus.InProgress)
.OnEntry(ValidateRequestEligibility)
.Permit(SwiftRequestTriggers.AutoApprove, SwiftRequestStatus.Approved)
.Permit(SwiftRequestTriggers.AdvancedServicesReview, SwiftRequestStatus.PendingAdvancedServices);
.....................
}
Which is triggered from the controller/any other layer:
private static void UpdateRequest(SwiftRequestDTO dtoRequest)
{
var workflow = WorkflowFactory.Get(request);
workflow.UpdateRequest();
}
As mentioned above, I had different workflow rules based on conditions in the request object and hence used a factory pattern WorkflowFactory.Get(request); you may create an instance of your workflow/inject it as desired
And inside the workflow class (BaseWorkflow class in my case), I have exposed the actions:
public void UpdateRequest()
{
using (var trans = this.dbContext.Database.BeginTransaction())
{
this.actionComments = "Updating the request";
this.TryFire(SwiftRequestTriggers.Update);
SaveChanges();
trans.Commit();
}
}
protected void TryFire(SwiftRequestTriggers trigger)
{
if (!workflow.CanFire(trigger))
{
throw new Exception("Cannot fire " + trigger.ToString() + " from state- " + workflow.State);
}
workflow.Fire(trigger);
}
In brief: I want resolve interface by prop in entity.
I have self hosted wcf and use ninject for DI.
My working code for example:
//program.cs
...
private static StandardKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<IDbConnectionFactory>().ToMethod(c =>
new OrmLiteConnectionFactory(
conString,
SqlServerDialect.Provider))
.InSingletonScope();
kernel.Bind<IControllerProccessor>().To<ControllerProccessor>()
.WhenInjectedInto<HelloWorldService>().WithConstructorArgument(kernel);
kernel.Bind<IControllerProccessor>().To<Vendor1Proccessor>()
.Named("vendor1");
kernel.Bind<IControllerProccessor>().To<Vendor2Proccessor>()
.Named("vendor2");
return kernel;
}
...
//IControllerProccessor.cs
public interface IControllerProccessor
{
SimpleController Ctr { get; set; }
bool sendMsg(string msg);
}
//Vendor1Proccessor.cs
public class Vendor1Proccessor : IControllerProccessor
{
public SimpleController Ctr {get; set;}
public bool sendMsg(string msg)
{
//specific to vendor code, for example calls to vendor1 SDK
Console.WriteLine("Controller id: {0} vendor:{1} recivied msg: {2}",
Ctr.Id,
"Vendor1Class",
msg);
return true;
}
}
//Vendor2Proccessor.cs
public class Vendor2Proccessor : IControllerProccessor
{
public SimpleController Ctr { get; set; }
public bool sendMsg(string msg)
{
//specific to vendor code, for example calls to vendor1 SDK
Console.WriteLine("Controller id: {0} vendor:{1} recivied msg: {2}",
Ctr.Id,
"Vendor2Class",
msg);
return true;
}
}
//ControllerProccessor.cs
public class ControllerProccessor : IControllerProccessor
{
public SimpleController Ctr {get; set;}
private readonly IKernel kernel;
public ControllerProccessor(IKernel _kernel)
{
kernel = _kernel;
}
public bool sendMsg(string msg)
{
var param = new Ninject.Parameters.PropertyValue("Ctr", Ctr);
return kernel.Get<IControllerProccessor>(Ctr.Vendor, param).sendMsg(msg);
}
}
//HelloWorldService.cs
public class HelloWorldService : IHelloWorldService
{
private readonly IDbConnectionFactory dbFactory;
private readonly IControllerProccessor ctrProccessor;
public HelloWorldService(IDbConnectionFactory _dbFactory, IControllerProccessor _ctrProccesor)
{
dbFactory = _dbFactory;
ctrProccessor = _ctrProccesor;
}
public bool sendMsgToAllControllers(string msg)
{
var db = dbFactory.Open();
var controllers = db.Select<SimpleController>();
foreach(var ctr in controllers)
{
ctrProccessor.Ctr = ctr;
ctrProccessor.sendMsg(msg);
}
db.Close();
return true;
}
}
//SimpleController.cs
[DataContract]
[Alias("SimpleController")]
public class SimpleController
{
[AutoIncrement]
[DataMember]
public int? Id { get; set; }
[DataMember]
public string Vendor { get; set; }
}
When I call sendMsgToAllControllers("TEST_MESSAGE") console output:
Controller id: 2 vendor:Vendor1Class recivied msg: TEST MESSAGE
Controller id: 3 vendor:Vendor2Class recivied msg: TEST MESSAGE
Controller id: 4 vendor:Vendor2Class recivied msg: TEST MESSAGE
How I can refactor above implementation so that it was in DI style, and dont use IoC locator anti-pattern (or in my case this is not anti-pattern) ?
In future I will move implementations (vendor1, vendor2, etc..) in separate assembly and do runtime binding. (Here I want to plugin system)
I also would appreciate any suggestions to improve my code. Very thanks.
Modification of implementation
After thinking process I came to the following:
I remove ControllerProccessor class instead I create ControllerProcessorFactory:
public class ControllerProcessorFactory : IControllerProcessorFactory
{
private readonly IResolutionRoot resolutionRoot;
public ControllerProcessorFactory(IResolutionRoot _resolutionRoot)
{
resolutionRoot = _resolutionRoot;
}
public IControllerProcessor Create(SimpleController ctr)
{
IControllerProcessor processor = resolutionRoot.Get<IControllerProcessor>(ctr.Vendor);
processor.Ctr = ctr;
return processor;
}
}
In Bindings:
kernel.Bind<IControllerProcessorFactory>().To<ControllerProcessorFactory>();
kernel.Bind<IControllerProcessor>().To<Vendor1Processor>()
.Named("vendor1");
kernel.Bind<IControllerProcessor>().To<Vendor2Processor>()
.Named("vendor2");
Usage (wcf class):
public class HelloWorldService : IHelloWorldService
{
private readonly IDbConnectionFactory dbFactory;
private readonly IControllerProcessorFactory ctrProcessorFactory;
public HelloWorldService(IDbConnectionFactory _dbFactory, IControllerProcessorFactory _ctrProcFactory)
{
dbFactory = _dbFactory;
ctrProcessorFactory = _ctrProcFactory;
}
public bool sendMsgToAllControllers(string msg)
{
var db = dbFactory.Open();
var controllers = db.Select<SimpleController>();
foreach(var ctr in controllers)
{
var ctrProcessor = ctrProcessorFactory.Create(ctr);
ctrProcessor.sendMsg(msg);
}
db.Close();
return true;
}
}
kernel.Get<IControllerProccessor>(Ctr.Vendor, param) is service locator,
but then again that doesn't always mean "it" is a problem. If it's easily interchangable, then it's not a big deal (well at least that's the opinion of some). Easily interchangeable? Create a specific factory interface whose only responsibility is to return all the processors.
The implementation then would consist of exactly return kernel.Get<IControllerProccessor>(Ctr.Vendor, param);. As long as the implementation is part of the composition root this specfici dependency on ninject is ok.
Shorter Alternative
Now, to be honest, your design looks superfluosly complicated to me, but then again, i don't know all the details. So for now i'm just using the name parameter, but you can easily add parameters (almost) as you like, it'll still work:
Just inject a Func<string, IControllerProcessor> instead of the kernel:
public ControllerProccessor(
Func<string,IControllerProcessor>> controllerProcessorFactory)
You can then specfiy a binding as follows:
private static IControllerProcessor CreateSpecificControllerProcessor(
IResolutionRoot resolutionRoot, string vendorName)
{
return resolutionRoot.Get<IControllerProcessor>(vendorName);
}
Bind<Func<IControllerProcessor>()
.ToConstant(vendorName => CreateSpecficiControllerProcessor(this.Kernel, vendorName));
Instead of specifying the Binding for the Func it might be possible to use Ninject.Extensions.Factory. Note however, that when you use this extension it won't be possible to Bind any Func manually anymore (the binding will be overriden by the extensions generation mechanism).
Look at Dynamic module loading in their documentation.
i.e.
kernel.Load("*.dll");
But make sure you do this at startup so you don't overwhelm your system at runtime.
As far as your pattern, I would recommend using the GetAll() method on the kernel as that will give you more flexibility and control
IEnumerable<IControllerProccessor> processors = kernel.GetAll<IControllerProccessor>();
foreach(var processor in processors)
processor.sendMsg(....);
I'm just wondering if there's an automated way to generate constructors with every possible combination of the parameters you might need.
I have a ctor with 4 parameters, but I want to provide overloads where a developer could pass in a single param, or two or three. By hand I've been writing every possible combination and passing defaults to the 4 parameter one. I also need to then introduce two more "full" prototypes ( with a fifth ), then create all the possible combinations for those as well, so I need loads of ctor overloads to cover all combinations.
I'd like to manually write the three full ctors, then be able to generate the combinations with a context menu click. I haven't seen an option like this in Resharper. Anyone know if there's an existing solution out there already?
If you need a lot of constructor parameters, rather than struggling with the explosion of possible permutations, consider creating an "options" class that has sensible defaults:
public class FooOptions
{
public FooOptions()
{
MaintenanceInterval = TimeSpan.FromSeconds(30);
MaximumIdleTime = TimeSpan.FromMinutes(5);
}
public TimeSpan MaintenanceInterval { get; set; }
public TimeSpan MaximumIdleTime { get; set; }
//etc...
}
then
class Foo
{
public Foo():this(new FooOptions())
{
}
public Foo(FooOptions opts)
{
//...
}
}
This situation would be a perfect fit for the Builder pattern.
For example, if the class Foo can have any combination of a String, an int and a Bar:
public class Foo
{
public string MyString { get; set; }
public int MyInt { get; set; }
public Bar MyBar { get; set; }
}
Instead of adding a constructor with every possibility, make a Builder. Here's an example of a simple fluent implementation:
public class FooBuilder
{
private Foo foo = new Foo();
public FooBuilder WithString(String someString)
{
foo.MyString = someString;
return this;
}
public FooBuilder WithInt(int someInt)
{
foo.MyInt = someInt;
return this;
}
public FooBuilder WithBar(Bar someBar)
{
foo.MyBar = someBar;
return this;
}
public Foo Build()
{
return foo;
}
}
which can be used like this:
Foo foo = new FooBuilder().WithString("abc").WithInt(3).Build();
This eliminates completely the need for an exponential number of constructors.
Don't need multiple constructor overloads - try using optional/default parameters. Relevant link: https://msdn.microsoft.com/en-us/library/dd264739.aspx
Example code:
class Program
{
static void Main(string[] args)
{
var defaultMonster = new Monster();
var archerMonster = new Monster("crossbow");
var knightMonster = new Monster("broadsword", "plate mail");
var wizardMonster = new Monster(armor: "wizard robe", magicItem: "wand");
Console.WriteLine(defaultMonster);
Console.WriteLine(archerMonster);
Console.WriteLine(knightMonster);
Console.WriteLine(wizardMonster);
}
}
class Monster
{
private readonly string _weapon;
private readonly string _armor;
private readonly string _magicItem;
public Monster(string weapon = "scimitar", string armor = "leather", string magicItem = "nothing")
{
_weapon = weapon;
_armor = armor;
_magicItem = magicItem;
}
public override string ToString()
{
return string.Format("Monster armed with {0}, wearing {1}, carrying {2}", _weapon, _armor, _magicItem);
}
}
I have a class in which I have to repeat multiple steps to complete a process like below, this is just a pseudo code to demonstrate what I am asking. Basically each method needs another method to do something, so a few methods are executed one after another to get the desired result, but somehow I don't like this, is there another way to achieve this may be using a design pattern? I have seen the chain of responsibility but that does not suit me as I don't have different type of processors.
Thanks
class Processor
{
void Process()
{
var credentials = GetCredentialsFromDb();
var result = ProcessData(credentials);
}
string GetCredentialsFromDb()
{
return "user";
}
string ProcessData(string credentials)
{
return ExtractData();
}
string ExtractData()
{
return ParseData();
}
string ParseData()
{
return ValidateData(data);
}
string ValidateData(string data)
{
return "validatedData";
}
}
As each of your method calls wraps around the subsequent one, I'd say that the decorator pattern could fit your needs.
This would allow you to specify how the stack is build by only accepting certain types to be wrapped in others, if this is important.
You probably want a Builder Pattern - http://en.wikipedia.org/wiki/Builder_pattern
Basically the builder initializes your object and contains all of the logic, each in separate methods taking arguments for what information they need, for "building up" the end result.
Then you would implement a director that always calls them in sequence.
public static void main() {
var builder = new ProcessorBuilder();
ProcessorDirector director = new ProcessorDirector();
director.Build();
Console.WriteLine(builder.Processor);
}
class ProcessorDirector { //I tell processor builders how to build processors!
ProcessorBuilder _builder {get;private set;}
public ProcessorDirector(ProcessorBuilder builder) {
_builder = builder;
}
public void Build() {
var credentials = _builder.GetCredentialsFromDB();
var data = _builder.ProcessData(credentials);
var isDataValid = _builder.ValidateData();
if(isDataValid) {
_builder.ParseData();
}
}
}
class ProcessorBuilder
{
public string Processor {get;set;}
void ProcessorBuilder()
{
//if you change your end result object into a non-value type, you'd initialize it here.
}
public string GetCredentialsFromDb()
{
return "user";
}
string ProcessData(string credentials)
{
//process
//builder should be stateless, so return data
}
public string ParseData()
{
//parse
}
public string ValidateData()
{
//validate
}
}