I'm reading Elliotte Rusty Harold's Java Network Programming. In chapter2, I've read the text about makrSupported()
method of InputStream
class. The author explains that this method is not object oriented. Because the function for checking mark()
available is not provided by separated type. How is the design to be more object oriented still supporting mark()
and reset()
methods?
1 Answer 1
In a good object-oriented design, there is no need to ask an object if it supports a method like mark
or not. Instead, the interface- or class type of your reference should tell you exactly which methods your code expects to be able to use.
A more object-oriented design would be along the lines of
class InputStream extends Object
{
...
// no mark() nor reset()
}
class ResettableInputStream extends InputStream
{
void mark() { ... }
void reset() { ... }
}
The reason that Java isn't designed this way probably has historical reasons, such as that InputStream
with mark
/reset
was already in widespread use when a new derived class was introduced that couldn't support mark
/reset
and a strong desire to not break all existing code.
-
Yes, you're right. But sometimes, I may need to handle a bunch of InputSreams mixed with InputStreams and ResettableInputStreams. Using
instanceof
operator seems worse than before. In that case, how can I write OOP code? Or how can I avoid this case?jyshin– jyshin2018年01月01日 12:49:10 +00:00Commented Jan 1, 2018 at 12:49 -
@jyshin, if you don't need the
mark
/reset
behaviour, then you can treat them all as plain InputStreams. No need forinstanceof
.Bart van Ingen Schenau– Bart van Ingen Schenau2018年01月01日 14:18:47 +00:00Commented Jan 1, 2018 at 14:18 -
I would point out that promising functionality that doesn't exist is bad design generally, and good design of any sort will avoid it.Derek Elkins left SE– Derek Elkins left SE2018年01月01日 17:45:45 +00:00Commented Jan 1, 2018 at 17:45
-
@BartvanIngenSchenau Oh.. I got it. I think you mean use of
mark / reset
withInputSteam
(in your design) is also bad. If I needmark / reset
, I should do it withResettableInputStream
type. Did I get it right?jyshin– jyshin2018年01月02日 02:24:14 +00:00Commented Jan 2, 2018 at 2:24 -
@jyshin, yes that is right. In fact, in my design, it would be impossible to use
mark
/reset
on anInputStream
without casting it to aResettableInputStream
first.Bart van Ingen Schenau– Bart van Ingen Schenau2018年01月02日 08:26:59 +00:00Commented Jan 2, 2018 at 8:26