Object instantiation through factory method not giving desire result - c++

In below code snippet I do require to instantiate the object through factory method in order to call the selected adapter (i.e. adapterTwovalue)but while calling through factory method i am not able to get the desire results. When we assign static declared object's address (i.e adapter = &at) it works but with factory i usually get the blank output.
I tried as well with (adapter = new adapterTwo()) to instantiate the object but output string is giving blank results. As per my requirement i need to populate the all the getters in connect function which is pure virtual function to frame the response.Anybody can suggest how to achieve this using factory method.
#include <iostream>
using namespace std;
class IAdapter
{
public:
enum FactoryList { AdapterOnevalue = 0, AdapterTwovalue };
virtual void connect() = 0;
static IAdapter* CreateList(FactoryList);
virtual ~IAdapter() {}
};
class LibraryOne
{
string property;
public:
void SetConnection(string property)
{
this->property = property;
}
string getConnection()const
{
return property;
}
};
//LibraryTwo
class LibraryTwo
{
string broker;
public:
void SetBroker(string broker1)
{
this->broker = broker1;
}
string getBroker() const
{
return broker;
}
};
//adapterOne
class AdapterOne : public IAdapter
{
LibraryOne one;
string constring;
public:
void SetClientconnection(string constring)
{
one.SetConnection(constring);
}
string GetClientconnection()
{
return one.getConnection();
}
void connect()
{
constring = GetClientconnection();
}
};
//Adapter to use library two
class AdapterTwo : public IAdapter
{
LibraryTwo two;
string brokerstring;
public:
void SetClientbroker(string constring)
{
two.SetBroker(constring);
}
string GetClientbroker()
{
return two.getBroker();
}
void connect()
{
string constring = GetClientbroker();
cout << "final value=" << constring;
}
};
IAdapter* IAdapter::CreateList(FactoryList SelectList)
{
IAdapter *ListObject;
switch (SelectList)
{
case AdapterOnevalue:
ListObject = new AdapterOne();
break;
case AdapterTwovalue:
ListObject = new AdapterTwo();
break;
default:
ListObject = NULL;
}
return ListObject;
}
int main()
{
IAdapter *adapter = 0;
//LibraryTwo obj;
AdapterTwo at;
at.SetClientbroker("amqp");
//cout << at.GetClientbroker();
//adapter = &at; it works
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);//it doesn't work
//Just do the operation now
adapter->connect();
return 0;
}

You can see the complete solution in below share link.
http://coliru.stacked-crooked.com/a/d8b9d32a1fa989c9
Here is the explanation.
(1) setClientBroker() or all other adapters related setter functionality needs to be implement as a virtual function in Interface with default parameter value " " (blank string).
(2) you need to always use override keyword (c++11) feature in derive class for setters so that compiler will cross check during compilation whether proper virtual method is being overridden or not.
(3) instead of using local raw pointer , always use smart pointer . below is the
implementation link for the same.
http://coliru.stacked-crooked.com/a/2feea991ee90d4a2

