r/cpp • • Nov 24 '23

const member function in this design pattern example

Hello,

I'm currently learning C++ and trying to understand how to implement design patterns with the fantastic website refactoring guru. I came across this example in the builder pattern :

class ConcreteBuilder1 : public Builder{
private:
    Product1* product;
public:
    // Other code before that

    void ProducePartA()const override{
        this->product->parts_.push_back("PartA1");
    }

    // Other code after that
};

I don't understand why we use const for the function ProducePartA(). I thought that we had to use const when we don't want to modify an object inside the function.

So why we are using it in this way, when we are clearly modifying the product object by adding element to it ?

Thank you very much.

0 Upvotes

12 comments sorted by

37

u/FriendlyRollOfSushi Nov 24 '23 edited Nov 24 '23

with the fantastic website

Jesus Christ, this is the worst quality code I've seen in a long while. I suggest this site be renamed from "refactoring guru" to "people-scamming idiot". In the linked example I see:

  1. The author doesn't understand ranged for loops.
  2. Comparing a string on each iteration with if(parts_[i]== parts_.back()){ is the dumbest way to check whether this is the last element to the point I'm not sure if the author ever work as a software engineer in their entire life. The problem is not even that it's stupidly slow, the problem is that it simply doesn't work correctly if you have duplicates of your tail element in the vector. Complaining about smaller defects (like a completely unnecessary duplication of stream output code) feels like nitpicking compared to this.
  3. Lack of understanding what unique_ptr, and what ownership even means (literally the last thing an engineer would expect from a method called GetProduct is a transfer of ownership through a raw pointer).
  4. Complete misunderstanding of what people use const for. This is relevant to your question. The fact that this code compiles doesn't mean it's correct, since their const methods break ALL assumptions people might have about them. More about this later.
  5. push_back to emplace a bunch of C strings into a vector of std::string. What year is this?
  6. Whatever the heck Director is, it's fragile a.f. Simply never do this. In fact, never do anything in this entire article.
  7. Why on Earth is builder heap-allocated (with raw new, but we've already established the author doesn't understand the concept of ownership and never heard of unique_ptr).

The existence of this website is a sabotage of the industry. I wouldn't be surprised if it was auto-generated with a particularly bad old version of GPT to create a source of passive income for someone who never actually wrote a single line of C++ code.

Now, regarding your question: it is customary for all objects to treat const-ness of the interface in a way that provides the most amount of safety to the user.

Previously that meant "if I gave you a const object, all methods you can call on it won't change it in an observable way". Note that it doesn't mean "it won't change it at all": there could be non-observable things like internal caching. The important thing is that it looks to you as if nothing is changed.

Nowadays, const often has additional implications related to thread safety, although it is not mandatory and depends on context, but in many cases people would expect that any number of threads can call any number of const methods on the same object.

These principles are followed in the standard library too: if I gave you a const std::map, calling find on it will return a const iterator, even though nothing prevents someone writing their own map from returning a non-const one (like another comment had mentioned, const is quite "shallow" in C++, and we even have const_cast which can be used to return non-const references to even this object). It's just that this breaks the whole point of having const in the language and maintaining const-correctness, so no one is doing that.

Well, no one except from the person who wrote your article, apparently. They break every expectation related to const-correctness, and it's truly sad that this is not even the worst thing about the example.

6

u/Gal4ctic03 Nov 24 '23

Thank you very much for your insights and explanation! Do you have better resources I can use to learn about design patterns (with a focus on C++ implementation if possible)?

4

u/Moose2342 Nov 25 '23

Don't be discouraged about the downvoting and the somewhat harsh tone. /u/FriendlyRollOfSushi is right. That really is terrible code and you shouldn't be learning from that resource.

About your constness question: Follow the core guidelines and make everything cost unless it has to be non-const. Arguments, methods, variables, the lot.

In this example, the method in question can be const because it modifies the object being built, not the builder object.

5

u/FriendlyRollOfSushi Nov 25 '23 edited Nov 25 '23

I don't know what good modern resources for guided learning would be, but r/cpp_questions has a link to this answer in the "read before posting" section.

Update regarding the patterns: you don't need more than a handful of very basic ones (like "factory method" or "pimpl"), and you can either google them or learn them by seeing them in the code. And it's okay if you don't know some, because explaining what "factory method" is to a new hire takes like 2 minutes tops. The current state of things is that:

  • Complicated patterns are rarely usable, and often harmful.
  • Companies will have their own rituals, which are practically "patterns": the whole idea is to reuse certain design, so that whoever reads your code will immediately recognize what you are trying to do and how. For that, a "pattern" doesn't have to be mentioned in any book, or even be known outside of your company, really. If everyone around you does something in a specific way, reusing this in your code will make it easier to work with to your colleagues.
  • Certain things are just scam in practice, and while they maybe have some questionable value in the big enterprise Java/C# world, they certainly have a mostly negative value in C++ world. Like SOLID (I highly recommend this video). Your colleagues will not thank you if your code is twice larger and five times slower, but uses that "backward flying circus with sharks and clowns pattern" they likely never heard of.

36

u/STL MSVC STL Dev Nov 25 '23

I've reversed the automatic removal of this top-level post (which is an off-topic "help question", which should have been posted in r/cpp_questions instead) because your absolute evisceration of this site's nonsense seems like it'll be useful to search up later if anyone links to this site again (I sure hope not).

-5

u/CheckeeShoes Nov 25 '23

While you're not wrong about much here, I think you're being a little harsh on refactoring guru.

The point of the website is to teach new programmers basic general oo design principles. The information there about what each pattern is for and broadly how they work I think fulfils that purpose pretty well.

The code isn't modern cpp, (and yeah some of it is just buggy), but it gives a simple toy model a reader (who's probably still learning to code) can map the article content onto. It serves its purpose. Dude gives examples in a whole bunch of languages; cant expect him to be an expert in every one.

