Which is more appropriate: getters and setters or functions? - c++

Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?
For example, imagine I have this class in C++:
public class SomeClass {
private:
bool mIsVisible;
public:
void draw();
void erase();
}
I could add functions to get/set "mIsVisible" like this:
bool getVisible() { return mIsVisible; };
void setVisible(bool visible) {
if (!mIsVisible && visible) {
draw();
} else if (mIsVisible && !visible) {
erase();
}
mIsVisible = visible;
}
However, it would be equally possible to use the following methods instead:
bool isVisible() { return mIsVisible; };
void show() {
if (!mIsVisible) {
mIsVisible = true;
draw();
}
}
void hide() {
if (mIsVisible) {
mIsVisible = false;
erase();
}
}
In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?

Have a read of the article "Tell, Don't Ask" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.
Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely:
get current visibility value,
make decision based on value,
update object.

In the example you gave, show() and hide() make a lot of sense, at least to me.
On the other hand, if you had a property skinPigment and you decided to make functions called tanMe() and makeAlbino() that would be a really poor, non-obvious choice.
It is subjective, you have to try to think the way your users (the people utilizing this class) think. Whichever way you decide, it should be obvious to them, and well-documented.

I would go with the isVisible()/show()/hide() set.
setVisible() implies that all it does it change the internal variable. show() and hide() make the side effects clear.
On the other hand, if all getVisible()/setVisible() did was to change the internal variable, then you've just changed remarkably little from having them as public fields.

setters actually have very little to do with object orientation, which is the programming idiom applied in the example. getters are marginally better, but can be lived without in many cases.
If everything can be gotten and set, what's the point of having an object? Operations should be called on objects to accomplish things, changing the internal state is merely a side-effect of this.
The bad thing about a setter in the presence of polymorphism - one of OO's cornerstones - is that you force every derived class to have a setter. What if the object in question has got no need for an internal state called mIsVisible? Sure he can ignore the call and implement as empty, but then you are left with a meaningless operation. OTOH, operations like show and hide can be easily overridden with different implementations, without revealing anything about the internal state.

In general, I think setters/getters should only set the values of properties. In your example, you are also performing an action based on the value of the isVisible property. In this case, I would argue that using functions to perform the action and update the state is better than having a setter/getter that performs an action as a side-effect of updating the property.

If switching mIsVisible really turns visibility of the object on and off immediately, than use the show/hide scenario. If it will stay in the old state a little longer (e.g. until something else triggers a redraw) then the set/get scenario would be the way to go.

I prefer the show() and hide() methods because they explicitly tell what you are going. The setVisible(boolean) doesn't tell you if the method is going to show/draw right away. Plus show() and hide() are better-named method for an interface (IMHO).

Implicitly, the 'show' and 'hide' functions you list are both setters
For booleans, I'd think that a single tool like you've shown would be good. However, a .show and .hide function also look like commands, not functions that change the state of the object.

In the case you actually have to write code like
if (shouldBeShowingAccordingToBusinessLogic()) w.show();
else w.hide();
all over the place, you might be better off with
w.showIfAndOnlyIf(shouldBeShowingAccordingToBusinessLogic())
Or, for truly bizarre cases, when your logic can't decide whether to dhow or not till the end of some code stretch, you can try
w.setPostponedVisibility(shouldBeShowingAccordingToBusinessLogic());
...
w.realizeVisibility();
(Didn't I say it's bizzare?)

An additional motivation to go for the display/hide solution is that as a setter,
the setVisible method has a 'side effect', in that it also displays or hides SomeClass. The display/hide methods better convey the intent of what happens.

Related

Programming pattern for components that are toggleable at runtime

