Entity component architecture : want to split big entity -> hard to refactor - c++

In the first step of development, I design Car and AI as 1 entity.
It works nice (pseudo code):-
for(every entity that is "racing car"){
//^ know type by using flag
// or iterate special component (e.g. "RacingCarComponent")
Entity entity=...
AI* ai=get<AI>(entity);
ai->setInformation(...)
}
for(every entity that is "bicycle"){
Entity entity=...
AI* ai=get<AI>(entity);
ai->setInformation(...) //the info is very different from "racing car"
}
Later, I want a new feature : switch in-out Driver (which effect AI).
I split the entity as shown in the following diagram :-
The above code will be updated to be :-
for(every entity that is "racing car"){
Entity entity=...
AttachAI* aiAttach=get<AttachAI>(entity); //<-- edit
aiAttach->ai->setInformation(...) //<-- edit
}
for(every entity that is "bicycle"){
Entity entity=...
AttachAI* aiAttach=get<AttachAI>(entity); //<-- edit
aiAttach->ai->setInformation(...) //<-- edit
}
Problem
It works nice both before and after the change, but it is hard to maintain.
If there are N types of vehicle in version1 e.g. truck, motercycle, plane, boat, rocket,
I will have to edit N*2 lines of which potentially have already scattered around many .cpp.
Main issue : If I forget to refactor any code, it will still compile fine.
Problem will appear in only run-time.
In real life, I face such issue whenever new design wish to divide an entity into many simpler entities.
The refactoring is always just adding another one indirection.
Question
Suppose that in version1, I don't expect that I will want to switch in/out Driver.
Is it possible to prevent the problem? How?

I may be mistaken, but it seems as though you may be looping through all of the entities multiple times, checking a condition. I am not exactly sure about c++ syntax, so please bear with me:
for (entities as entity) {
info = null;
//Check type to get specific info
if (type is a "racing car"){
info = "fast car";
}
elseif (type is a "bicycle") {
info = "rad spokes";
}
//If we found info, we know we had a valid type
if (info isnt null) {
aiAttach = get(entity);
aiAttach->ai->setInformation(info);
}
}
I'm not sure if the get function requires anything specific for each type. In my pseudocode example, I assume we are only sending the entity and not something type specific. If it does, an additional variable could be used.

Related

SCIP: How to resolve LP after catching a 'node infeasibility' event,