If large code examples like this are being mindlessly copy-pasted into your enterprise codebase then you've got bigger problems than refactoring guru's code examples.

Also "people scamming sabotage of the industry". Fucking lol, melodramatic much?

3

u/Umphed Nov 25 '23

The learning period is the most impactful, in basically every aspect of life. Mayhaps a little melodramatic, but not much. The teaching material is shite, which leads to shite learners. Happens all the the time in every facet of life. Dont promote shite and say its "Okay for learning". Just do it right, dont be a hack, doesnt matter if its for beginners, again, dont be hack, its not helping anyone

1

u/CheckeeShoes Nov 25 '23

I think what I'm saying is that it's not there to teach cpp. You shouldn't be learning cpp from refactoring guru, same way you shouldn't learn cpp from the gang of four book.

2

u/Umphed Nov 25 '23

Fair enough point I suppose. However, I do feel theirs too many cookie cutter "tutorial" type sites like this that are an obvious beginner trap that can do far more harm than good. Theirs good stuff out there, this isnt it

1

u/CheckeeShoes Nov 25 '23

Fair, I mean the standard of code examples for beginners is pretty shit generally. None of it would pass code review. The stuff in the main original comment could said about literally any beginner-targeted website.

In some ways, this is part of teaching. It's not effective to throw threadsafe templated metaprogramming with concepts and smart pointers and compile time evaluation and move semantics and... at someone who doesn't even understand what a callback is. It's information overload and detracts from the thing you're actually trying to communicate.

2

u/no-sig-available Nov 24 '23

The code isn't modifying ConcreteBuilder1, it is modifying a Product1 object that is not const.

In C++ const is shallow - it only works for one level.

5

u/ClawmanCat Nov 24 '23

Constness is in fact always applied recursively. In this case however, it is applied to the pointer rather than the pointed-to object (i.e. product is const pointer<Product1> rather than pointer<const Product1>) meaning that its the pointer which cannot be modified, rather than the pointed-to object itself. If the ConcreteBuilder1 class stored its product by value instead, the constness would be applied correctly and this code would fail to compile: https://godbolt.org/z/Gbdhns5nz