C++ organize flow of functions [closed] - c++

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.

Related

Is it a good practice for a class to have only public (no private or protected) methods and variables? [closed]

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 2 years ago.
Improve this question
recently I am doing a project for a school course. I always declare all variables and methods inside every classes public because It helps me access those variables easier while developing and less coding for the get(); and set(); functions. However, i think this is the wrong way of doing OOP. Any ideas?
Getters/Setters are useful sometimes, but aggregates are also useful.
If you have an aggregate, you should be willing to accept any data that matches the types of your data fields. If you want to maintain invariants (width>height) and assume it elsewhere in your code, you'll want accessors.
But code that doesn't assume invariants is often easier to work with and can even be less bug prone; manually maintaining invariants can get extremely hard, as messing up or compromising even once makes the invariant false.
Honestly, the biggest advantage of getters/setters is mocking (making test harnesses) and putting a breakpoint at access/modification. The costs in terms of code bulk and the like are real, and having more of the code you write not be boilerplate has value.
So a width/height field on a non-"live" rendered rect? Default to public data. A buffer used to store the data in a hand written optional<T>? Private data, and accessors.
Accessors should be used to reduce your own (or the code reader's) cognitive load. Write code with a purpose, and don't write code that doesn't have a purpose.
Now you'll still want to know how to write getters/setters, so practicing on stupid "rect width/height" cases has value. And learning the LSP problem that while a ReadOnly square is a kind of ReadOnly rect, a ReadWrite square is not a kind of ReadWrite rectangle might be best done via experience (or maybe not, as so many people experience it but don't learn the lesson).
This pertains to the principle of encapsulation where exposing internals means, from the perspective of the class in question ("you"):
You have no control over what is written to these fields
You are not notified if these fields are accessed
You are not notified if these fields are changed
You can never trust that the values are valid
You cannot change the types of these values without impacting any code that uses them
When you encapsulate you control access to these properties meaning:
You can prevent alterations
You can validate before writing, and reject invalid values
You can change the internal representation without consequence, provided the get/set functions still behave the same way
You can clean up the values before they are written
You have confidence that at all times the values are valid since you are the gatekeeper
You can layer additional behaviour on before or after changes have been made, such as the observer pattern
This is not to say you must use encapsulation all the time. There are many cases when you want "dumb data" that doesn't do anything fancy, it's just a container for passing things around.
In C++ this often leads to the use of struct as "dumb data" since all fields are public by default, and class as "smart data" as the fields are private by default, even though apart from the access defaults these two things are largely interchangeable.

What is the difference between abstraction and interface? [closed]

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 6 years ago.
Improve this question
I found the following definitions from the internet and both sound similar to me :
Abstraction : Abstraction is another good feature of OOPS. Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.
Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
So abstraction says expose only the details which are concern with the user (client) of your object. So the client who is using your class need not to be aware of the inner details like how you class do the operations? He needs to know just few details. This certainly helps in reusability of the code.
Interface : An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X". Again, as an example, anything that "ACTS LIKE" a light, should have a turn_on() method and a turn_off() method. The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.
Interfaces in Object Oriented Programming Languages
An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a scooter class and a truck class. Each of these three classes should have a start_engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start_engine action is the domain of the interface.
Doesn't both the explanations say the same thing? So are they same or different?
An interface tells you what you can do with something. Abstract(ion) might additionally tell you how you do some of these. Thus an interface is always a kind of abstraction, but an abstraction can carry more information than an interface.
In C++-world, unlike e.g. Java, there's no explicit declaration of an interface; instead, your class automatically provides all the interfaces that the base classes provide. Some of us tend to call classes with only pure virtual methods (and, possibly, a non-pure virtual destructor) and interface. Note that, strictly speaking, it's not the only way do specify an interface and new/upcoming C++ features (like Concepts) will likely change this scene. Similarly we usually say that a class is abstract when it has at least one pure virtual method, albeit there might be different definitions when you use template/traits based composition and fulfilling and interface instead of virtuals and inheritance for the same.
Abstraction is to move away from the details, to 'zoom out', if you will. You tend to abstract away from the implementation by creating structures to lay out your code. As an example, rather than thinking in terms of individual cells in a body, you could abstract away to thinking about the person as a whole, or go even further and think about groups of people.
An interface is just that; how you interface with your code. This is normally in the form of public functions in your classes, though not necessarily. Ideally, the interface should describe what something can do, without being affected by how it does it. For example, you might have a function to get a person to walk, but not one to move their individual muscles.
In the context of , say, a C++ function:
The interface describes how a feature is used which is what a function prototype does.
A client calling the function need not worry how the function is implemented (ie how it go about doing things). In short you have a layer of abstraction.

