Single Responsibility Principle the correct approach - oop

SRP really bug me. I know how to find responsibility what I dont know is how to assemble them correctly
e.g
class Modem{
public void dial(){//code here}
public void hangup(){//code here}
public void send(){//code here}
public void recive(){//code here}
}
In this common example we have connection and communication responsibility. So we divide that into 2 new interfaces
interface Connection{
public void dial();
public void hangup();
}
interface Communication{
public void send();
public void recive();
}
implement them:
class SimpleModemConnection implements Connection{
public void dial(){//code here}
public void hangup(){//code here}
}
class SimpleModemCommunication implements Communication{
public void send(){//code here}
public void recive(){//code here}
}
and at this point I dont really know how client code should look like
Do I aggregate those intefaces into Modem class ?
class Modem {
Connection connection = new SimpleModemConnection();
Communication communication = new SimpleModemCommunication();
}
main(){
Modem modem = new Modem();
modem.connection.dial();
modem.communication.send();
modem.communication.recive();
modem.connection.hangup();
}
Do I use them directly
main(){
Connection connection = new SimpleModemConnection();
Communication communication = new SimpleModemCommunication();
connection.dial();
communication.send();
communication.recive();
connection.hangup();
}
Or is there some other way?

I am afraid you may be overthinking this. A Modem needs to both connect and communicate. Unless you know of and expect a situation where these two can be separated out, there is simply no point in splitting this up. At the end, these principles should not be the primary driving force of your design. That should be your knowledge of the domain and the kind of changes you expect in the system.
So what you need to answer is if your Modem class would ever need to swap out its connection/communication subsystems?

This can be very confusing some times. I struggle with the same questions daily, but it's good that you think about it. I have been actively pursuing the use of the SOLID principles along with my TDD practices. One thing that it seems like you are not thinking of here is who will be using your modem, unit tests and actual object users in code.
In my mind it works like this. Modem has the responsibility of Dialling, hanging up, sending and receiving data, so those are the functions exposed to the user of you API (with the exception of Receive), whether it be your unit tests or your in code user. Therefore the following would exist.
IModem.cs
interface IModem
{
public bool Connect(); // Seen in your code as dial
public void Disconnect(); // Seen in your code as hangup
public void SendData(); // Take data as parameter
// Receive will not be public, instead I would make it call out to the user saying "I have received data for you"
}
This clearly states that the responsibility of your Modem Object is to Connect, Disconnect and Send data to where it needs to go. Now whether the modem does the connection and communication is the other question. I would say that what you have with your SimpleConnection and SimpleCommunication modules are perfect (I would change the naming a little ;) ). Connection becomes IConnectionModule and Communication becomes ICommunicationModule, as well as some function name changes. dial to Connect, hangup to Disconnect and send to SendData. Having that in mind I take the following approach.
Responsibility of my Modem: My modem will use the modules it has to connect the user to a remote host, as well as disconnect from the host or send any data necessary.
The definition above then results in the following code.
Modem.cs
class Modem : IModem
{
private IConnectionModule _connectionModule;
private ICommunicationModule _communicationModule;
public Modem(IConnectionModule connectionModule, ICommunicationModule communicationModule)
{
_connectionModule = connectionModule;
_communicationModule = communicationModule;
}
public bool Connect()
{
bool connectionSuccess = _connectionModule.Connect()
return connectionSuccess;
}
public void Disconnect()
{
_connectionModule.Disconnect();
}
public void SendData()
{
_communicationModule.SendData();
}
}
Looking at the above you can lay out the responsibilities as follows:
Modem: Serves as a bridge between the user of the API, allowing the user to send and receive information.
Connection Module: Connects the modem to a host (The user will never use this, the only user to use this will be it's unit test suite and the modem)
Communication Module: Sends information to an already connected host (The user will never use this, the only user to use this will be it's unit test suite and the modem)
The reason for "hiding" the modules from the user is because no user of a modem has to know about which connection module is being used. All you should have to do is call Connect/Disconnect and the functionality should be supplied. The rest should all be "invisible". Again, this depends solely on your development style but I always try to keep things nicely separated and make sure I always have one action per call. Whether it's farmed out to a different object or done within the class itself.
I hope this helps, let me know what you think, I am always up for discussions on designs and SOLID principles.

Related

How to create actor with parameterized constructor from testprobe

I am trying test to MyActor for sending a MessageB to itself on condition. MyActor takes setting as constructor parameter. Setting doesn't have setter cause it is intended to be immutable after creation.
public class MyActor : ReceiveActor
{
private bool Setting { get; }
public MyActor(bool setting)
{
Setting = setting;
Receive<MessageA>(message => HandleMessageA(message));
}
public void HandleMessageA(MessageA message)
{
if (Setting)
Self.Tell(new MessageB);
}
}
And here is the test
[Test]
public void HandleMessageA_SettingIsTrue_MessageBIsSent()
{
bool setting = true;
var testProbe = this.CreateTestProbe();
var myActor = Props.Create<MyActor>(testProbbe);
myActor.Tell(new MessageA);
myActor.ExpectMsg<MessageB>();
}
My problem is that i don't know how to pass bool setting to constructor.
Well I can write it like this
bool setting = true;
var myActor = Props.Create<MyActor>(setting);
And this way myActor will have settings set. But than I didn't use TestProbe and therefore will not be able to listen for expected message. So my question is how make Arrange section of test correctly?
A great guide to testing with Akka.NET describes how to create actors within the test system:
Create your actors within Sys so that your actors exist in the same
ActorSystem as the TestActor.
// create an actor in the TestActorSystem
var actor = Sys.ActorOf(Props.Create(() => new MyActorClass()));
Well the situation you have created is rather artificial. Because in a real world scenario you would either send MessageB to another actor. Which you would then be able to substitute with a TestProbe. Or you would verify the sideeffect that your messageB would have. So for example sending messageB to Self, would update some property on your actor, which you could then Test for.
Also see Chima's response, he shows the correct way to create your actor. Because only instantiating the Props is not enough.
And some general advice. When testing actors, you will want to try to refrain from testing for individual messages. Try and test the outcome (or side-effect) of sending those messages instead. That way your tests are a lot less brittle should you ever refactor your Actor's interactions

Apache tomcat stop

In Apache you can configure that operation will be load using the load_on_startup tag.
I want also when stopping Apache to do several operation using the stop tomcat command.
Is there something like that ?
10x
The closest I can think of is "Finalising a servlet"
http://docs.oracle.com/javaee/6/tutorial/doc/bnags.html
Notifying Methods to Shut Down
To ensure a clean shutdown, your destroy method should not release any shared resources until all the service requests have completed. One part of doing this is to check the service counter. Another part is to notify the long-running methods that it is time to shut down. For this notification, another field is required. The field should have the usual access methods:
public class ShutdownExample extends HttpServlet {
private boolean shuttingDown;
...
//Access methods for shuttingDown
protected synchronized void setShuttingDown(boolean flag) {
shuttingDown = flag;
}
protected synchronized boolean isShuttingDown() {
return shuttingDown;
}
}
If you want to run code to handle Tomcat specific things, use a LifecycleListener, i.e. create a class that implements LifecycleListener.
If you want to to things when your application starts, use a ServletListener.

Nodemailer transport creation recommendation

I have a mail service class set up on an express server.
Which method of creating a transport is recommended?
class mailService {
private transport: nodemailer.Transport;
constructor(){
this.transport = nodemailer.createTransport('configstring');
}
public sendEmail(email: string){
//send email
}
}
OR
class mailService {
public sendEmail(email: string){
let transporter = nodemailer.createTransport('configstring');
//send email
}
public sendOtherEmail(email: string){
let transporter = nodemailer.createTransport('configstring');
//send email
}
}
The documentation say "You can reuse a transport as often as you like after creating it" Which leads me to think that the first option would be better, however can't tell if there would be any advantage.
Would simply creating the transport every time be an issue of repetition or will there be multiple instances floating around in memory, orphaned every time the sendEmail function is executed?
There is little advantage in using the second method. It might come in handy if you want to change the transport configuration between different sending jobs.
If that is not the case, it is recommended to stick to using a single transport (1st method) for sending emails according to the
DRY
principle.
You also shouldn't be concerned about memory here because Node has a garbage collector and memory will be freed after your sendOtherEmail() function ends.

Is it better to use the Bus Start method or a class constructor to instantiate objects used by a service

I'm using nServiceBus 5 and have created a number of host endpoints, two of which listen for database changes. (The specifics of how to do this can be found here). The intention is to have a service running in the background which publishes an event message using the Bus when notified to do so by the database listener.
The code which creates the database listener object and handles events is in the Start method, implemented as part of IWantToRunWhenBusStartsAndStops.
So - Is putting the code here likely to cause problems later on, for example if an exception is thrown (yes, I do have try/catch blocks, but I removed them from the sample code for clarity)? What happens when the Start method finishes executing?
Would I be better off with a constructor on my RequestNewQuoteSender class to instantiate the database listener as a class property and not use the Start method at all?
namespace MySample.QuoteRequest
{
public partial class RequestNewQuoteSender : IWantToRunWhenBusStartsAndStops
{
public void Start()
{
var changeListener = new DatabaseChangeListener(_ConnectionString);
// Assign the code within the braces to the DBListener's onChange event
changeListener.OnChange += () =>
{
// code to handle database change event
changeListener.Start(_SQLStatement);
};
// Now everything has been set up.... start it running.
changeListener.Start(_SQLStatement);
}
public void Stop() { LogInfo("Service Bus has stopped"); }
}
}
Your code seems fine to me.
Just a few small things:
Make changeListener a class field, so that it won't be GC (not 100% sure if it would be but just to make sure);
Unsubscribe from OnChange on the Stop() method;
You may also want to have a "lock" around changeListener.Start(_SQLStatement); and the Stop so that there are no racing conditions (I leave that one up to you to figure out if you need it or not);
Does this make sense ?

RAPI Approach: 1 static instance for the entire winforms app vs create,connect,dispose

In many places in our application we have code like this:
using(RAPI rapi = new RAPI())
{
bool connected = TryToConnectWithTimeout(rapi);
if(connected)
DoSomethingWithRapi(rapi);
}
This has worked well so far.
We never have more than 1 rapi instance at a time. Until now:
But now we want to listen for the connect event on rapi.
We are doing it like this:
void StartMonitoringRapiConnection()
{
_rapi = new RAPI();
_rapi.RAPIConnected += new RAPIConnectedHandler(_rapi_RAPIConnected);
_rapi.RAPIDisconnected += new RAPIConnectedHandler(_rapi_RAPIDisconnected);
_rapi.Connect(false,-1);
}
private void _rapi_RAPIConnected()
{
DoWorkWhenRapiConnects();
}
private void _rapi_RAPIDisconnected()
{
//Listen for the next time that rapi connects
_rapi.Connect(false,-1);
DoWorkWhenRapiDisconnects();
}
"StartMonitoringRapiConnection" works pretty well as long as I do not start to new up and connect other RAPI objects. But once I start newing up other RAPI objects, the connect/disconnect events seem to fire out of order.
Would it work better to have just 1 static instance of RAPI for the entire app? Do you have any other advice? Thanks.
Logically, RAPI is a single connection between the PC and the device. It doesn't make sense for your app to even support multiple connections. I'd make a Singleton class that wraps up the RAPI calls and makes all of your calls for you so that everyone that needs to talk to the device goes through that one class.