java 组织面向对象代码的最佳方式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3066731/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to organize object oriented code?
提问by Adam
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.
我已经很久没有用 Java 编码了,在用 C 编码之后,我已经发布了组织我的面向对象编程的代码。更具体地说,我不确定何时创建新方法,何时创建新类,以及何时将所有内容混为一谈。
Are there some general rules or guidelines on how it should be done?
是否有一些关于如何完成的一般规则或指导方针?
回答by Jord?o
Take a look at the SOLID principles.
看看SOLID 原则。
EDIT(some more pointers):
编辑(更多的指针):
You need a SOLIDGRASPof 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:
 
- 单一职责原则 (pdf)(SOLID 中的 S)
 - Neil Ford 在本次演讲中给出了一些极好的建议,包括:
 
When writing code, high maintainabilityshould be your ultimate goal, and it's all about assigning responsibilities and separation of concerns.
在编写代码时,高可维护性应该是您的最终目标,这完全是关于分配责任和关注点分离。
回答by duffymo
回答by kirk.burleson
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.
首先,永远不要把所有东西都放在一起。首先尝试识别对象。为您的程序将使用的每个对象构建一个类。如果您正在为卡车司机构建应用程序,您将需要为司机、卡车、他所拖运的负载创建一个类,您可以将这些更大的物体分解多远实际上是没有限制的。至于方法,一个方法处理对象的一个动作。Truck.Start() 将启动卡车。Drive() 会启动它,等等......也许 Drive 方法需要一个 Route 对象作为一个参数,其中包含要行驶的道路。简而言之,当一个对象需要做某事时创建一个方法,当您想要处理另一种类型的对象时创建一个类。
回答by Khorkrak
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.
是您认为是系统中的事物、实体或参与者的东西。那么它是一个对象,所以创建一个类来表示它。没有必要让它变得比现在更困难。