With your code I expect the output: final value=.
It will not print final value=amqp cause you need to call SetClientbroker("amqp") on the right adapter object (adapter in your example).
Anyway, I would think about putting a virtual method SetString in the base class, so you could simply do:
int main()
{
IAdapter *adapter = 0;
//LibraryTwo obj;
//AdapterTwo at;
//at.SetClientbroker("amqp");
//cout << at.GetClientbroker();
//adapter = &at; it works
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);//it doesn't work
//Just do the operation now
adapter->SetString("amqp");//<---------
adapter->connect();
return 0;
}
EDIT after the comment:
You need to cast the object, at this point (as suggested by #Aconcagua).
But IMHO it's not elegant at all. I think you are going to loose the benefits gained with the factory method.

IAdapter* adapter = nullptr;
AdapterTwo at;
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
You have created two independent objects here (as calling new within createList): at and the one adapter points to.
AdapterTwo at;
at.SetClientbroker("amqp");
Now sure you get the expected output if you let adapter point to at, but how could the other object be aware of the string you set in the first one?
adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
adapter->SetClientbroker("amqp"); // (*) !!!
You need to set the broker at the other object, too. As being different objects, you even can set the brokers independently:
AdapterTwo at;
at.SetClientbroker("amqp");
IAdapter* adapter = IAdapter::CreateList(IAdapter::AdapterTwovalue);
adapter->SetClientbroker("aconcagua"); // (*) !!!
Output now would be (if you called connect on both objects):
final value=amqp
final value=aconcagua
Only: The marked lines ((*)) won't compile as your base class does not provide the appropriate setter!
There are now different solutions for this problem. You could, for instance, just cast the object:
// if you are REALLY 100% sure the object is of appropriate type:
static_cast<AdapterTwo*>(adapter)->setClientBroker("...");
// if NOT:
AdapterTwo* a2 = dynamic_cast<AdapterTwo*>(adapter);
if(a2)
a2->setClientBroker("...");
else
// appropriate error handling
You could find a more generic name for the set/get Broker/ClientConnection functions, have them already pure virtual within IAdapter and override them in the two implementing adapter classes, so you could then just call adapter->setXYZ("ampq");. [Edit: according to your comment to the question, not an option in the given case]
My personal favourite is providing an additional parameter to your createList function such that the setter would already be called within the factory - possibly with appropriate default: empty string, if you opt for a std::string parameter, or nullptr in case of char const*. You'd only call the setter if the parameter is not matching the default, of course... Alternatively, you could have two overloads.

Related

C++ how to have seperate versions of the same method?

I'm sorry if I don't know the right word for what I'm trying to accomplish.
Basically I have an event handler object which only has a single member. The member is a Stage object.
When the event handler receives an event, I want it to simply use the stage object to call the relevant method. For example:
Event event; //this event is not part of my code, but rather the library I'm using.
Stage s; // my custom class object
EventHandler event_handler; //also my custom class object
event_handler.stage = &s;
if(event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}
So what I'm trying to accomplish is that, there will be seperate scopes that my program goes into over time, and I want each scope to have access to the event_handler such that they can do something like:
void some_other_scope(EventHandler* eh) {
Stage* some_new_stage = new Stage(...);
eh->stage = some_new_stage;
}
This way, the original event code stays the same, and the event handler will be calling handle_shutdown on a different object than it was originally going to.
So what I want to do is to overload the handle_shutdown method so that there can be different implementations of it. I know how basic overloading works, it can be done by specifying different parameters, but is there any way to have different definitions of the same class method based on the file that the object was created in?
I was hoping to have several files, each with their own some_other_scope() function, and each file can redefine the handle_shutdown method to do different things based on what that file needs.
I'm sure there's a way to do what I want, I just don't know the right words to use.
It seems you want to use polymorphism:
class IStage
{
public:
virtual ~IStage() = default;
virtual void handle_shutdown() = 0;
// ...
};
class Stage1 : public IStage
{
public:
void handle_shutdown() override { /*Implementation1*/ }
// ...
};
class Stage2 : public IStage
{
public:
void handle_shutdown() override { /*Implementation1*/ }
// ...
};
And then
struct EventHandler
{
std::unique_ptr<IStage> stage;
// ...
};
EventHandler event_handler;
event_handler.stage = std::make_unique<Stage1>();
if (event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}
// Later
event_handler.stage = std::make_unique<Stage2>();
if (event == SHUTDOWN) {
event_handler.stage->handle_shutdown();
}

should we create object of any class on class level or function level

Which approach is better: I tried to find it on web, but I couldn't get a better answer.
1.
public class OtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
OtherClass oClass = new OtherClass();
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
2.
public class TestClass
{
public int Fun1()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
public int Fun2()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
}
I think it depends on what you are trying to test.
If you're testing the effects of a sequence of functions being executed on the same class instance then you might want to create a single instance (such as stress testing)
But otherwise I'd say it's always better to create a new instance of the class in each test function to ensure that the context of each test is predictable. If your test methods shared an instance of a class, and one test method fails and corrupts the state of the object under test, your subsequent test may fail for no other reason than the state of the object under test was corrupted by the previous failed test (it might appear the multiple tests are failing when in fact only one of the early ones is a true failure).
Depends on the scenario, if the class is gonna be shared on multiple functions and there are no specific arguments needed to create an instance of that class then it's better of being at the class level.
Let's say you're using the Fun1 and Fun2 often, having the instance creation on the method will have instance creation overhead rather than it being at the class level having a single instance, or better yet, make it static or make it singleton if you're sure that it's going to be a single instance throughout the whole app.
One benefit of having it in the class level is if you're doing unit testing, you can make an interface like IOtherClass and Inject it in the constructor of TestClass.
It would look something like this.
public class OtherClass : IOtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
IOtherClass oClass;
public TestClass(IOtherClass _oClass)
{
oClass = _oClass;
}
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
You're better off having it as a field in the class rather than declaring a new one in each method. The reason for this is simple, there won't be a line of code in each method declaring the variable meaning that if your declaration statement changes you will only have to change it in one place, not every method. Also it will make your code easier to read and add to because this line won't be duplicated everywhere.
Just remember if that field needs to be disposed your class should implement the IDisposable interface.

Partial Mock or new class or what else?

I have a question about testing.
I have a class that returns anomalies. in this class I have two different method that simply returns two different types of anomalies and one that return all anomalies (of both types)
this is the example code:
public interface IAnomalyService
{
IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2);
IList<Anomaly> GetAnomalies_OfTypeA(object parameter1);
IList<Anomaly> GetAnomalies_OfTypeB(object parameter2);
}
public class AnomalyService : IAnomalyService
{
public IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2)
{
var lstAll = new List<Anomaly>();
lstAll.AddRange(GetAnomalies_OfTypeA(parameter1));
lstAll.AddRange(GetAnomalies_OfTypeB(parameter2));
return lstAll;
}
public IList<Anomaly> GetAnomalies_OfTypeA(object parameter1)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 1 } };
}
public IList<Anomaly> GetAnomalies_OfTypeB(object parameter2)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 2 } };
}
}
class Anomaly
{
public int Id { get; set; }
}
I've created the tests for the two method that retrieve the anomalies of type A and type B (GetAnomalies_OfTypeA and GetAnomalies_OfTypeB).
Now I want to test the function GetAllAnomalies but I'm not sure what I have to do.
I think I have to way for testing it:
1) declare GetAnomalies_OfTypeA and GetAnomalies_OfTypeB in class AnomalyService as virtual, make a mock of the Class AnomalyService, and using Moq I can set CallBase as true and mock the two method GetAnomalies_OfTypeA and GetAnomalies_OfTypeB.
2)move the method GetAllAnomalies in another class called AllAnomalyService (with interface IAllAnomalyService) and in its constructor I will pass an interface of IAnomalyService and after I can test the GetAllAnomalies mocking the IAnomalyService interface.
I'm new at unit testing, so I don't know which solution is better, if is one of the mines or another one.
Can you help me?
thank you
Luca
Mocking is a good tool when a class resists testing. If you have the source, mocking is often not necessary. Try this approach:
Create a factory which can return AnomalyServices with various, defined anomalies (only type A, only type B, both, none, only type C, ...)
Since the three types are connected in some way, you should check all three in each test. If only anomalies of type A are expected, you should check that GetAllAnomalies returns the same result as GetAnomalies_OfTypeA and GetAnomalies_OfTypeB returns an empty list.

