I have Java (or C#, Python, Kotlin, or other similar language) class that will be used to communicate with client over network. Protocol used by this application allows many different ways to create connection (TCP, unix socket, serial port, …) and perform handshake (plain connection or TLS, with or without authentication). I use separate abstract class that will initialize the connection (called ConnectionStarter) and create instance of Connection. Connection will query the client for some information (this part is not dependent on used ConnectionStarter) and then allow communication with the other side.
Initialisation of the connection
ConnectionStartercreates the connectionConnectionStarterperforms handshakeConnectionStartercreatesConnectionConnectionqueries the client- the connection is initialized and
Connectioncan be freely used
The Connection will be always created by some descendant of ConnectionStarter.
The question is: Should I include the step 4 in Connection constructor or move it to separate function that has to be called?
Source code
abstract class ConnectionStarter {
Connection startConnection() {
Socket socket = inializeSocket(); // Step 1
performHandshake(socket); // Step 2
return new Connection(socket); // Step 3
}
abstract Socket initializeSocket();
abstract void performHandshake()
}
class Connection {
Socket socket;
Connection(Socket socket) {
this.socket = socket;
// ━━ The client will be queried now (Step 4) ━━
queryClient()
}
void queryClient() { … } // Step 4
}
// Accessibility modifiers are omitted for simplicity.