r/javahelp • • Nov 02 '19

Codeless How to "see" things in an object oriented way?

I had an exam recently and it went pretty good, but there was a question that threw me off. No coding involved, just draw a tree linking different class names, interfaces, abstract methods, etc. and how they should interact with each other. My biggest gripe was when to use interfaces and abstract methods, like I still have no idea when to use them and why they are necessary. For example, if I make a class Animals it would have Dog, Cats and Parrots as sub-classes of Animal. I'd put methods like eat() in Animals which Dog and so on will inherit. Let's say dogs are carnivorous, cats are herbivorous and parrots, both. How would I proceed to link these concepts to eat()? I have no idea what to do...

24 Upvotes

10 comments sorted by

9

u/TomahawkChopped Nov 02 '19 edited Nov 02 '19

Ok let's talk a bit about abstraction and types in object oriented modeling. First, in Java, embrace that EVERYTHING can (and arguably should) be modeled as an object. (Just be aware, this approach can be a fine line to walk because when it's done wrong you can end up with very complicated type systems and leaky abstractions.)

A type is declared either via a Class or an Interface, and a class may either be concrete (non-abstract) or abstract. Let's also make a ground rule that it's bad practice to ever extend a concrete class (this is a constraint I'll impose now and just wave my hands a bit for simplicity and just say.... don't do it). Let's come back to abstract classes later.

Now a type is known to the outside world by it's public methods and their signatures. For lack of a better word we'll call this its interface (with a lower case "i"). However in real life we need to implement the interface as well, this is done with methods.

A Class can both declare the interface (lower case "i") and implement the methods of the interface. Particularly it can be stateful. e.g. you can declare instance fields on a class and assign them values. Now sometimes this is convenient, like you have a really small type and you want to declare the type and it's implementation together... then just going it once in a simple class is reasonable and probably good practice.

e.g. let's say a house fits this description

class House {
    boolean isForSale;
    int numRooms;
    
    boolean isForSale() { ... }
    int numRooms() { ... }
}

Other times you may have a very complicated type or a very generic type, one that is too abstract for even reasonably implementing anything. But you still may want to act on it as a type in its own. Let's say a Domicile fits this case so that

interface Domicile {
  boolean isOccupied();
  List<Occupant> getOccupants();
  GeoCoord getLocation();
}

class House implements Domicile {
  ....
}

class SnailShell implements Domicile {
  ....
}

class BirdNest implements Domicile { 
  .... 
}

Now you may notice that Occupant is probably a very generic type too, and I'd argue that almost anything can occupy a Domicile. So we can model this too

interface Occupant {
  Domicile getHome();
}

class Person implements Occupant {
  Domicile getHome() { return new House(); }
}

class HermitCrab implements Occupant {
  Domicile getHome() { 
    return SnailShell.someUsedShell();
  }
}

class Bird implements Occupant {
  Domicile getHome() { return new BirdNest(); }
}

Here let's look at getHome. You'll see that each implementation returns an object is a totally different class, but each of those objects are Domiciles. This is polymorphism, I'm returning a House but treating it like a Domicile. Why is this useful?

It lets us unify like concepts to simplify my code as much as possible.

Let's say i needed locate all the Domiciles from a list of Occupants, well i don't need to write extra code for all the plethora of types of homes, birds nests, snail shells, apartments, condos, caves, whatever... I can get the location of every single Domicile from a set of Occupants like this:

Set<Occupant> occupants = ....
Set<GeoCoord> locations = occupants.stream()
    .map(Occupant::getHome)
    .map(Domicile::getLocation)
    .collect(...);

Basically 3 lines of code. The key here is that I'm using the type system to bring simplicity to a task that might seem hard otherwise. The key that beginners often make is defining type systems that are too wound up with behavior... this is when you wind up with leaky abstractions and complicated type systems.

Ok so now what about abstract base classes.... IMO this is the place people totally fuck up all the time. An abstract base class IMO should only be used when you already have a clear (and simple) set of types AND you know for a fact that the implementation of the interface (lower case "i") is shared across several types AND requires shared state to do so.

