Testable design with COM objects - unit-testing

What is a good way to design for testing and extensibility when a component used to complete a task could either be a COM component or a .NET component? Does it make sense to wrap the COM component completely and extract an interface? Here is a simple, completely contrived, RCW interface on a COM component, where "abc" is the acronym for the component maker:
public interface IComRobot
{
void abcInitialize(object o);
void abcSet(string s, object o);
void abcBuild();
void abcExit();
}
To me, the fact that the provider of the component chose to prefix all methods with something indicating their company is somewhat irritating. The problem is, I want to define other Robot components that perform the same actions, but the underlying implementation is different. It would be completely confusing to Robot builders to have to implement "abcAnything".
How should I go about building a RobotFactory with a simple implementation that works like this?
public class RobotFactory
{
public static IRobot Create(int i)
{
// // problem because ComRobot implements IComRobot not IRobot
if (i == 0) return new ComRobot();
if (i == 1) return new AdvancedRobot();
return new SimpleRobot();
}
}
Should I bite the bullet and accept the abc prefix in my interface, thus confusing robot implementers? Should I force a dependency on the Robot consumer to know when they are using the COM robot? None of these seem ideal. I'm thinking about an additional level of abstraction (that can solve everything, right?). Something like so:
public interface IRobot : IDisposable
{
void Initialize(object o);
void Set(string s, object o);
void Build();
void Exit();
}
public class ComRobotWrapper: IRobot
{
private readonly IComRobot m_comRobot;
public ComRobotWrapper()
{
m_comRobot = ComRobotFactory.Create();
}
public void Initialize(object o)
{
m_comRobot.abcInitialize(o);
}
public void Set(string s, object o)
{
m_comRobot.abcSet(s, o);
}
public void Build()
{
m_comRobot.abcBuild();
}
public void Exit()
{
m_comRobot.abcExit();
}
public void Dispose()
{
//...RELEASE COM COMPONENT
}
}
public class ComRobotFactory
{
public static IComRobot Create()
{
return new ComRobot();
}
}
I would then alter and use the RobotFactory like so:
public class RobotFactory
{
public static IRobot Create(int i)
{
if (i == 0) return new ComRobotWrapper();
if (i == 1) return new AdvancedRobot();
return new SimpleRobot();
}
}
public class Tester
{
// local vars loaded somehow
public void Test()
{
using (IRobot robot = RobotFactory.Create(0))
{
robot.Initialize(m_configuration);
robot.Set(m_model, m_spec);
robot.Build();
robot.Exit();
}
}
}
I'm interested in opinions on this approach. Do you recommend another approach? I really don't want to take on a DI framework, so that is out of scope. Are the pitfalls in testability? I appreciate you taking the time to consider this lengthy issue.

That looks spot on to me. You are creating an interface that is right for your domain / application, and implementing it in terms of a thrid party component.

Related

references are a pain for my mocks in TDD

