Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I parse/process data coming from many different streams (with different formats) and the number of different sources for data keeps growing in my system. I have a factory class which based on a config file specifying the source will give me the appropriate parser/processor pair (abiding to a small common interface) requested in something like this:
static Foo* FooFactory::createFoo(source c, /*couple flags*/)
{
switch (c)
{
case SOURCE_A:
{
//3 or 4 lines to put together a parser for A, and something to process stuff from the parser
return new FooA(/*args*/);
}
break;
//too many more cases which has started to worry me
default:
return NULL;
};
}
the problem is as the number of sources has grown I am facing two issues. First, when I build, I find myself pulling in all the FooA, FooB, FooC, FooD, FooE... relevant code - even if I was only interested in perhaps building a binary in which I'll only request FooA lets say. So how to go about modularizing that. A secondary issue is, right now in the case of SOURCE_A, I am returning FooA, but what if I am interested in SOURCE_A but I have different ways of parsing it and perhaps I want FooA_simple and FooA_careful but with the ability to plug and play as well?
For some reason, one thing that came to mind was the -u option to the linker when building a binary...it somehow suggests to me the notion of plug and play but I'm not sure what a good approach to the problem would be.
Well, you just create a factory interface and divide the logic among subtypes of that factory. So there might be a sub-factory (type/instance) for libFooA, and another for libFooB. Then you can simply create a composite factory depending on the subfactories/libraries you want to support in a particular scenario/program. Then you could even further subdivide the factories. You could also create factory enumerators for your composite types and do away with all that switch logic. Then you might say to your libFooA factory instance to enable careful mode or simple mode at that higher level. So your graph of FooFactory instances and subtypes could easily vary, and the class structure could be like a tree. Libraries are one way to approach it to minimize dependencies, but there may be more logical ways to divide the specialized sub-factories.
I'm not sure if you can get around importing FooA,FooB... because at any given moment any one of them might be instantiated. As for modularizing it, I'd recommend creating helper functions that gets called inside the switch statement.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a program for a microcontroller in C++, and I need to write a function to input some numbers trough a computer connected to it.
This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.
What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:
class GetNumbers {
public:
//using the constructor as what I called "main" function
GetNumbers(int arg1, char arg2) {
performFirstAction();
performSecondAction();
...
}
private:
performFirstAction() {...};
performSecondAction() {...};
...
bool aSharedVariable;
int anotherVariable;
...
};
And where I actually need to input those numbers from the computer:
GetNumbers thisMakesNoSenseInMyOpinion (x,y);
Making the "main" function a normal class method (and not the constructor) seems to be even worse:
GetNumbers howCanICallThis;
howCanICallThis.getNumbers(x,y);
...
//somewhere else in the same scope
howCanICallThis.getNumbers(r,s);
This is really a software design question. To be honest, unless you're sharing the component with a bunch of other people, I would really worry too much about how its encapsulated.
Many libraries (new and old) might make a family of functions that are to be used in a specific way. Sometimes they have a built in "state machine," but do not have a specific way of enforcing that the functions are used in a specific order. This is okay, as long as its well documented. A group of functions might be prefixed by the same word and packaged as a library if its to be re-usable, that way someone could link to your dll and include the appropriate headers.
https://en.wikipedia.org/wiki/Finite-state_machine
A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), finite automaton, or simply a state machine, is a mathematical model of computation.
Another way of organizing a set of computations is to package them up as a class, allow the contructor to accept the required input, and...
Kick off the required computation in the constructor
Kick off the computation after calling a public function like ->compute()
Making it into a functor (a class with an overloaded set of () operators)
Along with basically countless other options...
This has some benefit because if later you have multiple ways to compute results, you can replace it on the fly using something called the Strategy Pattern.
https://en.wikipedia.org/wiki/Strategy_pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables selecting an algorithm at runtime.
In the end, it doesn't matter which you use as long as you are consistent. If you are looking to make something more "idiomatic" in a given language, you really have to go out there and look at some code on the web to get a feel for how things are done. Different communities prefer different styles, which are all in the end subjective.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am very sorry for the long explanation, but it is required for proper understanding.
I am working on computer vision algorithms for industrial tasks. Computer vision algorithms tend to be very complicate. Usually they involve calls for dozens (at the very least) of simpler algorithms (that are not simple either). Those calls form certain hierarchy: bigger tasks call some smaller ones, which in turn call even smaller ones, and so on.
Let’s take for example typical computer vision task: find object in image under certain conditions. This is a task that should be performed in dozens of different applications. Each application has its own set of conditions and thus it is impossible to create single algorithm that works for all of them. But they are pretty similar. Usually it is enough to replace one or two lower level functions. For example: use different method for detection of points of interest in image.
And here comes a problem: for each new application I had to copy whole code from one of the existing applications and adapt relevant parts, which is a bad practice. I am trying to eliminate those duplications by creating system of algorithms that can be used in all application without changing the code itself. Here is the list of issues system had to deal with (at least the ones I identified so far):
1) Arguments provided to main algorithm should be able to set the 'algorithmic flow' inside the system, i.e. they determine what lower level algorithms are used and how
2) Different sub-algorithms that perform same task may require different inputs. One may need an array of ints, another requires pair of double, and so on... Algorithms on the higher level should be oblivious to replacement of one sub-algorithm with another. That means they should not be aware of what arguments they receive and pass down to sub-algorithms. Same true for output of sub-algorithm. It may vary if different combination of sub-algorithms is used
3) The system must be extendable. If new sub-algorithm became available (for example: yet another way to find points of interest) the system should be able to call it. I understand that changes might be unavoidable at this point, but I would like to keep them at minimum. And in any case the system should be able to work at the same way with previous sets of arguments.
4) System must be debuggable. End user of the system should have reasonable way to dump debug information about the 'algorithmic flow' in his system, so that algorithm developer will be able to recreate the situation. It is not that trivial considering requirement (3).
5) There should be reasonable way to make sanity check for the flow of algorithms.
6) I am not going to throw exceptions but there should be reasonable way to return success / fail status of each algorithm. Again it is not easy because of requirement (3).
7) This one is more 'good to have' rather than 'must have', but it may be important. Some calculations may be performed by multiple sub-algorithms. For example calculation of gradients in image may (or may not) be required for multiple different tasks. It is good to have an option to store results of those calculations in order to reuse them later.
I created some kind of solution to this but it is far from being good. Do you have any recommendations about how this should be done?
Used language: C++
Thanks you
I'd just use some tried and true design patterns.
Use a strategy pattern to represent an algorithm that you may wish to swap out for alternatives.
Use a factory to instantiate different algorithm (strategy) instances based on some input parameter or runtime context - I'm a fan of the prototype factory where you have "inert" instances of each object in some lookup table, and based on a key you pass in you can request a clone of the one needed. I like it mainly because it's easiest to extend - you can even add new configured prototype instances to such a factory at runtime.
Note that the same "strategy" model does not have to serve for everything - it sounds like you might have some higher-level/fuzzy operations which then assemble or chain together low-level/detailed operations. The high level operations could be one type of abstract object while the detailed algorithms are the more concrete strategy instances.
As far as the inputs to the various algorithms, if it varies a lot from algorithm to algorithm you could use an extensible object like a dictionary for parameters so that each algorithm can use just the parameters it needs and ignore the others for an operation. If the dictionary is modifiable during the operation this would also permit upstream algorithms to add parameters for downstream algorithms. Key-value pairs are pretty easy to dump to a log or view in a debugger.
If each strategy instance has a unique semantic identifier you could easily debug the algorithms that get instantiated and chained together. (I use an audio DSP library that has a function to dump a description of the whole chain of configured audio processors, it's very handy).
If you use a system with strategy patterns and extensible parameters you should also be able to segregate shared algorithms from application-specific algorithms, but still have the same basic framework for instantiating and running them.
hth
I'm going to assume that you are a competent OO programmer with good domain knowledge, and your problem is more about a higher level of organisation of software components (implementing algorithms) than OO generally provides.
The patterns mentioned by #orpheist make perfect sense. Consider them. They will not solve all the problems you list. You should also consider the following.
In what form will the data be for algorithms to access?
Will you need adapters to connect one component to another?
Do you pass the data to the component or the component to the data?
Do you want to assemble a pipeline or group of components to build higher ones, which can then be applied to the data?
Do you need a language (XML, DSL) to express connections and to allow for easy experimentation?
Is performance a dominant issue already, or can you afford more interpretive techniques at this stage?
It think you need to refine some of your questions and provide some more concrete specifics. I also think your questions would be a better fit on programmers.stackexchange than here.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am writing a game in Cocos2D-x and I am struggling with feeling like my OO is sloppy. I can't shake the feeling and I can place m finger on why.
Game Scene class
In This a Layer is created
Layer Class
responsible for creating itself
Also calls HUDS when needed
contains std::vectors of objects on the layer
Object Class
hold everything about itself
has a sprite member variable that is on the layer
HUD1
called when the user taps the layer and the touch even occurs in the Object
is a Menu of things that you can do to the Object
When you click a menu item it needs to change values in Object
When you click a menu item it actually runs code in Object (object::doSomething())
What feels sloppy I think is that there is a lot of dependency on these classes together.
I feel like I should abstract this out and create a class that controls all of this happening instead of some code in Object, Layer, HUD, etc.
Can anyone talk to me about how this is laid out and if I am making an OO mistake?
As it turns out graphics and games do not fit into OO designs very well despite being an example in many OO texts. Your instinct is right with respect to decupling the control from the data. A popular design pattern for games these days is to have components, entities, and systems instead of a rigid OO hierarchy.
The idea is that you have Entities or GameObjects that are just collections of components and perhaps some messaging infrastructure. Components store data about the Entity they are attached to, for example you might have a Transform component and a velocity component. Now one approach is to have a messaging system that components can hook into and use that to update their data. For example a Velocity component might hook into the Update message and in the Update handler it could get the transform of the object and move it. By using messages for all communication between components you can decouple them to a large degree.
Systems are a different way to handle updating component data. The idea with Systems is that you have a process that can say "I operate on entities with these components" and then it gets a list of all of the relevant entities when it runs. This decouples data from function even more and can make it easier to manage threading and dependencies
Essentially object oriented design is about capturing "what things are" in the real world, but with a game you don't really want that, all you care about is what things look like and you would like to be able to change the individual facets of something's behavior without pain.
Good resources for Entity-component systems:
http://piemaster.net/2011/07/entity-component-primer/
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
Have a think about what you are trying to achieve before trying to dive in to code (even though the urge to do this is very strong!)
Try to decouple your classes by using Dependency Injection. This may involve adding a bunch of extra classes and complexity now, but trust me, it will make your life much easier later on when you will inevitably need to refactor certain parts of your game. Avoid using 'gum and duct tape' solutions as the technical debt you will incur by doing this will come back and bite you later!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I m not an experienced programmer so please bear with me. As a consequence I will need to be specific on my problem which is about building an architecture to represent a power plant hierarchy:
Indeed, I m trying to construct a flexible architecture to represent contracts and pricing/analysis for multiple type of power plants. I am reading the alexandrescu book about generic design patterns and policy classes as it seems to me a good way to handle the need for flexibility and extensibility for what I want to do. Let s detail a bit :
Power plant can have different type of combustible to run (be of different types) : coal or gas or fuel. Among each of those combustible, you can choose among different sub-type of combustible (ones of different quality or Financial index). Among those sub-types, contract formula describing the delivery can be again of different types (times series averaged with FX within or via a division,etc...) Furthermore, you can be in europe and be subject to emissions reduction schemes and have to provide co2 crédits (enters in the formula of your margin), or not which depend on regulatory issues. As well, you can choose to value this power plant using different methodology etc... etc...
Thus my point is you can represent an asset in very different way which will depend on regulation, choices you make, the type of contracts you agree with another counterparty, the valuation you want to proceed and CLEARLY, you don't want to write 100 times the same code with just a little bit of change. As I said in the beginning, I am trying to find the best programming techniques to handle my program the best way. But as I said, I m new in building software achitecture. It appears to me that Policy classes would be great to handle such an architecture as they can express the kind of choices we have to make.
However, putting it in practice makes me headache. I thought of a generic object factory where Powerplant* is my abstract type where functions like void price() or riskanalysis() would be pure virtual. Then I would need to make a hierachy based on this and derive elements
I couldn't really get what do you want, but I think you should learn programming before you want to do anything related to programming.
Learning is hard and takes a lot of time but it's worth. Also, more useful than asking and getting the answer without explaination. ;)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In Grails, there are two mechanisms for modularity in the view layers: Template and TagLib.
While I am writing my own Grails app, I am often facing the same question when I need to write an UI component: do I need to use a template or a TagLib?
After searching the web, I didn't find a lot of best practices or rules of thumb concerning this design decision, so can you help me and tell me:
What is the main difference between the two mechanisms?
In which scenarios, do you use a TagLib instead of a Template (and vice-versa) ?
There is definitely some overlap, but below are several things to think about. One way to think about it is that Template is like a method-level reuse, while TagLibs are more convenient for API-level reuse.
Templates are great for when you have to format something specific for display. For example, if you wan to display a domain object in a specific way, typically it's easier to do it in a template, since you are basically just writing HTML with some . It's reusable, but I think its reusability in a bit limited. I.e. if you have a template, you'd use it in several pages, not in hundreds of pages.
On the other hand, taglibs is a smaller unit of functionality, but one you are more likely to use in many places. In it you are likely to concatenate strings, so if you are looking to create a hundred lines of HTML, they are less convenient. A key feature taglibs allow is ability to inject / interact with services. For example, if you need a piece of code that calls up an authentication service and displays the current user, you can only do that in a TagLib. You don't have to worry about passing anything to the taglib in this case - taglib will go and figure it out from the service. You are also likely to use that in many pages, so it's more convenient to have a taglib that doesn't need parameters.
There are also several kinds of
taglibs, including ones that allow
you to iterate over something in the
body, have conditional, etc - that's
not really possible with templates.
As I said above, a well-crafted
taglib library can be used to create
a re-usable API that makes your GSP
code more readable. Inside the same *taglib.groovy you can have multiple tag definitions, so that's another difference - you can group them all in once place, and call from one taglib into another.
Also, keep in mind that you can call up a template from inside a taglib, or you can call taglibs withing templates, so you can mix and match as needed.
Hope this clears it up for you a bit, though really a lot of this is what construct is more convenient to code and how often it will be reused.
As for us...
A coder is supposed to see specific object presentation logic in template, not anywhere else.
We use taglibs only for isolated page elements, not related to business logic at all. Actually, we try to minimize their usage: it's too easy to write business logic in a taglib.
Templates are the conventional way to go; for instance, they support Layouts (btw, they can be named a third mechanism)