0

I recently attended a C++ talk on SOLID principles and the presenter provided std::string as an example that violates SRP. I wasn't quite able to comprehend why that was the case. From what I understand, std::string isn't a paragon for STL data structures, unlike std::vector etc., since it duplicates some free functions from the <algorithm> library like find, replace(with no customized specialization [Please correct me]), etc. but, in my opinion, it is still a cohesive bunch of functions to help manipulate strings. One possible argument I could think against it demonstrating SRP was that std::string allocates as well as manipulates strings, which could lead to issues mixing it with other instantiations of std::basic_string but I'm not sure if that's an apt defect in the context of SRP. Can someone please help elaborate on why it violates SRP?

4
  • 2
    I don't think it does. It has one responsibility: represent a string object. What was the speaker's argument? Feb 28 at 21:24
  • 3
    (1) Without linking to any materials from that presentation or the presenter, any argument we try to make here will just be straw man. (2) The claim elucidated by OP's best effort seems to say that OOP fundamentally violates SRP by bundling the various aspects that make up "object-ness" into a single entity. Which is valid, from a C perspective. What's wrong with malloc and strchr, after all? What's wrong with char* ? Different languages, different perspectives.
    – rwong
    Mar 1 at 4:18
  • 2
    I remember a post here along the lines "We decided to fully enforce SRP. Our code went from 70 classes to 700. What should we do now?". SRP in the wrong hands is very dangerous.
    – gnasher729
    Mar 1 at 9:35
  • For what it's worth, std::string's internal APIs are based on indices and counts, while the algorithms are based on iterators. Broadly speaking, people who have string code based on using indices don't want to transition it to iterators. So that's what those APIs are for. Mar 3 at 20:14

1 Answer 1

8

SRP isn't a well-defined thing. Bob Martin, the guy who came up with it is on his 5th or so attempt at defining it and it's still mostly just confusing with very little concrete points or even code.

So it all depends on who you ask. To put it differently: both sides could be argued. Not just for string, but for mostly everything.

2
  • 5
    That's why you should take everything Bob Martin says as suggestions, not edicts. Feb 28 at 21:30
  • 6
    What's terrible about Bob Martin's SRP is that the David Parnas article that inspired SRP is much clearer. Page 24: "We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others" kilthub.cmu.edu/articles/journal_contribution/…
    – user949300
    Feb 28 at 22:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.