Can I conclude, Class B doesn't obey single responsibility principle since it uses the concept of inheritance?
No. SRP focuses on each class having a single responsibility, e.g. that FooRepository
knows how to retrieve Foo
objects, but it doesn't e.g. know the specific implementation details of how to log messages when it can't find the object it's looking for. That secondary responsibility should actually be the (sole) responsibility of a different class, e.g. Logger
. Every class knows how to do one thing, and that's what SRP prescribes. Classes have one responsibility, and then some dependencies on other classes (each with one responsibility) if they need to do more than just one thing.
SRP doesn't focus on the inverted, i.e. two classes having a similar (but in some way different) responsibility. What you're thinking of is DRY (Don't Repeat Yourself), which focuses on needless code repetition.
Although these two similar-but-different classes would usually violate DRY in some way, they don't violate SRP. And that's regardless of whether these two classes have a common ancestor or not.
I.e certain changes happen to Class A will require changes to Class B as well?
That's just not how inheritance is supposed to work. In a clean codebase, the only changes to A that necessitate changes to B are changes made to the contract of A. The consequences of such changes (i.e. needing to change B) is unavoidable; regardless of SRP.
If non-contract changes in A cause you to have to make changes in B, then you're not implementing inheritance properly (or cleanly). Even in an inherited hierarchy, each class has its own responsibility. They're closely related on a functional level, but they don't actually overlap. The entire point of inheritance is to divide the (otherwise combined) class' responsibilities into two separate chunks.
Hence the responsibility for these changes is shared between Class A and Class B?
"Responsibility for changes" isn't a concept, certainly not in regards to SRP.
Changes to a public contract will always lead to (possibly) needing to change the usage of this contract by your consumers. That's just a logical and unavoidable fact, by definition of what a contract exactly is.
What SOLID principles does this code obey and can some body help me in a better understanding the SOLID principles?
This isn't really answerable based on your snippet.
- (S) Responsibilities are not clearly delineated, context isn't clear; cannot discern what is a single responsibility and what is a conflation of responsibilities.
- (O) Can't be decided based on only seeing a derived class and not its base. The intention of the inheritance seems to adhere to OCP but that's just a wild inference.
- (L) No use of polymorphism in the shown code. Unsure what the consumer's expectations of the base class are and how it's intended to be consumed.
- (I) No interfaces used in the shown code
- (D) No dependencies used in the shown code