I have previously asked about the proper way of accessing member variables present in the project. In the project, I have CWinapp-derived class, CMainFrm class, a list of different view classes. However, currently, I have instances of different user-defined classes instantiated in the CWinApp-derived class, while the rest of the classes use a pointer obtained from AfxGetApp() function, and then access the different user-defined classes. I was told by some community members on the MFC newsgroup that this is a very bad design (i.e. the parent should not know anything about an app-class, view class, or document class). However, I'm not sure how otherwise I can access various user-defined classes without using this design. It would be great to hear some suggestions as I'm not familiar enough with MFC to come up with proper search terms.
"(i.e. the parent should not know anything about an app-class, view class, or document class)"
I'm not sure I understand this sentence, what do you mean with 'parent' here?
Anyway, in my opinion, the design you describe isn't really a problem. It's a trade off: do you either pass these classes to all functions that need them, complicating their use and API, or do you store them as a sort of global variables like you're doing? It depends on the data that is accessed, and how often. Data that is needed in many places can just as well be 'global'.
There are multiple ways of making data 'global': make it a member of CWinApp (that is, your CWinApp-derived class), or of CMainFrame, or do you make an actual 'global variable', or do you make a singleton, ...
The problem with global variables is that it becomes hard to figure out who accesses it when and from where. If you data as a member of CWinApp, you can access it through an accessor function and trace access from there (through log messages, break point, ...) This, in my opinion, mitigates most of the problems associated with global variables. What I usually do nowadays is use a Loki singleton.
The reason that is stated in your post for not making data a member of CWinApp, as a decoupling issue, is (in the context that you've presented it) a bit strange imo. If certain classes need access, they'll need to know of those data structures anyway, and their storage location is irrelevant. Maybe it's just because I don't know about the specifics of your design.
Related
I've heard people saying that having protected members kind of breaks the point of encapsulation and is not the best practice, one should design the program such that derived classes will not need to have access to private base class members.
An example situation
Now, imagine the following scenario, a simple 8bit game, we have bunch of different objects, such as, regular boxes act as obstacles, spikes, coins, moving platforms etc. List can go on.
All of them have x and y coordinates, a rectangle that specifies size of the object, and collision box, and a texture. Also they can share functions like setting position, rendering, loading the texture, checking for collision etc.
But some of them also need to modify base members, e.g. boxes can be pushed around so they might need a move function, some objects may be moving by themselves or maybe some blocks change texture in-game.
Therefore a base class like object can really come in handy, but that would either require ton of getters - setters or having private members to be protected instead. Either way, compromises encapsulation.
Given the anecdotal context, which would be a better practice:
1. Have a common base class with shared functions and members, declared as protected. Be able to use common functions, pass the reference of base class to non-member functions which only needs to access shared properties. But compromise encapsulation.
2. Have a separate class for each, declare the member variables as private and don't compromise encapsulation.
3. A better way that I couldn't have thought.
I don't think encapsulation is highly vital and probably way to go for that anecdote would be just having protected members, but my goal with this question is writing a well practiced, standard code, rather than solving that specific problem.
Thanks in advance.
First off, I'm going to start by saying there is not a one-size fits all answer to design. Different problems require different solutions; however there are design patterns that often may be more maintainable over time than others.
Indeed, a lot of suggestions for design make them better in a team environment -- but good practices are also useful for solo projects as well so that it can be easier to understand and change in the future.
Sometimes the person who needs to understand your code will be you, a year from now -- so keep that in mind😊
I've heard people saying that having protected members kind of breaks the point of encapsulation
Like any tool, it can be misused; but there is nothing about protected access that inherently breaks encapsulation.
What defines the encapsulation of your object is the intended projected API surface area. Sometimes, that protected member is logically part of the surface-area -- and this is perfectly valid.
If misused, protected members can give clients access to mutable members that may break a class's intended invariants -- which would be bad. An example of this would be if you were able to derive a class exposing a rectangle, and were able to set the width/height to a negative value. Functions in the base class, such as compute_area could suddenly yield wrong values -- and cause cascading failures that should otherwise have been guarded against by better encapsulated.
As for the design of your example in question:
Base classes are not necessarily a bad thing, but can easily be overused and can lead to "god" classes that unintentionally expose too much functionality in an effort to share logic. Over time this can become a maintenance burden and just an overall confusing mess.
Your example sounds better suited to composition, with some smaller interfaces:
Things like a point and a vector type would be base-types to produce higher-order compositions like rectangle.
This could then be composed together to create a model which handles general (logical) objects in 2D space that have collision.
intersection/collision logic can be handled from an outside utility class
Rendering can be handled from a renderable interface, where any class that needs to render extends from this interface.
intersection handling logic can be handled by an intersectable interface, which determines behaviors of an object on intersection (this effectively abstracts each of the game objects into raw behaviors)
etc
encapsulation is not a security thing, its a neatness thing (and hence a supportability, readability ..). you have to assume that people deriving classes are basically sensible. They are after all writing programs either of their own using your base classes (so who cares), or they are writing in a team with you
The primary purpose of "encapsulation" in object-oriented programming is to limit direct access to data in order to minimize dependencies, and where dependencies must exist, to express those in terms of functions not data.
This is ties in with Design by Contract where you allow "public" access to certain functions and reserve the right to modify others arbitrarily, at any time, for any reason, even to the point of removing them, by expressing those as "protected".
That is, you could have a game object like:
class Enemy {
public:
int getHealth() const;
}
Where the getHealth() function returns an int value expressing the health. How does it derive this value? It's not for the caller to know or care. Maybe it's byte 9 of a binary packet you just received. Maybe it's a string from a JSON object. It doesn't matter.
Most importantly because it doesn't matter you're free to change how getHealth() works internally without breaking any code that's dependent on it.
However, if you're exposing a public int health property that opens up a whole world of problems. What if that is manipulated incorrectly? What if it's set to an invalid value? How do you trap access to that property being manipulated?
It's much easier when you have setHealth(const int health) where you can do things like:
clamp it to a particular range
trigger an event when it exceeds certain bounds
update a saved game state
transmit an update over the network
hook in other "observers" which might need to know when that value is manipulated
None of those things are easily implemented without encapsulation.
protected is not just a "get off my lawn" thing, it's an important tool to ensure that your implementation is used correctly and as intended.
I have a connection manager which currently has a static reference to a class which is kept inside the connection manager in the private section of the class. A pointer to this class is passed to all connections and they can use it for utility purposes.
Now this class pointer is not immediately useful to the childs, but it is useful for the childs own children, so all that happens is that it's passed along.
Now I'm wondering that since there is only ever 1 instance of this utility class should I bother with all this passing around of the pointer, or would it be better to make the class a singleton and each class that requires it can simply use a static getInstance() method instead. This would mean that classes that don't care about it don't need to know about it.
There are lots of types of connections (30+) and none of them care about the utility class.
However, they will use classes (at the moment, just 2) that do care about the utility class.
I'm not sure if every type of connection should burden itself with something it doesn't care about, just for the sake of a couple of classes that it (may) use.
Singletons and static fields are generally considered evil. Why is it static anyway? It could happen so one day you'll need each connection manager to have its own reference.
The best idea I can think of is to make the reference non-static first. Then, forget about using the singletons. From this point you should start to think how to implement this in the most elegant way.
I don't know the nature of your class, but it sounds reasonable to me that each connection should have a reference (or a pointer) to the connection manager that manages it. Just in case.
Then, the connection manager should probably provide a getter for anyone who wants to access that utility class. Connections themselves should pass along either the reference to the connection manager or to the utility class depending on what makes more sense.
It also makes sense to pass the reference to the connection manager to the constructor of the common ancestor of the connections, if there is one (which it should be). This way, you no longer have 30+ classes that refer to something they don't really need, but just one abstract class that they are based upon.
And if you really want to do something singleton-like, then it's better to have a kind of static method with a parameter that returns the reference, as opposed to just a static method:
static UtilityClass *getInstance(int id);
// not static UtilityClass *getInstance();
Even if you don't use the id parameter right now, it may get very useful later, when you need multiple instances. You could have some sort of table or hash map that maps the id to the instance. You can even add a method that creates or replaces the instance for a specific id, which could be very useful for unit testing. Note that this approach still has at least the following disadvantages of the singleton pattern:
It is prone to various threading problems.
It still hides dependencies of your classes: that is, you can't say what a class uses just by looking at its API.
It is hard to give more advices without looking at the code.
If I understand you correctly, at the top layer there is a Connection Manager. It contains a static class which is useful later on.
The next layer down are many instances of a class which exists to service each of the connections managed by the aforementioned manager.
Each one of those may in turn use some instances of utility classes which would like access to information from the Connection Manager (in this case you've wrapped it up as the static object).
The question is how best should the 3rd layer down should gain access to the Connection Manager's contained information.
I'll call them: Manager (contains 'static class') -> Connection -> Utility
My suggestion would be to have the Connections take references to the Manager which owns them. They can't or shouldn't exist without it and they are managed by it. They in turn need to construct objects that need a specific bit of information from the Connection Manager (the static class contained within).
So when the Connection's construct the Utility classes, the Utility classes will require only the bit of information they need to operate (in this case a reference parameter for a class which happens to be static inside the Manager). They should take this by reference also. The Connection has the Manager class reference and is able to provide the constructor for the Utility the bit of information it needs to operate.
The reason I am suggesting this approach is:
Connections/Utility classes don't care whether the manager is a singleton (opens possibilities later if you need multiple managers)
Utility doesnt care whether static class is static. They only need a reference to a specific class they need.
Manager decides how it or its contained data needs to be allocated.
Lastly:
The only class which has reason to know about the other two main classes is the Connections class. It seems reasonable it might know which manager is managing it (and therefore some interface information). It also knows what the Utility classes it will require and what they will need in terms of construction params and other interface requirements.
To set this up there may be some funkiness with includes and classes may have to expose interfaces to each other but thats just standard fare anyway.
My 2c.
Singleton vs. Static
A good example of singleton usage: you wish only one instance to be running for a class, for example a texture manager, shader manager, connection pool manager etc. (see the pattern emerging:)
As an example lets take a connection pool manager: we want to create a single pool of connections that are managed and re-used by any other object that requires a connection in our code, so we make a ConnectionPoolManager singleton class, with say, 32 connections. This now allows every object requiring a connection to use a method, for example getFreeConnection, from the ConnectionPoolManager singleton, to retrieve a valid connection which can then be used as needed. This allows the ConnectionPoolManager to be the only part of the code anywhere that has anything to do with starting stopping and otherwise managing connections for your code.
Both singletons and static class can be implemented in such a way that they are thread-safe, however singletons have the advantage as they can implement interface (common), derive from other classes (less common), and a singleton can be passed around in exactly the same way as any other object (well a reference to it at least), where a static class can only implement static methods.
In regards of your specific case, you indicate that from 30+ classes only a couple require the utility class: the dependence on a singleton or static class is entirely up to your design and style. Should you wish a versatile way of doing it, with potential for change later, I would utilise a singleton. If you know that the static class will suffice and will not necessitate a redesign later, then go with that, or, if you have a particular liking for one or the other, use that one. There may also be hardware/software limitations and particulars which recommend one over the other, however that does not sound to be the case at the moment.
Let me know if you need more information, or if there are any particulars which you think may sway your choice one way or the other and I can provide information about pros and cons for each approach to suit your needs:)
I have a question on where to create, own and destroy data.
The data itself are large tables of numbers, either randomly generated or read from the hard drive. This data is then subject to analysis, and depending on what exactly is analyzed, I have made a few wrapper like structures, which encapsulated the desired functionality. Since the wrapper can be switched in later stages, I decided against creating/reading the data inside the wrapper constructors, and just handle them in the "main" function. The wrappers then only see pointers of the data.
First of, is this common/ a good idea, or should a wrapper always own its own copy of the data it wraps around?
Well, next I made a "menu" class to better navigate through data creation/analysis choices etc, and the easiest would be to make the data part of the menu class. This doesn't feel good though, so where should I put it? Should it stay in the main class?
I hope this is understandable. If not, I can try to give a better outline of what is happening.
Thank you for reading.
You could create a data class, and wrap other classes around it. An object of the data class probably should be global or defined inside main. OTher than that - your idea seems good. WIth a data class defined, you could also pass a pointer/reference to the menu, so you wouldn't have the problem with that. Note that a menu can also be a wrapper if you wish.
It's generally a better idea to keep the details of data in a specific wrapper class (I think you mean derived class?). Your wrapper classes should be derived from an interface or abstract type. You can construct wrapper-class factories in main(), and pass the factories around to constructors (constructors of the classes that are instantiated in main()). Later when the data-specific wrapper needs to be switched on or created, invoke the factory method. The factories can own the pointers, by which I mean they call new() and delete(). Try looking up SOLID principles and see how they guide you.
I have to write a bunch of DTOs (Data Transfer Objects) - their sole purpose is to transfer data between client app(s) and the server app, so they have a bunch of properties, a serialize function and a deserialize function.
When I've seen DTOs they often have getters and setters, but is their any point for these types of class? I did wonder if I'd ever put validation or do calculations in the methods, but I'm thinking probably not as that seems to go beyond the scope of their purpose.
At the server end, the business layer deals with logic, and in the client the DTOs will just be used in view models (and to send data to the server).
Assuming I'm going about all of this correctly, what do people think?
Thanks!
EDIT: AND if so, would their be any issue with putting the get / set implementation in the class definition? Saves repeating everything in the cpp file...
If you have a class whose explicit purpose is just to store it's member variables in one place, you may as well just make them all public.
The object would likely not require destructor (you only need a destructor if you need to cleanup resources, e.g. pointers, but if you're serializing a pointer, you're just asking for trouble). It's probably nice to have some syntax sugars constructors, but nothing really necessary.
If the data is just a Plain Old Data (POD) object for carrying data, then it's a candidate for being a struct (fully public class).
However, depending on your design, you might want to consider adding some behavior, e.g. an .action() method, that knows how to integrate the data it is carrying to your actual Model object; as opposed to having the actual Model integrating those changes itself. In effect, the DTO can be considered part of the Controller (input) instead of part of Model (data).
In any case, in any language, a getter/setter is a sign of poor encapsulation. It is not OOP to have a getter/setter for each instance fields. Objects should be Rich, not Anemic. If you really want an Anemic Object, then skip the getter/setter and go directly to POD full-public struct; there is almost no benefit of using getter/setter over fully public struct, except that it complicates code so it might give you a higher rating if your workplace uses lines of code as a productivity metric.
In a C++ multi-threaded application with many classes, i am trying to find out what are the methods to define a global variable
C style, define it as global in any one source file, define it as extern in a header which is included in the classes that access this variable.
Write a Singleton class, which contains these global variables and exposes set/get methods to write to the variable.
By second method one can control multi-threaded access via locks in a centralized manner rather than the first approach.
Are there more and better ways?
First of all try to avoid global variables as much as you can. If you just need to do it (by example this is the case with cin, cout and cerr) your second method is definitely the best (and more natural) way of doing it.
If the scope of your "global variable" can be narrowed down (which is typically the case - how many variables are truly global?) then you can make it a private static class member in the appropriate owning class. If your other classes need to see it (or less likely, update it), provide get/put accessors.
I would definitely go with the Singleton class. It's the best way to handle "global" variables in a multithreaded OOP environment.
If you must use a global variable (and why are you using one?) I recommend the second way you described. The first way is the way you can run into all kinds of namespace problems.
This probleam can be solved with an alternatieve method very easily.
C++ resolves this problem very easily by its new operator :: called scope resolution operator. The syntax is as follows
:: variable-name;
This operator allows access the global version of a vriable.
One tends to prefer the second method, because it seems to give you a better control but it may not turn out very useful in some scenarios.
First, In my understanding of philosophy of OOP, I do not consider objects as collections of bunch of data, but entities in terms of which, you can represent real world problems. So I do not consider it a good idea to to have a class to store random data. Especially when the data members are largely unrelated.
Second, If you are thinking of having a central control eg. having a single mutex to access all the data members, this is not going to work out very well for unrelated data members. You are going to block a lot of threads unnecessarily while the data they want is not exactly the one which is being currently protected by the lock.
So it may seem strange, but I would prefer the first method.
It depends on the problem at hand.
C-style globals have the advantage of simplicity, no need for Singleton::instance() call. However, Singleton::instance() allows you to initialize your global state on the first call.
To get the best of both worlds use C-style globals initialized using Schwarz Counter method. http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter
You can define a value object that wraps a single implementation with the handle/body idiom.
Also review "Modern C++ Design" by Alexandrescu for discussion about the difficulties of implementing singleton in MT environments and how to go about addressing them.
Not to kick a dead horse but, as mentioned, avoiding globals is the best solution. Some reasons are listed here. If a global variable is a must you might want to consider providing a function to access it from to avoid the so called 'global initialization fiasco'.