I'm wondering if there is some kind of logical programming pattern or structure that I should be using if sometimes during runtime a component should be used and other times not. The obvious simple solution is to just use if-else statements everywhere. I'm trying to avoid littering my code with if-else statements since once the component is toggled on, it will more than likely be on for a while and I wonder if its worth it to recheck if the same component is active all over the place when the answer will most likely not have changed between checks.
Thanks
A brief example of what I'm trying to avoid
class MainClass
{
public:
// constructors, destructors, etc
private:
ComponentClass m_TogglableComponent;
}
// somewhere else in the codebase
if (m_TogglableComponent.IsActive())
{
// do stuff
}
// somewhere totally different in the codebase
if (m_TogglableComponent.IsActive())
{
// do some different stuff
}
Looks like you're headed towards a feature toggle. This is a common occurrence when there's a piece of functionality that you need to be able to toggle on or off at run time. The key piece of insight with this approach is to use polymorphism instead of if/else statements, leveraging object oriented practices.
Martin Fowler details an approach here, as well as his rationale: http://martinfowler.com/articles/feature-toggles.html
But for a quick answer, instead of having state in your ComponentClass that tells observers whether it's active or not, you'll want to make a base class, AbstractComponentClass, and two base classes ActiveComponentClass and InactiveComponentClass. Bear in mind that m_TogglableComponent is currently an automatic member, and you'll need to make it a pointer under this new setup.
AbstractComponentClass will define pure virtual methods that both need to implement. In ActiveComponentClass you will put your normal functionality, as if it were enabled. In InactiveComponentClass you do as little as possible, enough to make the component invisible as far as MainClass is concerned. Void functions will do nothing and functions return values will return neutral values.
The last step is creating an instance of one of these two classes. This is where you bring in dependency injection. In your constructor to MainClass, you'll take a pointer of type AbstractComponentClass. From there on it doesn't care if it's Active or Inactive, it just calls the virtual functions. Whoever owns or controls MainClass is the one that injects the kind that you want, either active or inactive, which could be read by configuration or however else your system decides when to toggle.
If you need to change the behaviour at run time, you'll also need a setter method that takes another AbstractComponentClass pointer and replaces the one from the constructor.

Extending a general purpose function

I'm creating a game, and in this game a ball can be caught in various ways, which all result in different behaviour. Initially, I wanted to add an enum to a certain general purpose method when catching to ball, which will then delegate the actions that take place when a ball gets caught in a certain way. An example would be:
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
switch (Method)
{
case Method::PickUp: OnPickup(Catcher); break;
case Method::Pass: OnPass(Catcher); break;
// etc
}
}
This would allow me to call the function as:
MyWeapon->Catch(Catcher, Method::Pickup);
MyWeapon->Catch(Catcher, Method::Pass);
and the likes. I think this would read nicer than
MyWeapon->CatchByPickup(Catcher);
MyWeapon->CatchByPass(Catcher);
My main issue however, is that this is not extendable at all, which is what I was actually hoping to achieve with this general purpose method. If I make the method an enum, I cannot simply extend the enum and override the virtual Catch method in a derived class of Weapon. If I decide to extend the method in some derived class, I'd have to create a new enum which begins at the last value of the Method enum. I do not feel that this is a proper way to deal with the situation, but I do not know what the best practise in this case would be. Does it perhaps involve template specializations? The main problem to me, is that I cannot simply extend enums.
You could make use of std::function.
using CatchMethod = std::function<void(Character)>;
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
Method(Catcher);
}
Calling the function is then pretty straightforward
// If its a regular function you can just use the pointer to the function
weapon.Catch(Player, &OnPickup);
// If its a member function you can use lambda
weapon.Catch(Player, [this](Character Catcher){OnPickup(Catcher);});
// or std::bind (slightly more verbose and less flexible)
weapon.Catch(Player, std::bind(&Weapon::OnPickup, this, std::placeholders::_1));
It's a bit non-obvious since I'm not sure if you have any other code in your Catch method that is relevant to the system, but it sounds to me like you would want to simply not use methods at all and invert the control to have different functions. Like this, for example:
void pickup(Weapon weapon, Character catcher) {
/* Do whatever your OnPickup does */
}
void pass(Weapon weapon, Character catcher) {
/* Do whatever your OnPass does */
}
And then, obviously, just call them like this:
pickup(MyWeapon, Catcher);
pass(MyWeapon, Catcher);
If there is no surrounding code or similar prerequisites that you don't show in the question, I don't think there are any back sides to this, and declaring new functions to do similar things is entirely decentralized and extensible.
If it is that you need to pass the CatchMethod through other functions, you could simply pass a function pointer instead.
As an aside, by the way, unless Weapon and Character here are typedefs to something else, it's generally a bad idea to pass these kinds of things by-value. You probably want to use references or pointers instead.

