C.12 and dependency breaking
Using a reference to an interface for dependency breaking is so useful that I really think the advice can be harmful. It helps too against singletons, globals etc.. I think it can be very useful if you speak about value member.
class Frontend(BackendInterface &backend) : backend(beckend) { void sendMessage(string title) { auto message = backend.createMessage(); message.value = title; backend.scheduleMessage(message); } private: BackendInterface &backend; }
My reading of the guideline is not that you would avoid doing that but that you would use a pointer instead. I'm not 100% confident that this is what it's saying and I'm not sure I agree if it is.
But a pointer can be null at runtime. I use that if the interface can be not there or be changed. But normally this is not needed because this objects are initialized together.
I believe the rule is derived from https://herbsutter.com/2020/02/23/references-simply/ The relevant sections are
- Isn’t T& convenient for easily expressing a pointer than can’t be rebound to another object?
- Isn’t T& convenient for easily expressing a pointer that is not null?
- But what about using a reference type as a class data member?
My understanding is that he speaks mostly about values. But mocks are mostly implementing non copyable interfaces. Many would be traditionally implemented as singletons or simply functions like interfaces to resources like the file system or a database connection. I have the general impression that writing tests is not in the scope of the core guide lines but I still haven't finished them. 😏
Herb mentions gsl::not_null<>. I believe Core Guidelines recommends using (const) T& for functions and gsl::not_null<(const) T*> for classes when you need to pass mocks/dependencies, etc. At least that's how I approach dependencies in my projects.
Editors' call: Yes, @shaneasd and @coffee-lord summarize the intent here. We have added a Note about using a pointer, and also some additional explanation of the "bad" example.
Hmm, my experience with pointers is that people run in ownership problems and the start to use shared pointers which leads to even stranger bugs. It is hard to think about ownership so they choose the easy way out with a mix of shared pointers and defensive programming. If you use references the psychological barrier is higher and they start (hopefully) to reduce the complexity of the architecture.
The argument about copying is a litte bit strange because this type of classes normally have copying disabled. Maybe there should be a part about testing and dependency breakage in the guidelines?
@marbub T& and gsl::not_null<T*> are equivalent with the exception of gsl::not_null<T*> being reassignable (and thus not preventing the class from being copy/move-assignable). Both are non-owning according to R.3, R.4. I don't see how choosing one over the other might influence the decision to change the ownership from non-owning reference/pointer to owning smart pointer. After all, T& and gsl::not_null<T*> are equally susceptible to owndership-related problems.
As for the argument about copying - think of it this way: would you rather have a guideline that forces you to make non-copy/move-assignable classes whenever you need to use dependency injection or a guideline that aims to be flexible enough as to not prevent you from having both - proper inversion of control and copyable/movable classes? I would argue that just because a class uses DI doesn't mean it should always be non-copyable/movable.
@coffee-lord
Is gsl part of the standard? It is not so easy to argument for a new dependency in a project.
In my experiences DIs are not very often not reassigned. If they are they can be very often be null so a pointer is better.
T& and gsl::not_null<T*> are differ in many ways. The first is a language feature the second is a runtime feature. You can even to pointer arithmetics on it. T& is simply more constraint. And is it not better for API design to use the contraint tool if you don't need a features? I understand your technical argument but my argument was not technical but psychological. And psychology is a very important force in software development.
My experience with ambiguous guidance is that you better do not give them. Even better would be to have higher level abstractions to express the intend. It would be anyway something I desire for DI. So far I use virtual interfaces very much but they are only needed for the test code. In the final application there is only one implementation and no need for virtual calls. I see that is impossible to have this feature in the near future of C++ because there are no guidelines for progress. 😉 But maybe if TDD gets more popular in C++ this will change.
GSL is not part of the standard.
However, my point still stands. T& is non-null, non-reassignable, T* maybe-null, reassignable. gsl::not_null<T*> bridges the gap between the two, serving as a hybrid of sorts. I'm not sure what you mean by "runtime feature" but gsl::not_null<T*> doesn't do any runtime checks unless you enable the Expects mechanism of GSL. gsl::not_null<T*>'s main purpose is not having a default constructor (and deleted nullptr constructors too), which makes it very similar to T&. If you follow ES.42 you shouldn't be doing pointer arithmetic on gsl::not_null<T*>, and in fact you can't, since not_null's arithmetic operators are deleted.
If I couldn't use GSL for whatever reason (and didn't want to copy/paste not_null<T*>s implementation) I would still opt for using T* for DI. Why should I forgo copyable/movable classes if I choose to use DI? Why can't I have both? I agree that some classes might not need to be copy-assignable. But why shouldn't a class that uses DI be move-assignable?
I understand that your primary concern is psychological in nature. In fact, I used T& for DI myself when I first started learning about DI/mocking in C++. However, there are legitimate cases where you might want to make copies or move a class that uses DI. You might want to take snapshots, move an object to a different location, swap objects, etc. If we agree that ideally a class should "behave like an int" (C.concrete) then there is no ambiguity in this guideline. If you want a class to behave like an int, use pointers.
P.S. There are a couple of ways to mock classes without using virtual interfaces. You can use templates/policy based design, type erasure, #defines or even swap the implementation (.cpp) during build. Mocking in C++ could definitely use some improvement but I doubt it'll happen before we get compile time code generation or metaclasses.
The edit in 4028153 is a big improvement in terms of making it clear what the recommended alternative is.
@coffee-lord
If I have
struct MyClass { not_null<X> mydependency; ... }
then yes that class is copyable but it will be a shallow copy. Is that the correct copy for this type? Maybe. Maybe not.
If you need/want copy assignment then you don't have a choice. You can't use a reference. If you don't need/want copy assignment then using a pointer type opens you up to shallow/deep copy bugs. Hopefully your static analysis or code review process is effective enough to detect this but both are more likely to understand primitive constructs over library provided ones.
I agree that value classes should behave like an int but what about resources like a database connection. Even a mutex is not copyable. 😉 You could allocate them on the heap but then your ownership gets more complicated. My pattern in that case is to add a clone function to make expensive copies explicit because almost all copies of that kind of class are by accident. And for that kind of classes I mostly use DI. I never used DI for value classes.
@shaneasd It might not be a correct way to copy this type, I agree. But my point is that you've got to have a mighty good reason to make your class non-copy-assignable and non-move-assignable. Which is what you'll get if you use references. I struggled to come up with use cases for this when we had a discussion in the comments. I could only think of mutexes and singletons. Even polymorphic std classes like std::ostringstream are movable but not copyable. If you are writing a mutex then I suppose there's no harm in using references, knock yourself out.
Personally, I'd rather use gsl::not_null<T*> and unit test constructors and assignment operators, than punish the user by removing copy/move-assignment for no good reason. If some of my classes are not copyable and/nor movable it's not because of my being lazy or references, it is because the operation doesn't make sense for this particular type.
@marbub
what about resources like a database connection
I would expect a database connection to be non-copyable but still movable. And it seems whoever wrote this C++ wrapper for SQLite agrees :slightly_smiling_face:
I speak about application code, library code is very different because you don't know exactly how it is used. There are usecases for moving and then maybe you want to use pointer.
The reason to make it non movable and non copyable is very simple. You don't need it. Don't write code you do not need. Here we have the defaults of C++ again. class is a very generic term. It would be very nice if there would be meta classes so you could provide defaults for values, resources etc..
Okay, I found some code of my where I use a reference and which is movable. I really want to understand what can go wrong if the database is always there?
You've made Database non-movable so I don't see what could go wrong. However, comparing your Database class with the one I linked earlier - I'd prefer the latter because if, say during refactoring I wanted to add a factory function - well with your implementation I couldn't, it's too rigid
Database make_database(/* args... */) {
Database db{/*args*/};
// Do stuff with db...
return db; // Works with SQLiteCpp but not with your implementation of Database
}
Why shouldn't a database class be movable?
You might argue that you don't need a factory but my point is that if only you used pointers in your design, you could have gone ahead and made everything movable by default with arguably minimal effort, or at least made sure that the option to make it movable is always there.
PS. C.21 aka "the rule of five" is broken in quite a few places. Tsk tsk tsk.
Personally I try to avoid factory functions because they I very often construct classes in place. I see it as a feature if you cannot move or copy a class. It makes ownership much easier because nobody can move the class out of the scope of ownership. Restrictions reduces complexity and complexity produces new branches which if you don't test them can produce bugs. Adding testing code for not used features makes it more costly to change your code too.
I really looking forward to the day then the compiler enforces the rule of five. Handling the destructor and copy by yourself is ... Sometimes I think people care to much about old code and not enough about new bugs. Maybe something as an epoch in modules could be a good compromise.
I guess you're right, if you know for a fact that your class must be non-copyable and non-movable then technically there is no harm in using references and/or const members. C.12 doesn't really provide any reasoning as to why you should be using pointers if your class is non-copyable and non-movable. For the sake of consistency, maybe?
You can advice that but imagine all the discussions in teams about this rules. And if you have a rule which is not well argumented for all cases people start to say that the core guidelines are ... and demiss the value of the core guidelines completely. So I still think the rule should be better argumented or limited in scope. Otherwise this discussion will be repeated again and again in teams.
So I hope you understand my intention. It not about to change the rules but to have better arguments. And if your reasons are not very clear with very readable examples it is very likely that people start to demiss it. And yes, Herb said so, is not to all people a convincing argument ;-)
Using 'bad' or 'good' instead of repeating the reason sounds in the best case lazy, in the worst like a cult.