Invalid conversion from BaseClass* to DerivedClass*

I'm trying to use the factory method to return a derived class but the return type is the base class type. From my understanding I thought inheritance would allow me to do this, obviously I am wrong.
WeightExercise and CardioExercise are both derived from Exercise.
I could cast the object but I thought my design would mean I don't have to do that. Can someone point out my mistake please?
Main
ExerciseFactory ExerciseFactoryObj;
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Factory Class
class ExerciseFactory
{
public:
ExerciseFactory();
~ExerciseFactory();
Exercise* createExercise(int exercisetype);
private:
static WeightExercise* createWeightExercise() { return new WeightExercise(); }
static CardioExercise* createCardioExercise() { return new CardioExercise(); }
};
Factory Implementation
Exercise* ExerciseFactory::createExercise(int exercisetype)
{
if ( 1 == exercisetype )
{
return this->createWeightExercise();
}
else if ( 2 == exercisetype )
{
return this->createCardioExercise();
}
else
{
cout << "Error: No exercise type match" << endl;
}
}
You can assign a Derived class returned from the factory to the base class one :
ExerciseFactory ExerciseFactoryObj;
Exercice *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
Edited:
If you really need to access WeightExerciceObject element use :
WeightExerciceObject * weight = dynamic_cast<WeightExerciceObject *>(ExerciseFactoryObj.createExercise(menuselection));
this will return NULL if the class is not the exact one. You need to check against NULL.
In the main method, this:
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
should be this
Exercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
You can't use WeightExercise, because you don't know what specific type of exercise is being returned, it might be a CardioExercise or a WeightExercise, or some other future type you aren't yet aware of.

