Inheritance Pattern [closed] - c++

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 am finding my naming conventions rather bothersome. I seem to be re-using the child specific names too much. In my Example below, I have a Widget which has-a Connection which has-a Config. Each of these objects has specialized classes for Foo and Bar types.
So my FooWidget has-a Foo-Connection which has-a Foo-Config. The same for Bar. In C++ I've ended up with nine different header files.
widget.h
connection.h
config.h
foo_widget.h
foo_connection.h
foo_config.h
bar_widget.h
bar_connection.h
bar_config.h
I cant help but look at this a feel like it isn't right. My instincts tell me something needs to be changed. It's like there is a design pattern somewhere to be taken advantage of. But I can't find a better solution.
So I guess my question is the following: Is there a design pattern that will improve this design?
-- I am having difficulty wording my question correctly. Please excuse me, I will update as the question itself becomes more clear.

I don't think there is anything wrong with the structure of your classes but without seeing what these classes do it is going to be hard to give advice on how to improve your design.
I think it is good style to have one header file per class. It makes things easier to find and you can easily use directories (or filters in your IDE) to organise your files. For example you may find it easier to structure your files:
|--Foo
|--foo_widget.h
|--foo_connection.h
|--foo_config.h
|--Bar
|--bar_widget.h
|--bar_connnection.h
|--bar_config.h
|--widget.h
|--connection.h
|--config.h

First of all, there's nothing wrong with doing things that way. Many like to put one class per header, in general. If you don't like looking at so many headers you might organize them by directory, or project tree filter, etc.
This is all a question of style. As long as functionality is untouched, the best option is a function of that funny feeling you have, and same for the folks supporting your code down the road. Maybe this answer can make that funny feeling go down for you, or maybe not.
Second, this very much depends on the use of each class. If the Foo and Bar classes are small, they can be put in the header that contains the encapsulating class. Perhaps add a forward declaration for the sake of the parent class, and finish declaring it at the bottom of the header. Bonus points if they're all related (for example FooConnection is a subclass of Foo) because this shortens declaration space.
If they're relatively small classes, there may be no harm in declaring the Foo and Bar classes within the definition their base class. Then there is no FooConnection--it's actually a Connection::FooConnection. In this case Connection doesn't just define the base for FooConnection, it owns its very definition. That means every time you use a FooConnection in your code, you are thinking in the context of a Connection. I rarely do this myself, primarily because I don't like typing Connection:: all the time, but also because there are so few cases where I only use a class in one context.
If the encapsulated classes are protected or private, then they're only used by the parent class itself (and friend classes and maybe subclasses, what have you). Then, since limited context is established, and if the class declarations are small (<50 or <100 lines), you can declare FooConnection and BarConnection within Connection and still maintain readability.
Bonus point: if you do end up declaring classes inside classes, you might take advantage of namespace separation. I don't know the uses of these classes, but I'm guessing FooConnection isn't a connection itself, but a Foo that belongs to a Collection. So then you might declare a Foo and a Bar class for each of Widget, Connection, and Config.

Related

Is it good practice to declare derivate classes in the same C++ header? [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 last year.
Improve this question
I'm declaring a pure virtual class that will provide a unified interface for a handful of derived classes. My instinctual way to organize this would be to create a base folder with the header for the base class (e.g lib/Base.h) and then create subfolders for the header + source file of the derived classes (so lib/implA/ImplA.h,lib/implA/ImplA.cpp and so forth). This keeps the files short, but feels cluttered.
Would it be considered good practice to gather the definitions of the derived classes in the header lib/Base.h and keep the various implementations in the same folder?
It is neither good nor bad. What matters is what you want to present as an API, that is what a user or your classes will have to write in their own sources. #include "lib/implA/ImplA.h" uses 2 directory level which is not very common while not being too much either IMHO. It can makes sense if a single application will seldom use more than one implementation.
For the way you want to organize your headers and translation units, it is really a question of having reasonable sizes. And the magnitude order may vary between teams...
Two-file folders (like lib/implA/ImplA.h, lib/implA/ImplA.cpp) are unnecessary, for small projects people usually just put everything in lib/. If lib/ becomes too cluttered, put this whole hierarchy in lib/my_hierarchy/Base.h, lib/my_hierarchy/ImplA.cpp, etc. Maybe extract a logical subsystem instead of a hierarchy. Just keep reasonable folder sizes and some organized structure.
As for putting multiple declarations in the same header, it's your design choice. As far as I know, there's no single "best practice" in C++ regarding this. C++ doesn't enforce one class per file, like Java does. However, including a lot of classes in a single header means slightly longer compilation times for users, because that long header needs to be parsed in every .cpp file where it's #included. Usually people try to keep their headers minimal, but also provide a convenience "aggregate" header that includes all other headers (like bits/stdc++.h for the standard library). In your case, that would be:
// lib/lib.h
#include "my_hierarchy/Base.h"
#include "my_hierarchy/ImplA.h"
// etc.
So that users who don't mind longer compilation times can just #include <lib/lib.h> and have everything, while others can #include only classes they need.

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.

Does the inheritance of opencv functions make my program better? [closed]

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 have a program that uses opencv functions such as calibratecamera. Now I am working on the final version of my code, and I was wondering if instead of calling opencv's functions I inherit them in my classes would make my program 'better' ?
As pointed out in the comments, your question is very "general" and somehow confused. However, there is a general answer to the question "is it better to inherit?". Of course, being a general answer, it is oversimplified and might not apply to your case.
Item 58 in "C++ Coding Standards" (Sutter, Alexandrescu), is titled
Prefer composition to inheritance
You can find similar advice in several other books too.
The reason they give for making their case is:
Avoid inheritance taxes: Inheritance is the second-tightest coupling relationship in
C++, second only to friendship. Tight coupling is undesirable and should be
avoided where possible. Therefore, prefer composition to inheritance unless you
know that the latter truly benefits your design.
So, the general advise is to try and avoid inheritance as much as possible, and always being conservative on using it, unless you have a very strong case for it. For instance, you have a case for the use of public inheritance if you are modelling the so called "is-a" relationship. On the other hand, you have a case for using nonpublic inheritance if you are in one of the following situations:
If you need to override a virtual function
If you need access to a protected member
or in other less frequent cases.
Whatever your final choice is, be sure to only inherit from classes that have been designed in order to be base classes. For instance, be sure that the base class destructor is virtual. As the cited book poses it:
Using a standalone class as a base is a serious design error and
should be avoided. To add behavior, prefer to add nonmem-ber
functions instead of member functions (see Item 44). To add state,
prefer composition instead of inheritance (see Item 34). Avoid
inheriting from concrete base classes
OpenCV is a library with well defined API. If you have an existing application that uses functions bundled within this library and you don't have a valid reason for adding an additional functionality to them, there is no advantage that you could gain by wrapping them.
If you want to change the interface because you think it will make your code cleaner, I would worry about the maintenance in case the API will change in the future.
While changing the design of your applications, your decisions should be based on specific reasons. "I want to make my program better" is too abstract one.

C++ Conventions: Structure of Headers and Classes [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 9 years ago.
Improve this question
Well, this is a pretty trivial question. But i'd like to know if it is okay to put multiple classes into one header / source file. I've often enough seen that for every class there is another header and another source file, like it is in Java (not only by Convention...)
I see the ups and downs here: on the one hand you might want to have some relevant classes on one place for editing, since big projects sometimes require you to search a bit for them. On the other hand, more files make single files less heavy, so you don't have to scroll down tousands of lines to get to the method you're searching.
Now what do the Conventions say about that?
[Example]
At the moment i have 3 classes in one file: a Server, A ClientHandler for the Server and a ServerManager.
The server manages the connections, the ClientHandler manages all in- and outgoing traffic for each client and the ServerManager contains some logic i need to run the Server.
[Edit] be gentle with my abilities of the english language, i'm foreign ;)
It's considered good form for each class to have its own header/implementation pair.
The most compelling reason (for me) is that the files are named after the class they contain. This makes it easy to find the correct file for a declaration in the code. If a file has more than one type in it, it becomes harder to name, and therefore harder to maintain.
However, sometimes it's not so clear cut. A "main" class might have some other supporting class that's definitely part of its interface (in the Herb Sutter sense of interface), but doesn't rightly belong as a nested type. This should be rare, but such a case might justify having more than one class per file.
If you've gone to the trouble of abstracting out concepts (such as in the example you give), why not go the extra little bit and put them in their own files? You will thank yourself for it down the line!
There's no real rule, other than common sense. If two classes
are closely linked, it's common to put them in the same header.
And of course, not everything in C++ is a class; free functions
may be grouped in various different headers according to
whatever seems most logical.
Also, there isn't always a one-to-one relationship between
headers and source files. If your class is a template, there
may not be a source file at all. On the other hand, if you're
writing a library that will be widely used, and the class isn't
polymorphic, you'll probably want to put each function in
a separate source file.
And a lot of classes are defined directly in source files, and not in headers.

Is nesting namespaces an overkill? [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 5 years ago.
Improve this question
I'm writing a C++ program that has a large number of classes. In my head I can visualise them as distinct collections. For example there's a collection of classes for reading and storing config data, and another collection for drawing a user interface with various widgets.
Each of those collections could be neatly stored inside separate namespaces, which seems sensible. The config part has a "screen" class, and the GUI part also has a "screen" class, but they are different to each other. I could rename one "gui_screen" and the other "config_screen", but that's the point of a namespace isn't it? To remove these prefixes we invent to separate things.
Part of me then thinks it'd be tidy to store those namespaces inside one main one so that none of my code can interfere with the namespaces of anything else. And I suppose it might also make the code more readable too.
Or am I just making overly complex hierarchies of data for no reason at all?
If you're having namespaces with common names such as "gui" and "config", and it's possible that your code may in the future be part of a library meant to be linked with other code not under your control, it might indeed be a good idea to nest all of "your" namespaces into a single named one (which probably should have no other content except the nested namespaces) which identifies them as "yours". There is really no penalty for doing so, especially if, as you think, it can be done in a way that helps readability. (That's quite different from deep nested hierarchies of class inheritance, which can definitely hamper clarity, as different functionality is added at each layer and a reader or maintainer of the code has to be jumping around among many files to see or change what's added where!-)
No, IMO you're not overdoing at all.
And resist the temptation to use using declarations or (heaven forbid!) using directives! It takes very little getting used to always typing all namespaces and, once you're used to it, it makes the code much easier to read and understand. ("Which screen type is this again, gui or config?")
Personally I've never seen more than two levels of namespace nesting that was at all meaningful or useful. What you've described sounds fine, but I wouldn't go any deeper than project::component unless you've got a tangible, demonstrable, "this breaks without it" reason to do so. In other words, foo::bar::screen is reasonable, foo::bar::ui::screen is highly questionable, and anything more than that almost certainly introduces more complexity than is justified.
It is not overkill. It is reasonable to nest your namespaces, e.g. piku::gui::screen etc.
You could also collapse them to piku_gui_screen, but with the separate, nested namespaces you get the advantage that, if you're inside piku::gui, you can access all names in that namespace easily (e.g. screen will automatically resolve to piku::gui::screen).
Defining namespaces you are not doing any hierarchy, so I don't see what the problem is, anyway namespace are there just to solve your very problem.
I personally love to group files/classes by their functionality. I normally start with a folder with a name that matches the namespace I will use. Eventually if a namespace needs to be reused in another application, you can easily take it out and build it into it's own dll and share it.
It also makes for nice intellisense so that when I'm drilling down through namespaces, I can see just the classes that are part of that group of functionality.
It seems to me that one namespace per developer ought to be enough -- you (presumably) have control over all the type names you define in your own code, and it's unlikely that you'll want to use the same type name for different types within the same project.
I think the main use of namespaces is to handle the case where two independent developers happened to choose the same type name -- without namespaces you'd have no way to use both developers' code in the same project. Multiple namespaces within a single developer's codebase, OTOH, just add complexity and typing overhead, with little or no compensating benefit.
All IMHO, of course.