Retrieving values of collection from multiple classes, what's the correct way?

Before anything, thanks for reading!
I'm developing an application in C++ and I want an advice about a design issue. Let me explain:
The main class of my application has some collections, but other classes eventually need to get a value from one of those collections. Something like this:
class MainClass {
private:
// Collections are internally implemented as QHash
Collection<Type1> col1;
Collection<Type2> col2;
};
class RosterUnit {
public:
RosterUnit() {
/* This method needs to get a specific value from col1 and
initialize this class with that data */
}
};
class ObjectAction {
public:
virtual void doAction() = 0;
};
class Action1 : public ObjectAction {
public:
void doAction() {
// This needs a specific value from col2
}
};
class Action2 : public ObjectAction {
public:
void doAction() {
// This needs a specific value from col1
}
};
My first approach was passing the whole collection as parameter when needed, but it is not so good for ObjectAction subclasses, because I would have to pass the two collections and if I later create another subclass of ObjectAction and it needs to get an element from other collection (suppose col3), I would have to modify the doAction() signature of every ObjectAction subclass, and I think that is not too flexible. Also, suppose I have a Dialog and want to create a RosterUnit from there. I would have to pass the collection to the dialog just to create the RosterUnit.
Next I decided to use static variables in RosterUnit and ObjectAction that pointed to the collections, but I'm not very happy with that solution. I think it is not flexible enough.
I have been reading about design patterns and I first thought a Singleton with get functions could be a good choice, but after some more investigation I think it isn't a proper design for my case. It would be easier and more or less the same if I use global variables, which don't seem to be the right way.
So, could you give some advices, please?
Thank you very much!
As mentioned previously, Iterators are good for abstracting away the details of the Collection. But going this route implies that the objects that use the Iterators will need to know about what's inside the Collection. Meaning they will need to know how to decide which object in the Collection they need, thus increasing the coupling. (more details below in the Factory paragraph) This is something you need to consider.
Another approach would be to create accessor methods on the MainClass that take some sort of key and return an object from the Collection (findObject(key)). Internally the MainClass methods would search through the container(s) and return the appropriate object. To use this approach, you will however need access to the MainClass, either by dependancy injection as mentioned before, or possibly making it a Singleton (not recomended in this scenario, though).
With the info provided so far, it may even be better for your ObjectAction Factory to have a reference to the MainClass, and as a part of the ObjectAction creation logic, call the appropriate MainClass accessor and pass the result into the ObjectAction, thus decoupling the ObjectAction Objects from the MainClass.
You probably want to use iterators, they exist exactly for the purpose of abstracting away sequences from specific containers.
If your issue is how to pass the iterators to the code that needs them in the first place, do not give in to the temptation to use globals. It may look more convoluted if you have to pass parameters in, but your code is that much more decoupled for it. "Dependency Injection" is a good keyword if you want to read more about this topic.
I would also advise you to check out std::function or boost::function instead of inheriting from ObjectAction. Functional style is getting more common in modern C++, as opposed to how it's usually done in languages like Java.
There's not enough information here of what you are trying to do. You make it sound like 'at some point in the future, this statically created action needs this data that was left behind.' How does that make any sense? I would say either construct the actions with the data, as you would for instance with a Future or Callable), or have the command ask for the next piece of data, in which case you are just implementing a Work queue.
Sounds like you are trying to do something like a thread pool. If these actions are in any way related, then you should have then in some composing object, implementing something like the Template Method pattern, e.g. execute() is abstract and calls a few other methods in a fixed sequence and that cannot be overridden, the other methods must be (protocol enforcement).

Alternatives to passing a flag into a method?

