What is the difference between abstraction and interface? [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 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.

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.

Inheritance Pattern [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 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.

What are the benfits of inheritance over template based data structures? [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
I'll get to the point and explain below.
What, if any, are the benefits of...
template<class T>
class myStack : public myList<T>...// my stack
over
template<class T, Container = deque<T> >
class stack...// C++ stack
Recently I was writing some code and was faced with an inheritance issue where I was exposing aspects of the base class that I would rather not. The specific example isn't important so I'll relate it to few semesters ago when I took a data structures class where we implemented our own list, stack, queue and others.
In this class we were to design a stack which was to inherit from a list. The problem with this was I was exposing public methods of the base that could potentially damage the stack's integrity. It may be that I'm a bit of a purist but having the insert() and remove() lying around in the stack was bothersome for me. I didn't have time to investigate it then but this time I thought I would consult the C++ standard to see how the stack was defined there. Low and behold I found the code above; it was an obvious solution that I overlooked.
Here's my view...
The C++ implementation is "better" because it allows the user the freedom to choose the underlying structure if desired and maintains a more pure stack in that it is clear only stack functionality available to the user and can be more guarded from unintended corruption. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
The obvious benefit of mine is code re-use which is par for the course, I don't see that as an additional benefit the way I personally see the benefit of the freedom with the C++ implementation. I do see the over exposure (my words) of the base class as a con though. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
Again, I'm not concerned with languages, I'm more concerned with weighing the pros/cons for my own designs.
C++ collections and Java collections are very different. Java collections have an obvious type hierarchy, whereas most C++ collection types do not extend any other class, and templates are extensively used to support multiple collection types.
Although I don't know for sure, I imagine that the Java library developers made Stack a subclass of Vector because a stack is a collection of elements in a well defined order, so acts like a list, and by subclassing Vector they could get most of the implementation of the stack for free. This also has the benefit that you can use stacks in places where you need a list or a vector, for example you could pass a stack to a function that takes a list and iterates over it. Of course, c++ stacks are not iterable, so there is (intentianal or not) a very different semantics between the two stacks.
Finally, for your own code, if you are considering whether B should inherit or contain A, first ask yourself if B is an A, or more specifically, if you would ever want to treat a B as an A by passing it to a function that expects an A, or returning it from a function that needs to return an A. If so you should use inheritance, otherwise you should probably use composition.
The Stack class, as well as Vector, are legacy containers. They are left-overs of JDK1.0, they are based on an older design of the utils library, and are inefficient because of synchronization.
The preferred implementation of Stack in Java is given by implementations of the Deque interface (mainly ArrayDeque and LinkedList). You get the difference: in C++ one says that an stack has a given implementation. In Java one declares a class implementing the desired interface:
class ArrayDeque<E> extends AbstractCollection<E>
implements Collection<E>, Deque<E>, Queue<E> //etc
When using such classes, always take the less specialized interface possible, for instance:
Deque<String> stack = new LinkedList<String>();

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.

What is the best way to arrange this classes? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm doing a simple project to manage data for a tabletop game, but I'm mostly using it to get experience about correct coding.
I've just reached a point where I have five classes that are tightly coupled, and I'm not sure whether leaving the whole thing as it is, or refactoring.
What I have is basically this:
class ShipTemplate: This class ( that has nothing to do with c++ templates ) has all constant members and contains basic informations about a category of Ships.
class TemplateSet: This class contains all ShipTemplates that are currently available to build, and it has a name. It should be stand-alone, since it represents the available technology of each player at any time, so one would be able to save/load different sets at different times.
class Ship: This class represents a complete ship, with loadouts, name and other things. It contains a const reference to a ShipTemplate, which the class is not allowed to change, to refer to its basic functionality. It could extend ShipTemplate, but I wanted to keep track of which Ships had a particular underlying ShipTemplate, and it seemed easier doing it like this.
class Fleet: This class contains a list of Ships, it has a name and contains other information. It should contain a cost variable equal to the sum of the cost of all Ships in it.
class Deployment: This class contains pointers to all the Ships, Fleets, and TemplateSets available to the player. It also needs to keep track of ShipTemplates that are no longer available, but that are still used by already built Ships. It should contain a cost variable equal to the sum of the cost of all Ships available to the Player. It has to manage the transfer of Ships from one Fleet to another. It has to find out which Ships are within a given Fleet, or which Ships have a given ShipTemplate.
Unfortunately every class is pretty interwined with all the others. I thought about different approaches, but I'm not sure if even one of them is the correct one.
Use friend statements all over the place, so that if one class modifies something, it can correctly update all the others.
Use very long names, like Deployment::modifyShipThrustInFleet, and allow any modification solely through the Deployment class, which will take care of everything.
Remove TemplateSets and Fleets and represent them within Deployment, so that it can update correctly cost values/pointers without breaking any "correctness" rule. This too implies that every modification to the system has to pass through Deployment.
Insert into lower classes pointers to upper classes, so for example when changing something in a Ship it can automatically update costs of both its Deployment and Fleet.
Is there some other solution I didn't see, or maybe a refactor into more classes that can help me achieve readable, mantainable code?
Just some thoughts.
When thinking in object oriented way, thinking about real-life objects lays out the view, what you should describe in program. And what is object in real-life? It is a "thing" which has certain features and exposes some functionality.
For example ShipTemplate is a blue-print of the ship. It should define size, layout, part types and quantities (DieselEngine, SteamEngine, AntiAircraftGun, UnderwaterMines, etc), and how they are connected with each other.
Ship on the other had is constructed according to blueprint - it should have all part instances. For example it might have two DieselEngines and three AntiAircraftGuns. And it is correct, that ship does not inherit from blueprint. Blueprint is only a description of ship, not it's parent.
Now, each type of the object (blueprint, part, ship) has it's own properties and functionality. For example, each engine consumes some amount of fuel and can increase speed of the ship to some value. Why not have base class for Engine, which has these features? (inheritance). The same goes for the guns (lets call it ShipWeapon). There is of course a big difference between mine-gun and anti-aircraft gun, but they are both guns, they are both mountable on the ship, they both have weight, ammo type, reload time, ammo capacity, whether gun is operating.
So these are some properties of the objects. What about functionality? Other important concept of OO design is that each object has (encapsulated) some functions which can be done with it (and it may or may not alter objects state). For example ShipWeapon should have method Fire(), which maybe should decrees amount of ammo in it. Or try to target at first with Aim(sometarget). Engine on the other hand would have Start(), Stop(), SetSpeed(speed). Note that these would work internally on the object and it's state. Ship might have SetCourse(direction, speed), which would start it's engines at required power and orient its rudder. Also ship might have Colide(ship). And Hit(typeofattackinggun), which would iterate through all parts of ship and damage some randomly (and set IsOperating for a gun, or turn off one of the engines, etc.)
As you can see you can go into a lot of detail while designing OO approach. Its also very good to know when to stop - just how much detail (or accuracy) you really need for you program to work.
Also, there could be a global World, which would hold all ships. And so on..
There is other part of program, the infrastructure. How you data objects (ships, worlds, players) are managed, how they know and interact with each other. For example each ship as an object can be observed by global map and each ship would notify it about movement (observer pattern). Or global world would query state of each ship at some time intervals, based on global clock. Or...
I guess what I was trying to say is to stick to main OO principles - encapsulation, inheritance, polymorphism. And there is a lot of literature out there for object-oriented design, design patterns, etc., which is useful. Wiki entry is a bit "academic" but has main definitions, which make you think :) Also look at SOLID
PS. And it is usually a sign of a bad design to do everything in a single class.
Now that you have described haw you want to represent the various data, before defining the complete relations, try to complete the description by defining the "protocols":
What can each class be able to do to the others? WHat methods and rules between methods are needed to achieve your goal?
Once you have defined how classes act on each other you will most likely discover what is candidate to be private, what is public and what level of friendship must exist between the parties.
May be is not your case, but -usually- when complex relations exist, one possible pattern can be the use of a "communication bus class", that expose the action that can be "sent" to the various object, each having a private interface and being friend of ... the bus itself (an only the bus).
EDIT
Following Svalorzen comment:
It depends on the side you are watching it.
This will, in fact, introduce multiple level of "privacy", allowing to implement encapsulation on a wider unit that the class itself. Whether this is good or bad is a matter of context, not idiom.
Instead of having just classes with everything private (for no-one else) or public (for anyone), you have a "capsule" that is a "club" (the "club of the classes having 'bus' as a friend") and a "club manager" the is the real "filter towards the public" (and hence the real OOP object), allowing certain methods that need to interact with more classes private parts at a same time, to do that inside the club only.
The deny of "friendship" is nothing more than a misconception that confuse techniques with tools, making OOP objects the same as C++ classes. That's -generally speaking- a FASLE IDIOM. C++ classes can be smaller units than OOP objects (think to the pimpl idiom: what is the "object" there?).
The fact that a class can be a friend of another doesn't make it a friend of anyone, hence the private parts are not made public. You are just defining another level of privacy where encapsulation apply the same as with "private". It just apply on a wider group. That "wider group" plays, respect to OOP, the same role a non-friend class plays.
The misconception that "friend breaks encapsulation" has nothing to do with the concept of OOP. It has to do with the way OOP has been implemented in Java, that is a completely different language respect to C++. In C++ friendsip is just a construct to "group thimgs together" just like class, struct, templates, inheritance, membership etc.
What OOP relation (composition, inheritance, linking...) has to be mapped to what C++ construct, unlike in java, when the language philosophy is defined to be one-way only, is not defined by the language itself and by it's standard library.
The mapping "OOP object = C++ class" is just a common cultural misconception inherited from the past, when C++ has no templates, no lambdas, no friendship, nothing more than classes (and was in fact called "C with classes") when the only way to implement an OOP hierarchy was through classes,since that was the only way to create a hierarchy relation using that time c++ constructs.
Nowadays I can even implement an OOP system using C++ members and implicit conversion for "OOP inheritance" and C++ private inheritance for "OOP membership". Or I can implement an OOP object with a "cluster of classes (or mat be labdas)", defining its run-time behavior (think to std::locale and related facets).
Starting a design with the OOP object == C++ classes idioms is in fact cutting away two degrees of freedom C++ adds to program design, restricting your mind to what C++ was more than ten years ago.