I'm trying to create functionality for a Chunk (Like the chunk we see in Minecraft that consists of 16x16x256 blocks).
How should i go about doing that while achieving the Single Responsibility Principle?
Functionality includes things like loading, saving, creating a mesh and keeping track of all the blocks.
Should i
Create a Chunk class consisting of many classes, each with one of these functionalities like loading or saving. Then initiate the classes in the Chunk class. What do i do when these classes needs functionality from the Chunk class, won't that break SRP?
Create all functionality in the Chunk class
So, if we're talking general pointers here then there's some simple things to start with.
Chunk
class should only deal with its primary responsibility - managing whatever is contained within aChunk
.ChunkGroup
, potentially using an Adapter pattern on the Chunk, which aggregates a 'network' ofChunk
s.Chunk
objects should exist. This is not the responsibility of theChunk
itself, but may involve an inner class which allows converting aChunk
into something which can be (de)serialised.So, I'd be expecting to see something like
The points to note about the SRP here:
Chunk
objects into a separate class. There are different ways of managing such kinds of networks, you may want to change that later. You can do so without altering how theChunk
itself works.ChunkNetwork
may have different methods depending on your usage, and that may inform how you choose to implement the interface, but the key point is that network management is outside of theChunk
itself.Chunk
objects are represented in XML or JSON (or whatever, on disk, in a file) is a separate concern from what the API of theChunk
is. However, with libraries like Jackson we can often get away without defining a separate class for marshalling/unmarshalling. If yourChunk
implementations become complex you may want to however.Ultimately, the SRP says that any individual class should have one reason to change. So you need to look at your functionality and look at why it might change. Typical reasons are:
Chunk
interface.Chunk
s using a tree structure). Equivalent to a change in (or reimplementation of) theChunkList
class.As a rule of thumb, if you find yourself describing a class using more than a single sentence or using a conjunction ('and', 'but', also punctuation like commas) then you're probably seeing a violation of the Single Responsibility Principle. A further rule of thumb is to take each one of those sentences / conjunctions and try to isolate them into a single class. Then see if that class violates the SRP. Rinse & repeat until nothing violates the SRP.
Sounds simple but, like chess, it takes minutes to learn but a lifetime to master.