Pre-constructor initialization - c++

My problem is like this, I have a class named "Product" and another class named "Agriculture", the "Agriculture" class is inheriting the "Product" class.
When I summon the "Agriculture" constructor obviously the "Product" constructor is summoned first.
The question is, can I initialize one of the product's members via a set method first?

If you have:
class Product { ... };
class Agriculture : public Product { ...};
you can't escape the standard rule that the base object is constructed before the derived object. You have no chance to intervene in this order, nor set anything in Product before it's constructor starts.
Recommendation:
The best design for your need would be to foresee a Product constructor that takes as additional parameter(s) the value(s) that you want to set:
class Product {
string origin;
public:
Product () : origin("tbd") { }
Product (string withorigin) { ...}
void setOrigin (string myorigin) { origin=myorigin; }
};
class Agriculture : public Product {
public:
Agriculture () : Product ("Earth") { ...}
};
Workaround:
If such design would not fit your needs, the only thing you could imagine, would be to have a static member in Product. This member would then be independent of any Product, and could thus be set before an object is constructed.
class Product {
static string defaultCurrency;
string currency;
public:
Product () : currency(defaultCurrency) { ... }
static void setDefaultCurrency (string cur) { defaultCurrency=cur; }
};
class Agriculture : public Product { ... };
int main() {
Product::setDefaultCurrency("EUR");
Agriculture a1;
}
It's more error prone: the construction result depends on order of operations not related to the construction. This could be a problem for example in case of multithreading, if several threads construct objects at same moment.

Product constructor is called firstly, and you set some values inside this constructor. So why you still want to initialize one of the product's members via a set method first?

Related

Adding operations on Model without adding code to Model

Say i have an hierarchy of Shape objects, each has its own data (polyline has list of vertices, circle has a center and radius, etc).
I want to be able to perform operations on each shape, such as Draw, Snap to some point, split to two shapes at a specific point, etc.
One way to do it is to add a method to Shape interface for each operation. However, in that case i will have to modify my model interface every time a new operation is added. It does not sound correct to me. I thought of the following solution and would like to here your opinion or other solutions.
I will add an interface of ShapeOperationsFactory and the following method to Shape interface:
class Shape
{
public:
virtual ShapeOperationFactory* createShapeOperationsFactory() = 0;
};
class Circle : public Shape
{
public:
virtual ShapeOperationsFactory* createShapeOperationsFactor();
};
ShapeOperationsFactory* Circle::createShapeOperationsFactory()
{
return new CircleShapeOperationsFactory();
}
ShapeOperationsFactory will be able to create a set of operations classes that are specific for the shape:
class ShapeOperationsFactory
{
public:
virtual ShapeDrawer* createDrawer() = 0;
virtual ShapeSnapper* createSnapper() = 0;
virtual ShapeSplitter* createSplitter() = 0;
};
class CircleShapeOperationsFactory : public ShapeOperationsFactory
{
public:
virtual ShapeDrawer* createDrawer();
virtual ShapeSnapper* createSnapper();
virtual ShapeSplitter* createSplitter();
}
ShapeDrawer* CircleShapeOperationsFactory::createDrawer()
{
return new CircleShapeDrawer();
}
ShapeSnapper* CircleShapeOperationsFactory::createSnapper()
{
return new CircleShapeSnapper();
}
ShapeSplitter* CircleShapeOperationsFactory::createSplitter()
{
return new CircleShapeSplitter();
}
In this implementation the Shape interface will not change when new operations are added. For new shape i will need to implement a new operations factory and a class per operation. For new operations i will need to add a method to the operations factory class and a class implementing the operation for each shape.
Making your classes more modular by creating an Operator class I think is great, but this is not really a factory. Factory usually involved creating an object base on some message, for example on a unserialization process.
For your case you could have an Operator member in your base class and in the constructor of your derived class you assign that member to the appropriate Operator derived class.
A solution could be to use the visitor design pattern. The purpose of this design pattern :
the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.
The principle is simple:
You create a visitor class:
class Visitor
{
public:
virtual void visit(Circle*) = 0;
virtual void visit(Polyline*) = 0;
...
};
You add this method to Shape:
virtual void accept(class Visitor*) = 0;
Then you implements this method in each Shape sub class.
void Circle::accept(Visitor *v)
{
v->visit(this);
}
And then you have to create one visitor per operation:
class Drawer: public Visitor
{
public:
Drawer()
{
}
void visit(Circle* c)
{
drawCircle(c);
}
void visit(Polyline*p)
{
drawPolyline(p);
}
...
};
You could also delegate each visit method to a service: (visit(Circle* c) to a CircleDrawer).
void visit(Circle* c)
{
circleDrawer->draw(c);
}
void visit(Polyline*p)
{
polylineDrawer->draw(p);
}
If you want to add an operation, you will have to create a new visitor sub class.
If you want to add a shape, you will have to add a new method on each visitor.
The visitor collaborare really well with the composite design pattern (heavily use in gui programming). The visitor pattern can be used in addition with the composite pattern. The object structure can be a composite structure. In this case in the implementation of the accept method of the composite object the accept methods of the component object has to be invoked.
Note:
I am not a c++ programmer, feel free to edit and make the code syntactically correct.

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.

GOF State Pattern State Transition Implementation Issues

Firstly, can anyone explain how a state object can be shared when the state object has no instance variables ?
This text is taken from GOF, page 308, item 3 (consequences section):
The state object can be shared.
If state objects have no instance variabkes - that is, the state they
represent is encoded entirely in their
type - then contexts can share a
state object. When states are shared in
this way, they are essentially
flyweight.
Can anyone explain this text ?
Secondly, what are the approaches to the state transition decision? I mean the decision of which next state to propagate?
Please help.
Thanks.
In the state pattern you have an represent the state of an object by using state-objects. These state-objects represent a certain state, but they do not have any mutable state of their own. This means they never change. Therefore, any number of objects can use the same state-object at the same time (even from different threads). If the state-object had mutable state, other objects would have to worry about their state-object being changed from elsewhere.
The using of one object instance by many others can be seen as an instance of the flyweight-pattern.
As for the second part of your question, here is an example:
class SomeStateMachine;
class AbstractState {
// abstract baseclass for all state-classes
void input(const std::string & data, SomeStateMachine & caller) = 0;
}
class FinalState : public AbstractState {
FinalState * getInstance(); // always returns same instance
}
class InitialState : public AbstractState {
public:
InitialState * getInstance(); // always returns same instance
void input(const std::string & data, SomeStateMachine & caller) {
std::cout << data << std::endl;
caller.m_State = FinalState::getInstance();
}
}
class SomeStateMachine {
public:
SomeStateMachine() : m_State(InitialState::getInstance())
void input(const std::string & data) {
m_State->input(data, *this);
}
private:
friend class InitialState;
AbstractState * m_State;
};
So you basically pass a reference to the calling object to every method of your state-object. This way, the state-object is able to change the state of the caller when needed. This example might not be very beautiful, but I hope you get the idea.
The paragraph is basically saying that you encode your states as individual classes - then the instance type is the "state" and the classes don't need any instance variables because their type encodes all the information you need.
E.g say I want to have three states "Open", "Active" and "Closed". I might define the following classes:
abstract class State {};
class Open extends State {
public Open() {}
}
class Active extends State {
public Active() {}
}
class Closed extends State {
public Closed() {}
}
--
Another option - I'd suspect this is the combination with flyweight being hinted at in the GOF text would be to create a state class which a bunch of static members (one for each state) which can then be shared -
public class State {
private string name;
private State(String name) {
this.name = name;
}
public final static State OPEN = new State("Open");
public final static State ACTIVE = new State("Active");
public final static State CLOSED = new State("Closed");
}
I had to go digging to remind myself of how all this stuff worked in detail. Kerievsky has a good description of this (I've heavily borrowed from one of his examples above!) and how the state transitions can be handled by sub-classing from the state class, to create classes that manage each transition. See "Refactoring to Patterns" (ISBN: 0321213351)
EDIT(2): His web site has a class diagram for his example - http://www.industriallogic.com/xp/refactoring/alteringConditionalsWithState.html

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.

How to allow derived class to call methods on other derived class? OO-design

Say I have something like -- this is just an example mind you.
class Car
{
void accelerate();
void stop();
}
class Person
{
void drive(Car car);
}
class Toyota : public Car
{
void accelerateUncontrollably();
}
class ToyotaDriver : public Person
{
void drive(Car car)
{
// How to accelerateUncontrollably without dynamic cast?
}
}
A couple things, Toyotas and ToyotaDriver go together, i.e. I can have a ToyotaFactory class which will return the driver and the car. So the pieces are interchangeable and used in different parts of the code but a Toyota and a ToyotaDriver go together.
You can't and you shouldn't...
This is meant to protect you from yourself :)
Either accelerateUncontrollably can only be done in Toyotas (but not in other car models) and then the definition is ok and you should check first if the car is indeed a Toyota or the all the car can "accelerateUncontrollably" and then the declaration should be in the Car class.
You can, of course, make a cast... but ask yourself... if you do know the subtype you're getting... why are you receiving a car and not a Toyota??
Edit: I still don't see why you can't edit it to look like:
interface IToyotaAccelerable
{
void accelerateUncontrollably();
}
class Toyota : public Car : IToyotaAccelerable
{
void accelerateUncontrollably();
}
class ToyotaDriver : public Person
{
void drive(Car car)
{
// Do whatever logic you want with the car...
// How to accelerateUncontrollably without dynamic cast?
IToyotaAccelerable accel = car as IToyotaAccelerable
if (car != null)
{
accel.accelerateUncontrollably();
}
}
}
Now you're programming against a behavioural property, something a given object can or cannot do ... so you don't need to cast and the function at leasts makes a little more sense from a semantic point of view...
You can avoid unsightly downcasting and breaking the Liskov Substitution Principle by simple delegating from the common interface like this:
class Toyota : public Car
{
void accelerateUncontrollably() // can't have abstract methods here, btw
{
// throttle the engine unexpectedly, lock pedal beneath mat, etc.
}
void accelerate() // you have to implement accelerate anyway because of Car
{
accelerateUncontrollably();
}
}
Now the ToyataDriver will have no idea that simply accelerating will call accelerate uncontrollably:
class ToyotaDriver : public Person
{
void drive(Car car)
{
car.accelerate();
}
}
Note also that any Driver object that finds themselves with a Toyota Car object may experience the same effect:
LexusDriver driver = new LexusDriver();
driver.drive(ToyotaFactory.newPrius()); // whee!
GreenHornetDriver driver new GreenHornetDriver();
driver.drive(ToyotaFactory.newCorolla()); // wow!
This is the idea: Toyata Cars present themselves to a Driver as simply a "Car", not an "Uncontrollably Accerating Car." The Driver isn't coupled to the uncontrollablyAccelerate interface, i.e., has no idea what's about to happen. Once they do call accelerate, and assuming doing so doesn't cause the system to crash, we may see a rare corollary to the Liskov Substitution Principle, the Universal Recall Principle.
Seems to me you need another type of car, it needs to extend to a type of car which can accelerate uncontrollably then have Toyota inherit from that.
By you design you are saying not all cars can accelerate uncontrollably and breaking that is break your OO and is a No-No... sorry about the rhyme.
I assume that Person::drive() usually calls Car::accelerate() at some point. I would override the definition of Car::accelerate() in Toyota::accelerate() to include Toyota::accelerateUncontrollably().
If Car::accelerate() isn't virtual, and you can't add a virtual bool Car::isCrazy() function, then there's not a good way to do this. Humorous analogies aside, it appears what you're trying to do is add a property to the Car class without actually modifying the class. There's just not going to be a good OOD way of doing that.
My impression is that using a dynamic_cast is absolutely fine here. No need to avoid it.
You can use the pattern COM follows:
class Car
{
void accelerate();
void stop();
virtual Car* specifyModel(int modelID)
{
return NULL;
}
}
class Person
{
void drive(Car car);
}
#define MODEL_TOYOTA 1
class Toyota : public Car
{
virtual Car* specifyModel(int modelID)
{
if (modelID == MODEL_TOYOTA) return this;
return NULL;
}
void accelerateUncontrollably();
}
class ToyotaDriver : public Person
{
void drive(Car car)
{
Toyota* toyota = static_cast<Toyota*>(car.specifyModel(MODEL_TOYOTA));
if (toyota != NULL)
{
toyota->accelerateUncontrollably();
}
}
}
The basic idea is that you define a virtual method in your base class that represents a "downcast" function that takes a type tag and returns a pointer. If the returned value is not null, the implication is that it can be safely downcasted to the type that matches that tag.
Derived classes override the method, check against their type tag, and return a valid pointer if it matches.