0

I have two interfaces: MinServer and MaxServer. MaxServer extends MinServer. So, is the following code normal and right?

MinServer server=foo.getUndefinedServer();
...code according to MinServer
if (isThisServerMax){
  server=(MaxServer)server;
...code according to MaxServer
}
...code according to MinServer
  • Can you elaborate? I don't understand. Your reminds me of typical examples of LSP violations: http://stackoverflow.com/questions/20861107/liskov-substitution-principle-vehicle-example though – zapl Nov 26 '14 at 20:43
  • @zapl I have a client, that can connect either to remote server with minimum rights or to local server with maximum rights. The server type is taken from configuration. So in code I want to use this approach. If it's min it do minimum, otherwise maximum. –  Nov 26 '14 at 20:49

3 Answers3

2

No, it is not correct.

At this point:

server=(MaxServer)server
...code according to MaxServer

You are casting a MaxServer to a MinServer (which is OK) but then you assign the result of the casting to a MinServer ... so ehhm, you are in the same point where you started.

If you change it like this:

MaxServer server2 = (MaxServer)server
...code according to MaxServer using server2

then it will be correct.

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • Maybe you wanted so say "You are casting a MinServer to a MaxServer which is ok"? –  Nov 26 '14 at 20:54
  • @PashaTurok No, I wanted to say it as it is there. It is OK to do the cast at that point as he has already validated with that `if` that the cast will not throw an exception. – Daniel Nov 26 '14 at 20:55
  • Then I don't understand you. We are casting MinServer to MaxServer. I think so. –  Nov 26 '14 at 20:57
  • @PashaTurok You cast from `Min` to `Max`, and then you assign it to the variable `server` which is a `Min` so you are again where you started. – Daniel Nov 26 '14 at 20:58
0

No.

If the isThisServerMax is a boolean variable that correctly indicates whether server's class implements MaxServer, then everything actually shown will run without error. However, nothing you present establishes a context wherein methods can be invoked on server that do not belong to interface MinServer, as I suppose is the intended meaning of "code according to MaxServer".

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

There is nothing wrong with the downcast you are doing. It will compile fine. Just know that if it can't be downcasted it will throw a runtime exception that you should handle. If it is not actually a MaxServer then it will throw an error...

brso05
  • 13,142
  • 2
  • 21
  • 40