r/javahelp • • Jan 02 '16

How to think in OOP?

Hi all! When I write some app in Java, I have code in 2-3 classes. When I see how more expirienced programmers write similar apps, I see an hierachy of types, using of interfaces, abstract classes, all classes are small and understandable. I seem to understand all of these conceptions when I see someone's code but when I write myself I can't create something similar.

19 Upvotes

15 comments sorted by

8

u/Joha_Mraadu Employed Java Developer Jan 02 '16

4

u/MegaGreenLightning Jan 03 '16

I've read both Effective Java and Clean Code and highly recommend them as well.

There's also Agile Software Development (by Robert C. Martin): http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445/ref=sr_1_1?ie=UTF8&qid=1451828712&sr=8-1&keywords=agile+software+development

This book contains among other things a description of the SOLID principles of software design. For example the Single Responsibility Principle tells you that each class should have only one responsibility. This reduces coupling and leads to small and more easily understandable classes. The book also contains some nice case studies showing how to apply these techniques.

While Clean Code deals with writing code and how to design methods and classes, Agile Software Development tackles the topic at a higher level and discusses how to develop and design software consisting of different classes and packages etc. It requires a basic knowledge of programming and OO, though.

Robert C. Martin has also created a series of purchasable training videos at cleancoders.com. These videos cover the topics of both books starting with the rules for clean code and then going into the SOLID principles and other advanced topics.

0

u/[deleted] Jan 02 '16

[deleted]

2

u/Joha_Mraadu Employed Java Developer Jan 02 '16

I learned Python at CodeAcademy:
https://www.codecademy.com/learn/python

These books are generally good, but I cannot comment on quality of this one:
Head First - Python by Paul Barry
http://www.amazon.co.uk/Head-First-Python-Paul-Barry-y/dp/1449382673/ref=sr_1_1?ie=UTF8&qid=1451758567&sr=8-1&keywords=head+first+python

You better head to /r/LearnPython and /r/Python though :)

3

u/king_of_the_universe Jan 02 '16

It comes natural to some, but in general what you need is lots of experience/practice. I suggest you try this: In the years to come, from time to time do a (small) project several times. Usually, first when you do a project, the goal is to get it functional and ultimately finished or at least to a state where you can live with what it does. But when you do it several times, inevitably part of the goal becomes to create good code, which is the very goal that you have right now. So, that's what you should try, I think.

3

u/[deleted] Jan 02 '16 edited Jan 13 '26

jar door exultant quickest memory afterthought cow angle water zephyr

This post was mass deleted and anonymized with Redact

1

u/[deleted] Jan 04 '16

I'm sure people will nitpick at that explanation, but I think it's the perfect "elevator pitch" for OOP.

1

u/mariox19 Jan 07 '16

I've seen people nitpick that explanation, but the complaints usually come down to what Jobs "left out"—things like inheritance, and so forth. What these critics miss is the major point, which is that Jobs explained OOP from what is perhaps one of its most important points: namely, that you give an object what it needs to get the work done and not trouble yourself with how it does it.

My guess is that there would be a critic or two who would miss that point entirely and code something like this:

Launderer launderer = new Launderer();
String location = launderer.getLaundryLocation();
Double costPerLoad = launderer.getLoadCost();
List<int> availableWaterTemperatures = launderer.getTemperatureOptions();
// etc.

Jobs is talking OOP design:

Launderer launderer = new Launderer();
CleanClothes clothes = launderer.doLaundry(dirtyClothes);

2

u/[deleted] Jan 03 '16

Writing clean code comes with experience and discipline. Just keep coding, reading, and learning and you'll improve. I'd bet that in a year from now when you look back you'll be amazed at how far you've come.

On a side note, you may find that other paradigms and styles come more naturally to you. For years I programmed in OOP languages (i.e. C++, Java, Python), but I always found the designs ended up overly complex (class/type explosion) and more difficult to reason about (object state) than I thought they should. I began to notice a pattern wherein I was using more functional concepts (static methods in Java to make more pure functions or creating basic interfaces and then using anonymous classes like closures, etc.), so I decided to take the dive into a more functional set of languages (Erlang, Clojure, Scala). Now I find it more difficult to go back...

1

u/hugthemachines Jan 03 '16

I really think that sounds like you found your thing.

Definately a better love story than Twilight.

1

u/[deleted] Jan 03 '16

