• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Why use OOP ?

 
Ranch Hand
Posts: 92
Android
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why do we use object oriented when we can do the same thing in our main method .. why creating classes and perform some task in self choice method and then return it to main Method while we can do the same thing in Main method !!
 
author & internet detective
Posts: 41967
911
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Saad,
Putting everything in the main method would make the code long and hard to read. OOP makes the code easier to read/understand and also helps with reuse.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Saad,

In OOP, A big problem is broken into the small one. If we use all in main methods. What will be a use of OOP. We need break into the small one for modularity programming.
 
Saloon Keeper
Posts: 28127
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
People used to put everything in a single code module. In fact, many early programming languages had limited, if any support for doing it any other way.

The results tended to be a big, unmaintainable mess. In fact, the term "spaghetti code" was coined, referring to the tendency of such modules to weave logic all over the place similar to the pasta strands on a plate of spaghetti.

The first major disciplinary attempt to address that problem was the development of subroutines (sometimes known as functions). Subroutines allowed breaking code into modules where the internals of the modules were basically "black boxes". Meaning that you could (theoretically) completely re-design and re-code the insides of those modules and the rest of the program would remain unaffected - in fact, ignorant - of the changes.

That was a step up, and it had the bonus effect of creating re-usable code instead of having to put everything together from scratch each time, but spaghetti code was still a problem. Often there was one big main module and lots of little function modules and the main module was usually still very messy and sometimes so were some of the subroutine modules.

The next disciplinary attempt, coming somewhere around the 1970s was the banishment of the infamous "goto" statement and its replacement with 3 logical building blocks: Linear code, logical selection (if/then or select/case) and loop statements (do-while, repeat-until, for-each and so forth). That got rid of a lot of the logic weaving (spaghetti), but even then modules tended to become large and unwieldy. I once encountered a COBOL program where a single "IF" statement and its sub-clauses ran to 4 pages of 66 program print lines. And in COBOL, a statement terminator was a single ".", which was especially perilous - can you spot the dot?

The idea of creating "building blocks" and giving them self-contained properties and behaviors dates back to about 1960, but until the arrival of the Smalltalk programming language, mostly it was used for graphics management and simulation languages. Smalltalk was perhaps the first general-purpose language that was based on object-oriented programming.

In the early 1980's, Bjarne Stroustrup at AT&T Bell Labs modified a C compiler front-end to support object-oriented programming. He called it "C with Classes", then "C++". AT&T made it part of their licensable software product offerings and I purchased a license and ported it to the Commodore Amiga computer system. This was a case of being in the right place at the right time. The Amiga was the first 32-bit machine* with a totally flat address space, and the AT&T C++ translator wasn't designed to be as kind to hardware as 1960s-era compilers were. Meaning that 16-bit processing was right out and the segmented memory storage model used on the IBM 80286 and earlier Intel systems was an absolute nightmare. I could go into the sordid details, but until Microsoft started running OS's in flat memory spaces, C++ products for the DOS/Intel platform were a problem.

C++ is literally object-oriented in that you could still write "flat" programs in C++ that were essentially the same code as straight C, but you could also define object classes. However by 1990, James Gosling had adapted the concepts to a similar language that was truly object-based - the "Oak" language that eventually became Java.

Coding modules isn't just beneficial to programmers, although now that computers are cheaper than programmers, the more productive you can make programmers, the better. However, the modularity afforded by making things object-based allows the compiler to produce more efficient code by taking advantage of locality of reference. Basically, this amounts to keeping as many resources that are in active use as possible within short reach, since at the raw machine language level, far-away stuff typically requires longer, slower machine instructions to access and more base address registers to find them.

Up until about 1983, most compilers were fairly inefficient. The rule of thumb being that high-level language code would run about 10% less efficient than hand-coded assembly (machine) language. However, about then optimizing compilers started being the rule rather than an extra-cost exception. My first experience with such a compiler was IBM's Pascal/VS compiler which could juggle around internal objects every time it re-compiled, giving, in effect, several days worth of hand-rewriting in a matter of milliseconds. About the same time, we were working with the COBOL compiler for Honeywell's mini-computer line (which I often joked was the only COBOL compiler suited to write OS code in a la C). In both compilers, you had to keep your modules fairly small, since the optimizer allocated only a few address registers per module, and in the case of IBM mainframes, an address register could only access in a range of 8192 bytes of RAM.

So, in short, object-oriented programming (and modular programming in general) are preferred as being more efficient for both people and computers.

There are other approaches, such as Functional Programming, but we'll leave that for another day.

====
*The Commodore Amiga and the Apple Macintosh both used the Motorola MC68000 CPU, but the Amiga OS and its official compilers used it in 32-bit mode, whereas the Macintosh used it as a 16-bit processor. So even though the Mac hardware was capable, the Apple OS wasn't set up for it.
 
Marshal
Posts: 28296
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's this application that I wrote; I just looked through it and counted them, and I found it has 744 classes in it. That's not 744 lines of code, that's 744 classes.

I suppose that it might theoretically be possible to write a single class with a single main() method which does the same thing, but I for one am not going to spend the time to see if that's true. And if I did, I would never ever be able to change it again.

If you're going to school, or if you're studying for one of those certification exams, I can see how you might get the impression that almost every program is a simple one consisting of less than 100 lines of code. But in the real world, that is very far from being the case.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
wow mate 744 classes ..
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And that 744 doesn't include all the classes (I presume) that are used by the project, not just those in the standard Java packages either.

Out of curiosity I checked the one I'm currently on...it's over 5000, excluding test classes.
 
