This got me thinking: is the String class a well designed class in terms of the general rules of Object Oriented Design? Does it, in fact, break the single responsibility principle or the laws of demeter and is it tightly coupled to all other parts of an application? Is it a God Object?
The easy way to answer this is to look at a in terms of the Single Responsibility Principle, and the best way to do that is to count the number of method calls it has and figure out what they do.
If you do that you’ll find that Java’s class has 66 method calls in it’s repertoire and you may conclude that a number this high could be the first sign of a God Object.
Next, if you look at these 66 method calls you can group them into several different areas of responsibility. For example there are:
Conversion Methods
Methods that split String
Equivalency Methods
Search Methods
Combining Methods
…and more besides.
Using the lists above, you could now write a CRC card for a that goes something like this: “A is responsible for combining itself with other s to create new s AND converting itself into other objects or arrays of objects AND splitting itself into different pieces AND comparing itself to other objects AND performing searches on itself”
Sticking to the letter of the law then the lists above show that method calls break down into at least five areas of responsibility, which means that, by the book, the Single Responsibility Principle has been violated.
Taking this to its logical conclusion, then you could refactor a to look something like this….
However, and this is the question, why isn’t Java’s class composed of some data and a bunch of classes that operate on it? The answer is both a matter of opinion and multifaceted. Firstly, history… Java as grown over time as so has the class; methods have been added piece-meal as the Java version number ticks ever upwards. Secondly, pragmatism. A object in it’s current design may break the Single Responsibility Rule, but it doesn’t matter, it’s easier to leave it as it is and get on with writing the programs that count. Lastly, and I think that this is important, we all generally know what a is. Its name and meaning is in common usage. If we had to define what a ’s responsible for using a CRC card, then we’d write something like: “a is responsible for being s ”.
A may have 66 methods, but I believe that by general consensus it’s not a God Object. However, software is just a matter of opinions, so I’ll leave you answer the other questions I posed at the beginning of this blog and to make your own mind up…
Reference: Is Java’s String Class a God Object? from our JCG partner Roger Hughes at the Captain Debug’s Blog .
Thank you!
We will contact you soon.
Roger HughesFebruary 27th, 2012Last Updated: October 21st, 2012

This site uses Akismet to reduce spam. Learn how your comment data is processed.