I have a working column generation algorithm in SCIP. Due to specific constraints that I include while generating columns, it might happen that the last pricing round determines that the root node is infeasible (by the Farkas pricer of course).
In case that happens, I would like to 1) relax those specific constraints, 2) resolve the LP, and 3) start pricing columns again.
So, I have created my own EventHandler class, catching the node infeasibility event:
SCIP_DECL_EVENTINITSOL(EventHandler::scip_initsol)
{
SCIP_CALL( SCIPcatchEvent(scip_, SCIP_EVENTTYPE_NODEINFEASIBLE, eventhdlr, NULL, NULL));
return SCIP_OKAY;
}
And, corresponding, the scip_exec virtual method:
SCIP_DECL_EVENTEXEC(EventHandler::scip_exec)
{
double cur_rhs = SCIPgetRhsLinear(scip_, *d_varConsInfo).c_primal_obj_cut);
SCIPchgRhsLinear (scip_, (*d_varConsInfo).c_primal_obj_cut, cur_rhs + DELTA);
return SCIP_OKAY;
}
Where (*d_varConsInfo).c_primal_obj_cut is the specific constraint to be changed, DELTA is a global parameter, and cur_rhs is the current right hand side of the specific constraint. This function is neately called after the node infeasibility proof, however, I do not know how to 'tell' scip that the LP should be resolved and possible new columns should be included. Can somebody help me out with this?
When the event handler catches the NODEINFEASIBLE event, it is already too late to change something about the infeasibility of the problem, the node processing is already finished. Additionally, you are not allowed to change the rhs of a constraint during the solving process (because this means that reductions done before would potentially be invalid).
I would suggest the following: if your Farkas pricing is not able to identify new columns to render the LP feasible again, the node will be declared to be infeasible in the following. Therefore, at the end of Farkas pricing (if you are at the root node), you could just price an auxiliary variable that you add to the constraint that you want to relax, with bounds corresponding to your DELTA. Note that you need to have marked the constraint to be modifiable when creating it. Then, since a variable was added, SCIP will trigger another pricing round.
maybe you should take a look into the PRICERFARKAS method of SCIP (https://scip.zib.de/doc/html/PRICER.php#PRICER_FUNDAMENTALCALLBACKS).
If the current LP relaxation is infeasible, it is the task of the
pricer to generate additional variables that can potentially render
the LP feasible again. In standard branch-and-price, these are
variables with positive Farkas values, and the PRICERFARKAS method
should identify those variables.

The balance of Single responsibility/unit testability and practicality

I'm still confused about unit testing. Suppose I have something as trivial as this:
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
return ScalrWrapper.resize(image, resizeMode);
}
}
Going by rules, Scalr.Mode resizeMode = should probably be a in a separate class for better unit testability of the aforementioned method, like so:
class xxx {
mode getResizeMode(int width, int height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = xxx.getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
}
But it looks like such an overkill... I'm not sure which one is better but I guess this way is better. Suppose I go this route, would it be even better to do it this way?
class xxx {
mode getResizeMode(Image image)
{
return (image.getWidth() > image.getHeight()) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
void someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
Scalr.Mode resizeMode = xxx.getResizeMode(image);
return ScalrWrapper.resize(image, resizeMode);
}
}
From what I understand, the correct way is the one where getResizeMode accepts integers as it is decoupled from the type of data whose properties are width and height. However, personally to me, the use of getResizeMode(BufferedImage) actually justifies the creation of a separate class better as some more work is removed from the main method. And since I am not going to be using getResizeMode for any sort of data other than BufferedImage in my application anyway, there is no problem of reusability. Also, I don't think I should be doing getResizeMode(int, int) simply for reusability if I see no need for it due to YAGNI principle.
So my question is: would getResizeMode(BufferedImage) be a good way according to OOD in real world? I understand it's text book good OOD, but then I have been lead to believe that 100% text book OOD is impracticle in real world. So as I am trying to learn OOD, I just want to know which path I should follow.
...Or maybe I should I just leave everything in one method like in the very first code snippet?
I don't think that resize mode calculation influences testability a lot.
As to Single Responsibility:
"A class should have only one reason to change" (https://en.wikipedia.org/wiki/Single_responsibility_principle).
Do you think that resizing mode calculation is going to change?
If not then just put in the class where this mode is needed.
This won't add any reasons to change for that class.
If the calculation is likely to change (and/or may have several versions)
then move it to a separate class (make it a strategy)
Achieving the Single Responsibility Principle (SRP) is not about creating new classes every time, one extracting a method. Moreover the SRP depends on the context.
A module should concern to the SRP.
A class should concern to the SRP.
A method should concern to the SRP.
The message from Uncle Bob is: Extract till you Drop
Beyond he said:
Perhaps you think this is taking things too far. I used to think so too. But after programming for over 40+ years, I’m beginning to come to the conclusion that this level of extraction is not taking things too far at all.
When it comes to the decision to create new classes, keep the metric high cohesion in mind. Cohesion is the degree to which the elements of a module belong together. If all methods work in one specific context and on the same set of variables, they belong to one class.
Back to your case. I would extract all the methods and put them in on class. And this one class is also nicely testable.
Little bit late to the party, but here's my 2c.
To my mind, class x is not adhering to the SRP for a different reason.
It's currently responsible for
Getting an image from a file (getter.getImageFromFile)
Resizing that image
TL;DR
The TL;DR on this is that both of your approaches are fine and both do in fact stick - with varying degrees of stickiness - to the SRP. However if you want to adhere very tightly to the SRP (which tends to lead to very testable code), you could split this into three classes first:
Orchestrator
class imageResizeService
{
ImageGetter _getter;
ImageResizer _resizer;
zzz ResizeImage(imageName)
{
image=_getter.GetImage(imageName);
resizedImage=_resizer.ResizeImage(image);
return resizedImage;
}
}
This class has a single responsibility; namely, given an image name,
return a resized version of it based on some criteria.
To do so, it orchestrates two dependencies. But it only has a single reason to change which is that the process used to get and resize an image in
general , has changed.
You can easily unit test this by mocking the getter and resizer and testing that they are called in order, that the resizer is called with the data given by the getter, and that the final return value equals that returned by the resizer, and so on (i.e. "White Box" testing)
ImageGetter
class ImageGetter
{
BufferedImage GetImage(imageName)
{
image=io.LoadFromDisk(imageName) or explode;
return image;
}
}
Again, we have a single responsiblity (load an image from disk, and return it).
The only reason to change this class would be if the mechanics of loading the image were to change - e.g. you are loading from a Database, not a Disk.
An interesting note here is that this class is ripe for further generalisation - for example to be able to compose it using a BufferedImageBuilder and a RawImageDataGetter abstraction which could have multiple implementations for Disk, Database, Http, etc. But that's YAGNI right now and a conversation for another day :)
Note on testability
In terms of unit testing this, you may run into a small problem, namely that you can't quite "unit test" it - unless your framework as a mock for the file system. In that case, you can either further abstract the loading of the raw data (as per the previous paragraph) or accept it and just perform an integration test off a known good file. Both approaches are perfectly valid and you should not worry about which you choose - whatever is easier for you.
ImageResizer
class ImageResizer
{
zzz ResizeImage(image)
{
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
private mode getResizemode(width, height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
This class also has but a single job, to resize an image.
The question of whether or not the getResizeMode method - currently just a private method to keep the code clean - should be a separate responsiblity has to be answered in the context of whether or not that operation is somehow independent of the image resizing.
Even if it's not, then the SRP is still being followed, because it's part of the single responsibility "Resize an Image".
Test-wise this is also really easy to test, and because it doesn't even cross any boundaries (you can create and supply the sole dependency - the image - during test runtime) you probably won't even need mocks.
Personally I would extract it to a separate class, just so that I could, in isolation, verify that given a width larger than a height, I was returned a Scalr.Mode.FIT_TO_WIDTH and vice-versa; it would also mean I could adhere to the Open Closed Principle whereby new scaling modes could be introduced without having to modify the ImageResizer class.
But really
The answer here has to be that that it depends; for example if you have a simple way to verify that, given a width of 100 and a height of 99, then the resized image is indeed scaled to "Fit to Width" then you really don't need to.
That being said I suspect you'll have an easier time testing this if you do extract that to a separate method.
Just bear in mind that if you're using a decent IDE with good refactoring tools, that should really not take you more than a couple of keystrokes, so don't worry about the overhead.

splitting tasks to categories

I have a class (lets call it checker) and diffrent kind of classes that execute tasks (lets call them tasks). each tasks belongs to several categories
each task runs and at some point asks checker if they are allowed to do something. checker answers according to system state and according to their category. a task can be in multiple categories
how would you implement that? (cpp but I don't really think its language specific).
I was thinking adding a list of categories in each task and have a function that gets a category and answers if the task belongs to it.
class checker {
bool is_allowed(Task * task);
}
class Task
{
bool is_belongging_to_category(Category cat);
void some_task_to_do()
{
...
if (checker::is_allowed(this)) { ....}
else {....}
}
}
Is there a better way to solve this? Maybe some known design pattern...
This looks like questionable design. You're making tasks the objects.
Let's say your tasks are: Eat, Drink, and Be_Merry
If you make each of those tasks objects, they'll have to maintain a reference to the actual individual that they operate on, then when the condition is met they'll need to modify state on the given individual.
This is a violation of Object Oriented Design which defines an object as:
A tight coupling or association of data structures with the methods or functions that act on the data
Notice that you have split the "methods or functions that act on the data" from the object. Instead you should have modeled the objects Jack and Jill which had methods: Eat, Drink, and BeMerry
As far as checker, whether it's parceled out will depend upon whether you're using a push or a pull coding. If you're doing push coding, then checker is simply a holding area for the behavioral properties of Jack and Jill, in such a case the properties should be pushed to Jack and Jill rather than held in checker. If they are properties for all Jack or Jill objects, use a static property. If however you are using pull coding then the information is unavailable until you attempt to execute the task. In this case the checker should probably be a singleton that Jack and Jill access in the process of performing their tasks.
EDIT:
Your comment reveals further tragedy in the design. It seems as though you've kicked off a bunch of threads which are doing busy waiting on checker. This indicates that you need to be using a pull coding. You're Jack and Jill objects need to maintain booleans for which tasks they are actively involved in, for example m_is_going_to_school, then when checker gets the condition that would stop your busy waiting in your design, instead kick off the goToSchool method.
You could make a vector to store all the possible allowed options. You can make a bool function (like you have) called IsAllowed with argument string and that will check if the option its going to do is allowed. If not, return false. That's just my idea though. Of course there's a zillion different ways to implement this. If you want multiple choices. Then you can make a 2d vector, and see if the corresponding row has any of the options. Good luck!
If you know the maximum number of categories in advance, I'd recommend using Bit Flags to do this.
enum Category {
CATEGORY_A = 1,
CATEGORY_B = 1 << 1,
CATEGORY_C = 1 << 2,
CATEGORY_D = 1 << 3,
};
class Task {
int32_t categories_;
public:
Task() : categories_(0) {}
void add_category(Category cat) {
categories_ |= cat;
}
void run() {
checker::can_run(categories_);
}
}
This allows to test for multiple categories all at once:
namespace checker {
bool can_run(int32_t categories) {
int32_t cannot_run_right_now = CATEGORY_A | CATEGORY_C;
if(categories & cannot_run_right_now != 0) {
return false;
}
...
}
}
Well, it depends. If you are 100% sure that you know how many categories there are to be and that is not some gigantic number then you might store this information as an integer. If n-th bit is 1 then task belongs to n-th category. Then depends on the state of system you might create some another integer that would serve as a mask. In the end you would just do some bit-AND ( mask & categories != 0 ) operation to determine if task and mask share common bit.
On the other hand if there will be unknown number of categories you might just make a list of categories it belongs to. Make a dictionary of [SYSTEM_STATE] => [CATEGORIES_AVAILABLE] and check
bool is_allowed(Task * task){
foreach (Category sysC in stateCategories[sys.GetState()])
{
foreach (Category taskC in task.GetCategories())
{
if(sysC == taskC) return true;
}
}
return false;
}
That would of course be slow for a big number of categories.
You could improve this method by making this list of categories some another data structure, in which searching is not O(n) such that the code would look like this :
bool is_allowed(Task * task){
foreach (Category sysC in stateCategories[sys.GetState()])
{
if task.GetCategories().Contains(sysC) {
return true;
}
}
It depends

Implementing UML Sequence Diagram

My question is relatively simple: how would I go about implementing a UML sequence diagram in C++ code? I was reading up on sequence diagrams the other day, and I found this example for a program for a student enrolling in a seminar.
How would I go about turning this diagram into a program? For the sake of this question, lets focus on one class, say the EnrollInSeminar controller. How would I go about implementing this?
I imagine that it might be something like this:
class EnrollInSeminar
{
public:
void Activate();
};
void EnrollInSeminar::Activate()
{
SecurityLogon logonUI{};
Student theStudent = logonUI.getStudent();
SeminarSelector seminarSelectorUI{};
Seminar seminar = seminarSelectorUI.getSeminar();
if (!seminar.isEligible(theStudent))
return;
theStudent.getSchedule().determineFit(seminar);
Fee fee = StudentFees.calculateFees(seminar, theStudent);
FeeDisplay feeUI{fee};
if (!feeUI.getVerification())
return;
seminar.enrollStudent(theStudent);
}
Is this the correct way to implement the EnrollInSeminar class? If not, how should I do it?
Actually a SD does not tell anything about the methods being used in the messages passed from one object to another except the name, the parameters and - as the name says - the sequence. So the only thing you can draw from "just the SD" are methods and their parameters.
You will need additional information from a use case to know what the methods are all about. Without you simply can not "implement a SD".

How to handle state transitions and yet replace "if" statements with polymorphic types?

Recently I was listening to a tech talk on clean coding. The speaker was a test engineer, who emphasized on avoiding the "if" statements in the code and use polymorphism as much as possible. Also he advocated against global states.
I quite agree with him, yet i need a clarification on replacing the global state and "if" statement using polymorphism for the below scenario,
I have 3 states in my document. I want to change the state of the UI components based on the document state. Right now, i use "if" blocks and an enumeration type holding the current state of document to transition the states of UI components.
eg:
enum DOC_STATE
{
DOC_STATE_A = 0,
DOC_STATE_B,
DOC_STATE_C
};
void QMainWindow::handleUi(_docState)
{
switch(_docState)
{
case (DOC_STATE_A):
{
menu.disable();
....
}
case (DOC_STATE_B):
{
menu.enable();
...
}
case (DOC_STATE_C):
{
...
}
}
I think i can have separate child classes for each state and have the handleUI() method in each class. Calling handleUi() method calls the right method call. But say i maintain these objects in my doc, how do i switch from one object to other each time there is a transition in state?
In other words, how to handle UI transition by tracking the change in state of document without using a global state and "if" or Switch statements?
I use Qt. Thanks.
If you are using Qt, take a look at The Qt State Machine Framework and the State Machine Examples. No need to re-invent the wheel when your framework already provides a sports car :)
I don't think I understand the problem because the answer is too trivial: you replace the pointer to your state instance with a new state instance and discard the old one.