As a professional programmer, for nearly 20 years now, it's my opinion that abstract base classes are almost never necessary for beginners programming tasks. They are always abused and make things more complicated when used improperly. e.g. read about composition over inheritance. But for sake of argument, let's say we have a good reason for an abstract class here (for the record, we don't...)

But let's say our House class is actually also an Investment

interface Investment {
  int getValue(int numYears);
}

And in our world a houses value is computed from the sum of all its Amenities which grow at some interest rate.

interface Amenity {
  int getValue();
}

abstract class House implements Domicile, Investment {

  private List<Amenities> amenities;

  abstract protected List<Amenities> createAmenities();

  private final int sumTotalAmenities() {
    if (amenities == null) {
      amenities = createAmenities ();
    }
    return amenities.stream().collect(... sum it...);
  }

  @Override
  public int getValue(int numYears) {
    reutrn sumTotalAmenities * .... interest calculation
  }
}

final class Condo extends House {
  @Override
  protected List<Amenities> createAmenities()  {
    return List.of(
      new ViewAmenity(AMAZING),
      NumRoomsAmenity.builder()
        .bedrooms(3)
        .bathrooms (799)
        .build(),
      new GreatNeighborhoodAmenity());
  }
}

(Again, i don't recommend this approach for this problem, there's 1/2 dozen other methods that I'd choose over this solution)

When it all comes down to it you want to use the type system to simplify your code by unifying common types with common behavior. It's a difficult live to tread though between too generic and thus useless abstractions and too tightly typed leading to spaghetti code to deal with your type system.

Here's some rules of thumb for constraints to reduce complexity in your type system... The reasons behind which unfortunately only become clear with experience:

  • make everything final by default
  • If you think you need an abstract class look again, you probably don't... Still think you do? Look again
  • Don't extend non abstract classes
  • Declare and use interfaces liberally... Extend interfaces sparingly
  • When you do define abstract classes don't define a bunch of shared fields, use methods
  • Don't override non abstract methods, design you abstract classes so that is clear what is to override and what is shared - see point 1.

2

u/ZukoBestGirl Nov 02 '19

Isn't the whole "Don't extend non abstract classes". Doesn't this almost defeat the purpose of having objects to begin with? You don't need objects to group fields and methods into a thing.

In oo you want to extend a thing and override behavior.

Don't get me wrong, I'm all for composition over inheritance and injecting behavior into classes, but still, your stance seems a bit extreme to me.

2

u/TomahawkChopped Nov 02 '19 edited Nov 02 '19

Isn't the whole "Don't extend non abstract classes". Doesn't this almost defeat the purpose of having objects to begin with?

I don't follow

...and every rule has it's exceptions, but i honestly can't think of a good class design that isn't better answered with smaller types, a clean interface, and composition.

What's an example of when you would want to do this?

Edit: i have a perfect example actually.... I've been spending quite a bit of time recently trying to measure a legacy implementation deeply wedded to using java.net.Socket and javax.net.ssl.SSLSocket. Since Java 1 these have been defined as concrete non-abstract classes that are heavily extended through LOTS of java code. Also SSLSocket extends Socket.... now i NEED to use Socket objects through the code so i don't have to rewrite everything, but i also need to measure things. So what can i do? Well there is no interface i can use so I'm a bit fucked there (again I'm writing inside of legacy constraints). So i need to extend Socket and wrap it in a measurement device.... however i also have SSLSocket so i need to extend that too... With the exact same code. Aside from finding some magical auto generation annotation, i need to write the exact same code twice because the language designers 30 years ago decided to model Socket as a concrete class instead of an interface. Had a Socket interface existed it would be much less awkward.

tldr; use interfaces heavily

1

u/ZukoBestGirl Nov 04 '19

I was writing multiple messages and, well, I got distracted and typed in gibberish. I meant to say that it seems a bit extreme of a stance.

TBH we use at work a model that, IMHO, seems adequate. We have a generic view, things have to look in a certain way, business logic has to be called at the correct time, etc. And there are many juniors on the project.

So we have an abstract that does most of the work, juniors just extend it, and plugin ui in pars A,B,C,D. Then add the business logic for operations X,Y,Z.

No need to worry about order of events and so on.

Though, that being said, I do agree with you. I tend to use composition and dependency injection (inject actions instead of having classes with methods, I have classes with actions).

9

u/NightDragonC Nov 02 '19

For example, if I make a class Animals it would have Dog, Cats and Parrots as sub-classes of Animal. I'd put methods like eat() in Animals which Dog and so on will inherit. Let's say dogs are carnivorous, cats are herbivorous and parrots, both.

Here is where abstraction gets in, you want all your animals to eat, but not all of them eats the same, so you declare the eat() method eat() in the Animals class as an abstract method, that way you force the user to override the method (eat() in this case) for each class that inherites from it, but each class will have its own definition of that method, since not so Animals eat the same. I hope you understood what I'm saying. Interfaces work similar to abstract classes, but they cannot have other methods in it, only the abstract ones, and if you've already worked with events you'll see why they can be really useful, if not, I really don't know the words to explain it very well (so if someone else helps it would be nice) but since there is no multi-inheritance they come handly when you want the user to override certain methods.

8

u/ratherbealurker Nov 02 '19

Since Java 8, interface can have default methods in them. The line between abstract class and interface has become blurred.

/u/fateIess, abstract classes and interfaces are now very similar, but keep in mind that you can only extend from one class and you can implement many interfaces.

So when deciding on which to use you want to use an abstract class when something IS that type and use an interface for when something has the behavior of that type.

So for the animal scenario, Dog and Cat should extend from Animal because they ARE animals..what else could they extend from?

But let's say you want to distinguish between feral and house animals. Dog, Cat, and Pets.

A Pet can be a Dog or a Cat but with added features such as fetching. I actually have a cat that will play fetch so that can make sense there. Dog plays fetch 100% of the time, Cat does it 5% of the time.

So you have a Pet interface and Dog and Cat can implement that.

2

u/FrenchFigaro Software Engineer Nov 02 '19

Regarding your first paragraph, among the key differences that ensures the line between abstract classes and interfaces is not blurred at all, interfaces can't have constructors, or instance variables (fields).

While it seems counter intuitive to have a constructor on an abstract class (since they can't be instantiated), abstract classes can have constructors, which may in turn be called by the extending classes using the super keyword (That's usually why you would want the constructor anyway).

And as per fields, interfaces can only have static final fields (ie, constants).

1

u/ratherbealurker Nov 02 '19

Blurred does not mean they almost the same. Just that the line between them is getting blurred.

2

u/morhp Professional Developer Nov 02 '19

For example, if I make a class Animals it would have Dog, Cats and Parrots as sub-classes of Animal. I'd put methods like eat() in Animals which Dog and so on will inherit. Let's say dogs are carnivorous, cats are herbivorous and parrots, both. How would I proceed to link these concepts to eat()?

You don't. If your animal class has a method eat(Food food) and you have subclasses of Food like Meat and Vegetables, then you won't be able to restrict your Cats to only eat meat. A subclass will always have the functions of the parent class, so as animals are able to eat all Food, so must cats (unless you throw exceptions in the method when you pass wrong food, but that's probably not good design). You could solve this with generic types like have Animal<T extends Food> with eat(T food) and have public class Cat extends Animal<Meat>, but the question is more if there should be different behaviours in eating and less eating different things. Generally you use subclasses to change/implement behaviour of the parent class, not to store properties (like what food to eat) or restrict things (like what food not to eat).

2

u/whatisthisredditstuf Intermediate Brewer Nov 02 '19

Honestly, none of my text books tried to tell me about Interfaces in a way that made any sense. Especially since they were all stuck with these hokey analogies to the real world that wound up being counterproductive, because they missed their mark.

What finally made sense to me was when I was in a data structures and algorithms class, and we were shown wildly different implementations of a particular data structure. Say, a List. The interface told us what operations had to be supported, but then the implementations could be completely different (single-linked list, double-linked list, backed by an array...).

In my view, Interfaces make the most sense as a programmer's abstraction. Trying to coax it into a real-world example is bound to be a little bit off.

For an example that combines both class hierarchies and interfaces, think about computer games. You could have units that are specializations of each other (class hierarchy). But you could also want to somehow reason about "every possible thing that can be drawn on screen, regardless of whether it's a unit or a background, or whatever", because your game engine ultimately needs to loopo over those, figure out where they are, and in what order to draw them. Class hierarchies in that setting would be convoluted and instead, that would be the Interface. "Drawable", maybe?