Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Dependency Injection (DI) and Single Responsibility Principle (SRP) are highly related. </p> <p>SRP is basicly stating that each class should only do one thing and delegate all other matters to separate classes. For instance, your <code>serializeMessageObjects</code> method should be extracted into its own class -- let's call it <code>MessageObjectSerializer</code>. </p> <p>DI means injecting (passing) the <code>MessageObjectSerializer</code> object as an argument to your <code>MessageQueue</code> object -- either in the constructor or in the call to the <code>consumeMessages</code> method. You can use DI frameworks to do this for, but I recommend to do it manually, to get the concept. </p> <p>Now, if you create an interface for the <code>MessageObjectSerializer</code>, you can pass that to the <code>MessageQueue</code>, and then you get the full value of the pattern, as you can create mocks/stubs for easy testing. Suddenly, <code>consumeMessages</code> doesn't have to pay attention to how <code>serializeMessageObjects</code> behaves. </p> <p>Below, I have tried to illustrate the pattern. Note, that when you want to test consumeMessages, you don't have to use the the <code>MessageObjectSerializer</code> object. You can make a mock or stub, that does exactly what you want it to do, and pass it instead of the concrete class. This really makes testing so much easier. Please, forgive syntax errors. I did not have access to Visual Studio, so it is written in a text editor. </p> <pre><code>// THE MAIN CLASS public class MyMessageQueue() { IMessageObjectSerializer _serializer; //Constructor that takes the gets the serialization logic injected public MyMessageQueue(IMessageObjectSerializer serializer) { _serializer = serializer; //Also a lot of other injection } //Your main method. Now it calls an external object to serialize public void consumeMessages() { //Do all the other stuff _serializer.serializeMessageObjects() } } //THE SERIALIZER CLASS Public class MessageObjectSerializer : IMessageObjectSerializer { public List&lt;MessageObject&gt; serializeMessageObjects() { //DO THE SERILIZATION LOGIC HERE } } //THE INTERFACE FOR THE SERIALIZER Public interface MessageObjectSerializer { List&lt;MessageObject&gt; serializeMessageObjects(); } </code></pre> <p><strong>EDIT:</strong> Sorry, my example is in C#. I hope you can use it anyway :-) </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload