r/javahelp • u/kamalist • 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.
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
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
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
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
3
Jan 02 '16 edited Jan 03 '16
Quick crash course:
object: A piece of your application. This has a state and can do things.Objectsare your lego bricks.class: A mold that you can use to make anobject.method: A thing you can make anobjectdofield: Part of yourobject's stateabstract: Part of aclass, that can be mixed and matched with other classes.interface: A set of requirements for class, to which you can claim yourclassadheres.static: A tool that comes with theclass.final: Something that's inherent to anobjector itsclass, and is not ever expected to change.private: accessible from the currentclassor objects made from itprotected: accessible from the currentclass, any molds that derive from it, or any objects made from either.public: accessible from anywhereannotation: metadata about aclass, afield, amethod, 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
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.
8
u/Joha_Mraadu Employed Java Developer Jan 02 '16
Uhm, I would first start with a complete introduction to OOP. This book:
http://www.amazon.co.uk/Thinking-Java-Bruce-Eckel/dp/0131872486/ref=sr_1_1?ie=UTF8&qid=1451750882&sr=8-1&keywords=thinking+in+java
helped me a lot. Once you go through with it, you should have a pretty solid understanding of OOP and Java.
Also I cannot stress enough how important this thing is, many people seem to neglect it nowadays:
http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
I recommend following books once you understand Java more :):
Effective Java by Joshua Bloch:
http://www.amazon.co.uk/Effective-Java-Second-Joshua-Bloch/dp/0321356683/ref=sr_1_1?ie=UTF8&qid=1451750978&sr=8-1&keywords=effective+java
Head First - Design Patterns by Eric Freeman:
http://www.amazon.co.uk/Head-First-Design-Patterns-Freeman/dp/0596007124/ref=pd_sim_14_2?ie=UTF8&dpID=61APhXCksuL&dpSrc=sims&preST=_AC_UL160_SR138%2C160_&refRID=1J4FWDFZDD8XERKQEY2Q
Clean Code by Robert C. Martin:
http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=pd_sim_14_3?ie=UTF8&dpID=51oXyW8WQwL&dpSrc=sims&preST=_AC_UL160_SR124%2C160_&refRID=1J4FWDFZDD8XERKQEY2Q