Sometimes when fixing a defect in an existing code base I might (often out of laziness) decide to change a method from:
void
MyClass::foo(uint32_t aBar)
{
// Do something with aBar...
}
to:
void
MyClass::foo(uint32_t aBar, bool aSomeCondition)
{
if (aSomeCondition)
{
// Do something with aBar...
}
}
During a code review a colleague mentioned that a better approach would be to sub-class MyClass to provide this specialized functionality.
However, I would argue that as long as aSomeCondition doesn't violate the purpose or cohesion of MyClass it is an acceptable pattern to use. Only if the code became infiltrated with flags and if statements would inheritance be a better option, otherwise we would be potentially be entering architecture astronaut territory.
What's the tipping point here?
Note: I just saw this related answer which suggests that an enum may be a better
choice than a bool, but I think my question still applies in this case.
There is not only one solution for this kind of problem.
Boolean has a very low semantic. If you want to add in the future a new condition you will have to add a new parameter...
After four years of maintenance your method may have half a dozen of parameters, if these parameters are all boolean it is very nice trap for maintainers.
Enum is a good choice if cases are exclusive.
Enums can be easily migrated to a bit-mask or a context object.
Bit mask : C++ includes C language, you can use some plain old practices. Sometime a bit mask on an unsigned int is a good choice (but you loose type checking) and you can pass by mistake an incorrect mask. It is a convenient way to move smoothly from a boolean or an enum argument to this kind of pattern.
Bit mask can be migrated with some effort to a context-object. You may have to implement some kind of bitwise arithmetics such as operator | and operator & if you have to keep a buildtime compatibility.
Inheritence is sometime a good choice if the split of behavior is big and this behavior IS RELATED to the lifecycle of the instance. Note that you also have to use polymorphism and this is may slow down the method if this method is heavily used.
And finally inheritence induce change in all your factory code... And what will you do if you have several methods to change in an exclusive fashion ? You will clutter your code of specific classes...
In fact, I think that this generally not a very good idea.
Method split : Another solution is sometime to split the method in several private and provide two or more public methods.
Context object : C++ and C lack of named parameter can be bypassed by adding a context parameter. I use this pattern very often, especially when I have to pass many data across level of a complex framework.
class Context{
public:
// usually not a good idea to add public data member but to my opinion this is an exception
bool setup:1;
bool foo:1;
bool bar:1;
...
Context() : setup(0), foo(0), bar(0) ... {}
};
...
Context ctx;
ctx.setup = true; ...
MyObj.foo(ctx);
Note:
That this is also useful to minimize access (or use) of static data or query to singleton object, TLS ...
Context object can contain a lot more of caching data related to an algorithm.
...
I let your imagination run free...
Anti patterns
I add here several anti pattern (to prevent some change of signature):
*NEVER DO THIS *
*NEVER DO THIS * use a static int/bool for argument passing (some people that do that, and this is a nightmare to remove this kind of stuff). Break at least multithreading...
*NEVER DO THIS * add a data member to pass parameter to method.
Unfortunately, I don't think there is a clear answer to the problem (and it's one I encounter quite frequently in my own code). With the boolean:
foo( x, true );
the call is hard to understand .
With an enum:
foo( x, UseHigherAccuracy );
it is easy to understand but you tend to end up with code like this:
foo( x, something == someval ? UseHigherAccuracy : UseLowerAccuracy );
which is hardly an improvement. And with multiple functions:
if ( something == someval ) {
AccurateFoo( x );
}
else {
InaccurateFoo( x );
}
you end up with a lot more code. But I guess this is the easiest to read, and what I'd tend to use, but I still don't completely like it :-(
One thing I definitely would NOT do however, is subclass. Inheritance should be the last tool you ever reach for.
The primary question is if the flag affects the behaviour of the class, or of that one function. Function-local changes should be parameters, not subclasses. Run-time inheritance should be one of the last tools reached for.
The general guideline I use is: if aSomeCondition changes the nature of the function in a major way, then I consider subclassing.
Subclassing is a relatively large effort compared to adding a flag that has only a minor effect.
Some examples:
if it's a flag that changes the direction in which a sorted collection is returned to the caller, that's a minor change in nature (flag).
if it's a one-shot flag (something that affects the current call rather than a persistent change to the object), it should probably not be a subclass (since going down that track is likely to lead to a massive number of classes).
if it's a enumeration that changes the underlying data structure of your class from array to linked list or balanced tree, that's a complex change (subclass).
Of course, that last one may be better handled by totally hiding the underlying data structure but I'm assuming here that you want to be able to select one of many, for reasons such as performance.
IMHO, aSomeCondition flag changes or depends on the state of current instance, therefore, under certain conditions this class should change its state and handle mentioned operation differently. In this case, I can suggest the usage of State Pattern. Hope it helps.
I would just change code:
void MyClass::foo(uint32_t aBar, bool aSomeCondition)
{
if (aSomeCondition)
{
// Do something with aBar...
}
}
to:
void MyClass::foo(uint32_t aBar)
{
if (this->aSomeCondition)
{
// Do something with aBar...
}
}
I always omit bool as function parameter and prefer to put into struct, even if I would have to call
myClass->enableCondition();

C++ design pattern to get rid of if-then-else

I have the following piece of code:
if (book.type == A) do_something();
else if (book.type == B) do_something_else();
....
else do so_some_default_thing.
This code will need to be modified whenever there is a new book type
or when a book type is removed. I know that I can use enums and use a switch
statement. Is there a design pattern that removes thisĀ if-then-else?
What are the advantages of such a pattern over using a switch statement?
You could make a different class for each type of book. Each class could implement the same interface, and overload a method to perform the necessary class-specific logic.
I'm not saying that's necessarily better, but it is an option.
As others have pointed out, a virtual function should probably be your first choice.
If, for some reason, that doesn't make sense/work well for your design, another possibility would be to use an std::map using book.type as a key and a pointer to function (or functor, etc.) as the associated value, so you just lookup the action to take for a particular type (which is pretty much how many OO languages implement their equivalent of virtual functions, under the hood).
Each different type of book is a different sub-class of the parent class, and each class implements a method do_some_action() with the same interface. You invoke the method when you want the action to take place.
Yes, it's called looping:
struct BookType {
char type;
void *do();
};
BookType[] types = {{A, do_something}, {B, do_something_else}, ...};
for (int i = 0; i < types_length; i++) {
if (book.type == types[i].type) types[i].do(book);
}
For a better approach though, it's even more preferrable if do_something, do_something_else, etc is a method of Book, so:
struct Book {
virtual void do() = 0;
};
struct A {
void do() {
// ... do_something
}
};
struct B {
void do() {
// ... do_something_else
}
};
so you only need to do:
book.do();
Those if-then-else-if constructs are one of my most acute pet peeves. I find it difficult to conjure up a less imaginative design choice. But enough of that. On to what can be done about it.
I've used several design approaches depending on the exact nature of the action to be taken.
If the number of possibilities is small and future expansion is unlikely I may just use a switch statement. But I'm sure you didn't come all the way to SOF to hear something that boring.
If the action is the assignment of a value then a table-driven approach allows future growth without actually making code changes. Simply add and remove table entries.
If the action involves complex method invocations then I tend to use the Chain of Responsibility design pattern. I'll build a list of objects that each knows how to handle the actions for a particular case.
You hand the item to be processed to the first handler object. If it knows what to do with the item it performs the action. If it doesn't, it passes the item off to the next handler in the list. This continues until the item is processed or it falls into the default handler that cleans up or prints an error or whatever. Maintenance is simple -- you add or remove handler objects from the list.
You could define a subclass for each book type, and define a virtual function do_something. Each subclass A, B, etc would have its own version of do_something that it calls into, and do_some_default_thing then just becomes the do_something method in the base class.
Anyway, just one possible approach. You would have to evaluate whether it really makes things easier for you...
Strategy Design Pattern is what I think you need.
As an alternative to having a different class for each book, consider having a map from book types to function pointers. Then your code would look like this (sorry for pseudocode, C++ isn't at the tip of my fingers these days):
if book.type in booktypemap:
booktypemap[book.type]();
else
defaultfunc();