C++ metaprogramming,why and when should be used? [closed]

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 7 years ago.
Improve this question
I am reading Abrahams,Gurtovoy book about C++ metaprogramming. I must admit that I do not understand properly there explanation for using template metaprogramming. For example:
You want the code to be expressed in terms of the abstractions of the problem domain.
Or:
You would otherwise have to write a great deal of boilerplate implementation code.
Could someone elaborate on this?
I too use C++ for scientific computing and, yes, template meta-programming comes in very helpful. One use is to help with implementations of general purpose numerical methods. A typical example is std::sort, which is an abstraction of sorting in such a way that it works for whatever you want to sort.
Similarly, you may write, say, a templated spline interpolation that can interpolate y(x) for any type x that implements the concept of a scalar (orderable, operators + - *) and type y that is interpolateable (allows y+y, y-y, y*x). Once you have established such a template, you can use it to interpolate, say, some matrix type over a double (representing time, for instance) without any further adaptations: it just works immediately (the compiler must do some work, though).
You want the code to be expressed in terms of the abstractions of the problem domain.
Template Metaprogramming (TMP) can be used to separate and abstract different tasks in your code. For example, Boost.Serialization is implemented so as to be completely agnostic of your (the user's) code. You just have to provide a bit of glue, in the form of a serialize() member function, and Boost.Serialize will be able to work with your class seamlessly. And since this is all at compile-time, this flexibility does not come at any runtime cost (as opposed to polymorphism).
You would otherwise have to write a great deal of boilerplate implementation code.
TMP techniques can be used to generate code, and to efficiently factorize common code. For example, Boost.Intrusive lets you "import" behaviour in your classes (by various means, such as inheritance or type traits), and that is nothing else than generating code and injecting it into your class to transform it into, for example, a list node.

How to modularize a large factory class? [closed]

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.

Signal/Slot vs. direct function calls [closed]

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 6 years ago.
Improve this question
So I have starting to learn Qt 4.5 and found the Signal/Slot mechanism to be of help. However, now I find myself to be considering two types of architecture.
This is the one I would use
class IDataBlock
{
public:
virtual void updateBlock(std::string& someData) = 0;
}
class Updater
{
private:
void updateData(IDataBlock &someblock)
{
....
someblock.updateBlock(data);
....
}
}
Note: code inlined for brevity.
Now with signals I could just
void Updater::updateData()
{
...
emit updatedData(data);
}
This is cleaner, reduces the need of an interface, but should I do it just because I could? The first block of code requires more typing and more classes, but it shows a relationship. With the second block of code, everything is more "formless". Which one is more desirable, and if it is a case-by-case basis, what are the guidelines?
Emmitting a signal costs few switches and some additional function calls (depending on what and how is connected), but overhead should be minimal.
Provider of a signal has no control over who its clients are and even if they all actually got the signal by the time emit returns.
This is very convenient and allows complete decoupling, but can also lead to problems when order of execution matters or when you want to return something.
Never pass in pointers to temporary data (unless you know exactly what you are doing and even then...). If you must, pass address of your member variable -- Qt provides a way to delay destruction of object untill after all events for it are processed.
Signals also might requre event loop to be running (unless connection is direct I think).
Overall they make a lot of sense in event driven applications (actually it quickly becomes very annoying without them).
If you already using Qt in a project, definitely use them. If dependency on Qt is unacceptable, boost has a similar mechanism.
There is another difference. #1 is hard coupled to the IDataBlock interface, and the Updater class needs to know about "someblock". #2 can be late-coupled via a connect call (or several, including disconnects), which leads to a more dynamic approach. #2 acts like a message (think Smalltalk/ObjC) and not a call (think C/C++). Messages can also be subject to multiple dispatch, which requires hand implementing that feature in #1.
My preference would be to utilize signals/slots due to their flexibility, unless code performance or the need for immediate return data does not allow for it (or the dependence on Qt is not desirable).
The two forms may appear to be similar. Functionally, that is true. In practice, you are solving a larger problem. In those cases, external circumstances will cause these two soltuions to be not equivalent.
A common case is figuring out the relation between source and sink. Do they even know each other? In your first example, updateData() needs to have the sink passed in. But what if the trigger is a GUI button [Update Data] ? Pushbuttons are generic components and shouldn't know about IDataBlock.
A solution is of course to add a m_someblock member to Updater. The pushbutton would now update whatever member is in Updater. But is this really what you intended?