0

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?

2

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 Jan 1 '18 at 12:49
  • @jyshin, if you don't need the mark/reset behaviour, then you can treat them all as plain InputStreams. No need for instanceof. – Bart van Ingen Schenau Jan 1 '18 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 Jan 1 '18 at 17:45
  • @BartvanIngenSchenau Oh.. I got it. I think you mean use of mark / reset with InputSteam(in your design) is also bad. If I need mark / reset, I should do it with ResettableInputStream type. Did I get it right? – jyshin Jan 2 '18 at 2:24
  • @jyshin, yes that is right. In fact, in my design, it would be impossible to use mark/reset on an InputStream without casting it to a ResettableInputStream first. – Bart van Ingen Schenau Jan 2 '18 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.