Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to organize object oriented code?

I haven't coded in java for a long time, and after coding in C, I'm having issued organizing my code for OOP. More specifically I'm not sure when to create a new method, and when to create a new class, and when to just lump everything together.

Are there some general rules or guidelines on how it should be done?

like image 335
Adam Avatar asked Nov 27 '22 01:11

Adam


2 Answers

Take a look at the SOLID principles.

EDIT (some more pointers):

You need a SOLID GRASP of some design principles.

To start small, take a look at these first:

  • Single Resposibility Principle (pdf) (the S in SOLID)
  • Neil Ford gives some excellent advice in this presentation, including:
    • Single Level of Abstraction Principle
    • Composed Method

When writing code, high maintainability should be your ultimate goal, and it's all about assigning responsibilities and separation of concerns.

like image 152
Jordão Avatar answered Dec 10 '22 14:12

Jordão


First of all, never just lump everything together. Try to identify the objects first. Build a class for each object your program will work with. If you're building an application for truck drivers, you will need a class for the driver, the truck, the load he's hauling, there's really no limit to how far you can break these bigger objects down. As for the methods, a method handles an action for the object. Truck.Start() would start the truck. Drive() would start it driving, etc... Maybe the Drive method takes a Route object for an argument which contains the roads to drive on. In short, create a method when an object needs to do something and create a class when you want to deal with another type of object.

like image 30
kirk.burleson Avatar answered Dec 10 '22 13:12

kirk.burleson