I am new with c++/tdd, embraced gtest/gmock, and fell in love.
One thing kind of puzzles me though. Are reference pointers really the way to go?
I find myself producing a lot of boiler plate injecting all mocks (even when I don't have any business mocking that behavior).
Example:
namespace
{
class set_configuration_command_tests : public testing::Test
{
protected:
void SetUp() override
{
_uart_peripheral = new uart8_peripheral_mock();
_uart = new uart8_mock(*_uart_peripheral);
_logger = new logger_mock(*_uart);
_mqtt_client = new mqtt_client_mock(*_logger);
_set_configuration_command = new set_configuration_command(*_mqtt_cient);
}
void TearDown() override
{
delete _set_configuration_command;
}
uart8_peripheral_mock *_uart_peripheral;
uart8_mock *_uart;
logger_mock *_logger;
mqtt_client_mock *_mqtt_cient;
set_configuration_command *_set_configuration_command;
};
TEST_F(set_configuration_command_tests, execute_update_configuration)
{
// arrange
// act
// assert
}
}
What I rather did here, is create my sut as
_mqtt_client = new mqtt_client_mock(nullptr); // will not compile of course
_set_configuration_command = new set_configuration_command(*_mqtt_cient);
All the other mocks, I don't need in this case.
Is this the drawback of using reference pointers? Or is there a better approach I should follow?
Found a better alternative. Providing interfaces (pure virtual classes) heavily reduces the need to provide an entire tree of mocks.
e.g
class flash_api : public iflash_api
{
public:
flash_api(iflash_peripheral &flash_peripheral) : _flash_peripheral(flash_peripheral)
{
}
virtual ~flash_api()
{
}
}
Before my mock inherited from flash_api directly. When I gave this class an interface too (`iflash_api') I can let my mock inherit from iflash_api, which gives me a parameter-less constructor.
class flash_api_mock : public iflash_api
{
public:
flash_api_mock()
{
}
virtual ~flash_api_mock()
{
}
}
Then I can write my unit test based on the mocks I actually want to give behavior.
class set_configuration_command_tests : public testing::Test
{
protected:
void SetUp() override
{
_mqtt_cient = new mqtt_client_mock();
_flash_api = new flash_api_mock();
_set_configuration_command = new set_configuration_command(*_mqtt_cient, *_flash_api);
}
void TearDown() override
{
delete _set_configuration_command;
}
flash_api_mock *_flash_api;
mqtt_client_mock *_mqtt_cient;
set_configuration_command *_set_configuration_command;
};

Avoid public `SetState()` interface in state pattern implementation in C++

The state pattern
itself is really nice pattern for implementing state machines because it allows to encapsulate state transitions logic in states themselves and adding a new state is actually becomes easier because you need to make changes only in relevant states.
But, it is usually avoided in description how should states be changed.
If you implement state change logic in Context then whole the point of pattern is missed, but if you implement state change logic in states, that means you need to set a new state in Context.
The most common way is to add the public method to Context SetState() and pass reference to Context to the state object, so it will be able to set a new state, but essentially it will allow the user to change state outside the state machine.
To avoid it I came to the following solutions:
class IContext {
public:
virtual void SetState(unique_ptr<IState> newState) = 0;
}
class Context : public IContext {
private:
virtual void SetState(unique_ptr<IState> newState) override { ... };
}
But in general changing the method scope in derived class doesn't look really good.
Is there another way to hide this interface (friend class is not an option because it requires to change the Context class for each state being added)?
You could consider having the handler handle()returning the next state...
class IState {
public:
virtual unique_ptr<IState> handle(Context&) = 0;
};
class StateA : public IState {
private:
// presented inline for simplicity, but should be in .cpp
// because of circular dependency.
//
virtual unique_ptr<IState> handle(Context& ctx) override
{
//...
if (/*...*/)
return make_unique(StateB{});
//... including other state switch..
return { nullptr }; // returning null indicates no state change,
// returning unique_ptr<>(this) is not really an option.
}
};
The goal of the state pattern is to hide/encapsulate different implementations from the caller.However, caller only needs to know what type of implementation it needs.
Not sure how much this helps, but I just implemented a sample state machine in C# that uses the observer pattern and a tiny bit of reflection to get a very clean and encapsulated implementation of the state pattern.
Context.cs:
using System;
using System.Collections.Generic;
using System.Linq;
public class Context
{
State State { get; set; }
List<State> States { get; }
public Context()
{
States = new()
{
new HappyState(),
new SadState(),
};
SetState<HappyState>();
}
void DoSomething() => State?.DoSomething();
string ReturnSomething() => State?.ReturnSomething();
void SetState<StateType>() where StateType : State => SetState(typeof(StateType));
void SetState(Type stateType)
{
if (!stateType.IsSubclassOf(typeof(State))) return;
var nextState = States.Where(e => e.GetType() == stateType).First();
if (nextState is null) return;
if (State is not null)
{
State?.ExitState();
State.ChangeRequested -= OnChangeRequested;
}
State = nextState;
State.ChangeRequested += OnChangeRequested;
State.EnterState();
}
void OnChangeRequested(Type stateType) => SetState(stateType);
}
State.cs:
using System;
public abstract class State
{
public event Action<Type> ChangeRequested;
protected void SetState<StateType>() where StateType : State
{
ChangeRequested?.Invoke(typeof(StateType));
}
public virtual void EnterState() { }
public virtual void ExitState() { }
public virtual void DoSomething() { }
public virtual string ReturnSomething() => "";
}
You can then use this Syntax in either the Context or any State
SetState<HappyState>();
Link to Repository

Creating a system wide resource C++

I am having an issue designing a software. I have a very big object(BO), let's say a map of dynamic arrays, that I need to access across various classes. Each time a class uses BO, it adds new data to it, or uses some of the data in BO to do computation.
As a newbie, I am lost on how to design such an object in C++ so that my code design and architecture is good. Making a global variable is not efficient enough, researched on Singleton but found out the rule is you can only access the object, not change it.
Anyone can point me in the right direction? what design pattern should I follow that is the most efficient and scalable?
Thanks
Based on the answers here, is the following a correct design- it's psudo!
Class BigObject {
private static BigObject instance = null;
private map;
private BigObject() { }
public static BigObject getInstance() {
if (instance == null) {
instance = new BigObject();
}
return instance;
}
public getArray(string key) {
return map[key];
}
public setBigObject(string key, Array value) {
map.insert(key, value);
}
"but found out the rule is you can only access the object, not change it."
You probably misunderstood something there?
The only purpose of a singleton is to guarantee to have a single instance of a class. You can still change its state as is permitted by its class member functions.
Regarding the singleton implementation you have posted in your updated question you should improve it to be thread safe (following Scott Meyer's Singleton):
class BigObject {
std::map<std::string,Array> map;
BigObject() { }
public:
static BigObject& getInstance() {
static BigObject instance;
return instance;
}
const Array& getArray(std::string key) const {
return map[key];
}
void setBigObject(string key, Array value) {
map.insert(key, value);
}
};
But as Singleton tightly couples your client code to the singleton class, you probably should declare an interface for your BigObject, take references in the classes that need to have access, and pass an instance from construction:
struct IBigObject {
virtual void doCostlyCalculations() = 0;
virtual void updateData(std::vector<int> record) = 0;
virtual ~IBigObject() {}
};
class BigObject : public IBigObject {
virtual void doCostlyCalculations() {
// Implementation ...
}
virtual void updateData(std::vector<int> record) {
// Implementation ...
}
};
class ClientA {
IBigObject& bo_;
public:
ClientA(IBigObject& bo) : bo_(bo) {}
}
class ClientB {
IBigObject& bo_;
public:
ClientA(IBigObject& bo) : bo_(bo) {}
}
int main() {
BigObject bo;
ClientA ca(bo);
ClientB cb(bo);
// ...
};

"Interface Object" pattern. Reasonable?

Lately I've been using some pattern quite a lot but I don't know if it is really good or not.
It goes as follows:
I have a set of function, lets call them ActionFoo, ActionBar and ActionZapper. These might differ in implementation but generally are used for same things across these. They may or may not be used together in a sequence(i.e. some of them can be used as a standalone), but there are some cases when they are, indeed grouped.
If I DO want to use them in a sequence I generally have two options:
1) write them manually each time
2) create a class hierarchy:
Approach #1:
void SomeActionSequence1()
{
ActionFoo1(1);
ActionBar1("Moo");
ActionZapper1("Moo", 42);
}
void SomeActionSequence2()
{
ActionFoo4(1);
ActionBar2("Moo");
ActionZapper1("Moo", 42);
}
This has drawbacks:
1) I won't have an ability to store state and will have to pass a lot of parameters to these Actions
2) I won't really have a coherent interface and won't be able to easily use autocompletion
Approach #2
class Base
{
public:
Base(){}
virtual ~Base(){}
virtual void ActionFoo(int) = 0;
virtual void ActionBar(string) = 0;
virtual void ActionZapper(string, int) = 0;
void ExecuteActionSequence();
};
void Base::ExecuteActionSequence()
{
ActionFoo(1);
ActionBar("Moo");
ActionZapper("Moo", 42);
}
Derived1 : public Base
{
void ActionFoo(int){/*some inplementation*/};
void ActionBar(string){/*some inplementation*/};
void ActionZapper(string, int){/*some inplementation*/};
}
Derived2 : public Base
{
void ActionFoo(int){/*some inplementation*/};
void ActionBar(string){/*some inplementation*/};
void ActionZapper(string, int){/*some inplementation*/};
}
and use it kinda like this:
Base* actionSequence = new Derived1();
actionSequence->ExecuteActionSequence();
Correct virtuals will be used and all seems ok except 2 small things:
1) Extensibility - I will have to write a class for each complex action
2) More importantly - either a lot of functions will be duplicated between these classes or
I will have a hierarchical tree too complex on my hands
I kinda "circumvent" problems of both approaches with "Interface Object" pattern (note, the name is mine, maybe it has a proper one)
What I do is this:
class InterfaceClass
{
public:
InterfaceClass(){};
~InterfaceClass(){};
void ActionFoo(int i)
{
if(fooPlaceholder != 0)
fooPlaceholder(i);
}
void ActionBar(string str)
{
if(barPlaceholder != 0)
barPlaceholder(str);
}
void ActionZapper(string str, int i)
{
if(zapperPlaceholder != 0)
zapperPlaceholder(str, i);
};
void ExecuteActionSequence();
std::function<void(int)> fooPlaceholder;
std::function<void(string)> barPlaceholder;
std::function<void(string, int)> zapperPlaceholder;
};
void InterfaceClass::ExecuteActionSequence()
{
ActionFoo(1);
ActionBar("Moo");
ActionZapper("Moo", 42);
}
in my application I do:
InterfaceClass complexAction;
complexAction.fooPlaceholder = ActionFoo;
complexAction.barPlaceholder = ActionBar;
complexAction.zapperPlaceholder = ActionZapper;
complexAction.ExecuteActionSequence();
Note that ActionFoo, ActionBar and ActionZapper are free functions, but at the same time I am using them in an interface. Also - I can easily switch between implementations of these functions, even at runtime(If I need this).
The advantage of this approach is - there is no need to create separate class structures for new actions and there is no code duplication of Action* functions.
Also - all functions can be brought to scope only where the complexAction is initialized.
The disadvantages are, I think, that it is not obvious just which Action* function is being used in the InterfaceClass object. Also - there is no ability to dynamic_cast such a class to determine just what it is.
I highly suspect that these are not only disadvantages of such approach so I would like comments about that.
It sounds like you want the Chain of Responsibility pattern
abstract class Action {
Action child;
Action(Action child) { this.child = child; }
Action() { }
void doAction(StateContext context);
void execute(StateContext context) {
if (child) child.execute(context);
doAction(context);
}
}
class ZapAction extends Action {
ZapAction(String theString, int theValue, Action child) { ... }
void doAction(Context context) { context.setZap(theString); }
}
Action actionSequenceAlpha = new ZapAction("", 1, new FooAction());
Action actionSequenceBeta = new FooAction(new BarAction(new ZapAction));
Advantages - Don't need to change this base object with a fixed set of strategies when you add a new Action, you can map actions in all sorts of fun and exciting ways, each object has a single responsibility and it is a nice standard pattern so everyone knows what is going on.
The other option would be to separate the sequence from the Action. Have an Action interface with the three Actions inheriting it. Then have a Sequence class with an execute method and a List of Actions
class Action { }
class FooAction extends Action { }
class Sequence {
List<Action> actions;
void execute() {
foreach (action : actions) action.execute();
}
}

How to decouple process in business layer

I am facing a problem that, for some business processes the sequence of invoking business objects and methods may change frequently. So I came up with something similar to the below:(Sorry somehow I can't post image..., I tried to express them in the below text)
Business Objects:
Object1, Object2
Methods: M1, M2, M3, M4
Processes: P1 (M1 > M2 > M3), P2 (M2 > M3 > if M3 return true then M4 else end)
In this case I am using .NET 3.5. I create some classes to represent processes, which contains those sequences I mentioned. It works. But the problem is I need to compile every time when process changed. It would be much better if I could configure it by some sort of XML.
I have heard about jBPM for Java, Workflow Foundation for .NET but not sure if they fit my needs, or would they be overkill. I even don't what keyword to search in Google. Could anyone advice what technology I should use to solve this issue? Or just point me to some websites or books? Thanks in advance.
A common way to decouple software layers is by using interfaces as stated by Dependency Inversion Principle. In you case you could abstract the process concept using an interface and implement the logic in the implementation of that interface.
when you need change the logic of the process you can create a new implementation of that interface. You can use any IoC framework to inject what implementation you want to use
below is showed just a simple way to do that:
public interface IMethod
{
void M1();
string M2();
void M3();
void M4();
}
public interface IProcess
{
IMethod Method { get; set; }
void P1();
void P2();
}
public class Process : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M1();
Method.M2();
}
public void P2()
{
if(Method.M2()==string.Empty)
{
Method.M3();
}
}
}
public class AnotherProcess : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M4();
}
public void P2()
{
Method.M2();
Method.M4();
}
}
public class UseProcess
{
private IProcess _process;
//you can inject the process dependency if you need use a different implementation
public UseProcess(IProcess process)
{
_process = process;
}
public void DoSomething()
{
_process.P1();
}
}