开发者

What is the best way to organize object oriented code?

开发者 https://www.devze.com 2023-01-04 02:10 出处:网络
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

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?


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.


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.


Well designed objects are SOLID.

This is a difficult question, one that everyone who worries about design has to figure out. I think it's the hardest part of using objects, light years beyond mere syntax.


Is is something that you think of as a thing, entity or actor in your system. Well then it's an object so make a class to represent it. There's no need to make it more difficult than it is.

0

精彩评论

暂无评论...
验证码 换一张
取 消