Should class methods accept parameters or use class properties

Consider the following class
public class Class1
{
public int A { get; set; }
public int B { get; set; }
public int GetComplexResult()
{
return A + B;
}
}
In order to use GetComplexResult, a consumer of this class would have to know to set A and B before calling the method. If GetComplexResult accesses many properties to calculate its result, this can lead to wrong return values if the consumer doesn't set all the appropriate properties first. So you might write this class like this instead
public class Class2
{
public int A { get; set; }
public int B { get; set; }
public int GetComplexResult(int a, int b)
{
return a + b;
}
}
This way, a caller to GetComplexResult is forced to pass in all the required values, ensuring the expected return value is correctly calculated. But if there are many required values, the parameter list grows as well and this doesn't seem like good design either. It also seems to break the point of encapsulating A, B and GetComplexResult in a single class. I might even be tempted to make GetComplexResult static since it doesn't require an instance of the class to do its work. I don't want to go around making a bunch of static methods.
Are there terms to describe these 2 different ways of creating classes? They both seem to have pros and cons - is there something I'm not understanding that should tell me that one way is better than the other? How does unit testing influence this choice?
If you use a real-world example the answer becomes clearer.
public class person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string getFullName()
{
return firstName + " " + lastName;
}
}
The point of an entity object is that it contains information about an entity, and can do the operations that the entity needs to do (based on the information it contains). So yes, there are situations in which certain operations won't work properly because the entity hasn't been fully initialized, but that's not a failure of design. If, in the real world, I ask you for the full name of a newborn baby who hasn't been named yet, that will fail also.
If certain properties are essential to an entity doing its job, they can be initialized in a constructor. Another approach is to have a boolean that checks whether the entity is in a state where a given method can be called:
while (person.hasAnotherQuestion()) {
person.answerNextQuestion();
}
A good design rule is to make sure that all constructors initializes objects to valid states and that all property setters and methods then enforces the valid state. This way there will never be any objects in invalid states.
If the default values for A and B, which is 0 is not a valid state that yields a valid result from GetComplexResult, you should a constructor that initialized A and B to valid a state.
If some of the fields are never allowed to be null then you would typically make them parameters to the class constructor. If you don't always have all of the required values available at once then using a builder class may be helpful.
For example:
public Builder {
private int a;
private int b;
public Class1 create() {
// some validation logic goes here
// to make sure we have everything and
// either fill in defaults or throw an error
// if needed
return new Class1(a, b)
}
public Builder a(int val) { a = val; }
public Builder b(int val) { b = val; }
}
This Builder can then be used as follows.
Class1 obj1 = new Builder().a(5).b(6).create();
Builder builder = new Builder();
// do stuff to find value of a
builder.a(valueOfA);
// do stuff to find value of b
builder.b(valueOfB);
// do more stuff
Class1 obj2 = builder.create();
Class2 obj3 = builder.create();
This design allows you to lock down the Entity classes to whatever degree is appropriate while still allowing for a flexible construction process. It also opens the door to customizing the construction process with other implementations without changing the entity class contract.