Yup. Although it's not too difficult to find better love stories than Twilight.

3

u/[deleted] Jan 02 '16 edited Jan 03 '16

Quick crash course:

  • object: A piece of your application. This has a state and can do things. Objects are your lego bricks.

  • class: A mold that you can use to make an object.

  • method: A thing you can make an object do

  • field: Part of your object's state

  • abstract: Part of a class, that can be mixed and matched with other classes.

  • interface: A set of requirements for class, to which you can claim your class adheres.

  • static: A tool that comes with the class.

  • final: Something that's inherent to an object or its class, and is not ever expected to change.

  • private: accessible from the current class or objects made from it

  • protected: accessible from the current class, any molds that derive from it, or any objects made from either.

  • public: accessible from anywhere

  • annotation: metadata about a class, a field, a method, or some other part of the mold

The key thing here is to think of Objects as the legos, and not classes. Classes are a template for Objects, but shouldn't contain much information themselves (i.e., the majority of your static methods should be factories for making objects).

Interfaces are important in a number of use cases:

  • Providing an implementation-agnostic anything (e.g., say your application is designed to run against any database you have an implementation for; you'd create a Database interface, and pull in the class by a set of configuration options, one of which specifies the classname for the Database implementation. This way, your application never needs to be aware of what database it's acting against. When writing tests that require a Database connection, you can create a dummy or in-memory implementation of the Database, and run your tests against that.

  • If your application has any kind of plugins system, those plugins will need to build against a set of interfaces your application provides. If you were to package implementations (concrete classes) instead, each plugin's behavior would vary, based on the version it was built against.

  • Most methods that accept an instance as an argument, should arguably accept an interface instead; this way, those methods can behave in a reliable way across many different implementations. For example, if you have doAThing(ArrayList a), you're limited to doing things with ArrayLists; LinkedLists, Stacks and Vectors need not apply. You could switch to doAThing(List a), which would allow any of these. In fact, depending on what doAThing is intended to do, you may be able to go more generic, and write doAThing(Collection a), which would enable Sets, Deques, and anything else that implements Collection and looks vaguely like an array of things.

Abstract classes are useful for providing common functionality between a group of similar classes - that is, you don't have to write getName() for fifty different types of NamedThing. The difficulty is that you can only extend one thing at a time, which is why Java 8 introduced default implementations in Interfaces. Most of my newer code doesn't bother with abstract classes (there are useful exceptions, mostly surrounding the fact that you can not mix two interfaces with the same default implementation name declared).

Final note: Learn Collections - specifically, List, Set and Map. These are arguably the most important parts of Java, and effectively using them requires you to learn the basics of object orientation.

1

u/someonesopranos Jan 05 '16

your answer is too good for every level programmer! Thank you.

1

u/empire539 "empire"+(((int)-~(byte)+('\''&~'&')<<(' '>>('+'+~'(')))+0x1b); Jan 02 '16

Try to break down your design into small pieces. If there is something needed in your project that has a specific functionality, then it's better to just make a class for it. If multiple things share common functionality, consider using an abstract class or interface.

Oftentimes, the class hierarchy or structure you see in a program may stem from the programmer's use of various design patterns.

1

u/jstock23 Jan 02 '16

You need to assess on an application to application basis what is best. If you have the need for a few different types of classes that share similar functionality, you can do so by creating a more basic class and then extending it. This isn't necessarily the case however.

You can also "hide" some code by using inheritance. You put basic functionality like getters and setters into the parent class and then put the heavy lifting in lower level classes that extend it. This doesn't do as much to cut down on repeating code, but it can compartmentalize things and so each section will have less going on, making it look more organized. But then again you'll need to consult two classes, the parent and child, to get a full picuture of the child's full functionality. Again, it's up to you to see what is best.

If you seem to be reusing parts of code in multiple classes, or creating workarounds to use a class in multiple ways, then it would make some sense to think about inheritance.

But again, it's perfectly possible that a project has no need for using inheritance whatsoever.

Don't be put off with refactoring your code to use inheritance though. Maybe clone the project and then copy/paste things and try and convert your current project into a new one using inheritance. You'll learn a lot from trying it out.

1

u/hugthemachines Jan 03 '16

Perhaps you should use it as you feel the need. First make sure you don't have much logic in main, then try to make the classes small. As a practice, divide a program into small classes etc. Then, later on you will feel the need for interfaces etc that will boost your motivation to learn how to do it.