Tim Holloway
Saloon Keeper
Posts: 28127
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And it's not unusual. I used to work regularly on a webapp that has 495 java class source files. AFTER migrating a lot of the web services out to a second webapp.

And that's not counting the persistence service libraries, which go into the app, but are kept as separate JARs. 199 ORM classes and another 63 for business logic.

Someday the client may pay their bills and I'll go back to working on it again.
 
Sheriff
Posts: 17665
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Alan Kay, recipient of the 2003 ACM Turing Award and one of the inventors of SmallTalk is often credited with coining the term "object-oriented programming".   In this document, he gives some insight as to the motivations behind OOP.
 
Paul Clapham
Marshal
Posts: 28296
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dave Tolls wrote:And that 744 doesn't include all the classes (I presume) that are used by the project, not just those in the standard Java packages either.



No, those are just the classes that I wrote. It's a Swing app so there's no doubt a gazillion classes, public and protected, which I'm using, and there's a JDBC driver with a lot of classes in it along with a connection pool with more classes, and some Date and Time selection classes which I got from elsewhere (following on from a conversation on the Ranch actually), and then there's the Apache POI project which is used for extracting data from spreadsheets -- several hundred classes I expect -- and there's more.
 
Bartender
Posts: 1971
17
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Saad Zahoor wrote:Why do we use object oriented when we can do the same thing in our main method .. why creating classes and perform some task in self choice method and then return it to main Method while we can do the same thing in Main method !!



Simply stated, probably the biggest bang for your buck that OOP gives you is "abstraction" (read: simplification or higher-level objects like "Customer" instead of (without OOP) some code here and some code and data over there that somehow you're "treating" as a customer.

-----------------------
Also, OOP gives you:
-----------------------
Encapsulation - code and data in same object
Inheritance - so you can extend your code without duplicating it
Polymorphism - so you can program to interface not to implementation.

---

Having said that, I still write utilities and other really short stuff using just a main method.

Plus, if you do things like microservices, those use a main method, too (but Spring's SpringBoot is quite complex).

HOPE THIS HELPS.

- mike
 
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote an app once(a paint APP) . it had almost 30 classes. some were anonymous. I jarred it from the command line. that was hard
 
Tim Holloway
Saloon Keeper
Posts: 28127
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike London wrote:
Plus, if you do things like microservices, those use a main method, too (but Spring's SpringBoot is quite complex).
- mike



Hmmm. Maybe I have a different definition of microservices, then.

In any event, one of the popular uses of Spring Boot is as a run-and-go Tomcat or jetty container, and webapps do not have a main method. The main method for a webapp server is the webapp server itself. When it isn't simply instantiated and run by some other main method (such as Spring Boot's).
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are several reasons.

(1) Don't repeat yourself (DRY) principle. I've wrote a code that took several sql tables and processed it. I had a class for each table. It turned out that records must be formatted in a certain way. I had to go back to each class and change it. They I needed to trim spaces. I went to each class and added a trimming method. Needless to say I missed some classes. Hence, some entries were formatted correctly, while other entries were not. Worse so, I was repeating the same operation over and over again. This is something computers are good at, but humans aren't. OOP enables automation.

(2) Often one needs and abstract feature that can be implemented in different ways. Cashier say "pay $10". This is an abstract `pay` method. There are concrete implementations "pay with cash", "pay with cc", "pay with check". OOP uses inheritance to model this behavior. Otherwise salesperson would have to say:
to proceed fulfill one of the following: pay with "cash, cc or check". This violates DRY principle. If a new payment method is added cashier has to keep track of it. Inheritance allows to outsource it to an abstract "pay" method and any new monetary instrument now has to implement "pay" method in order to join monetary market. Practical CS case is ArrayList vs LinkedList. Both can add, store, return and remove an ordered set of entries (this is what most users need - an abstract list). But for some users iteration performance is critical (use ArrayList), while for others insert/delete is essential (use LinkedList).
Sure, you can write a method that separately accepts ArrayList (from iterating users) and LinkedList (from inserting users), but you are repeating yourself.

(3) Code is written once, read many times. Messy code rots. Eventually it becomes prohibitively expensive to support the project and it dies. Please read "Clean Code" by Robert C. Martin. This book is a great reading. Most Java books make me fall asleep. Not this one.

(4) It is a pain to debug large messy methods and classes. Many short methods help to quickly localize a bug to a single small method and fix it. It is much harder to spot a bug in a method if it does a zillion of different unrelated things.

----
Mathematically speaking, any OOP code can be translated to (or written in) brainfuck. We don't have to use OOP. However, adding features and fixing bugs is way easier if you follow OOP and clean code practices.

For simple tasks I use write-only Perl code with RegEx expressions. I write it fast, but it is not meant to be reused or modified. For larger projects I go for Java, follow OOP principles and try to keep methods and classes as small as possible.
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:

Mike London wrote:
Plus, if you do things like microservices, those use a main method, too (but Spring's SpringBoot is quite complex).
- mike



Hmmm. Maybe I have a different definition of microservices, then.

In any event, one of the popular uses of Spring Boot is as a run-and-go Tomcat or jetty container, and webapps do not have a main method. The main method for a webapp server is the webapp server itself. When it isn't simply instantiated and run by some other main method (such as Spring Boot's).



Microservices as I use them all have a main method. That's what's so cool....you can run the "fat jar" directly as it has all the dependencies internally.

Like the code below taken from the Spring site:



---

FWIW, I really like the Java Spark framework better for smaller microservices. It's quick, easy, and super nice.

- mike
 
Do you pee on your compost? Does this tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic