About Object Oriented Design. Best practices. Splitting into classes?
I am working on a slightly c开发者_如何学Goomplicated puzzle for an interview. I do not know much about best practices in design.
I want to write a single big class which solves the problem at hand first. Then I want to split it into as many sub classes as I want.
Is this considered a good way in the industry to build a good design?
No. It's not.
Designing your objects should be one of your first priorities, not your last.
A good Object Oriented developer will look at a problem, decide which objects need created, set off about creating those objects, and then weaving them together to solve the larger problem.
If you try to make one giant class to handle all the work by itself, you're going to wind up with code that is very tightly coupled which can't be broken into classes...but could've been if you designed the code properly up front.
I'll try to answer with a possible approach you could take. First phrase your problem into some sentences that you want to solve. From these sentences nouns are your classes and variables. Verbs are your methods. From this point you can start writing your first version of code
When writing code for production, my experience is that actual practice is somewhere in the middle. When designing the system, come up with the classes you think you'll need (see Skyzer's answer for a good way to think about breaking things up). As you actual implement your solution, you'll probably get to the point where some objects are getting too big; doing too much. At that point, you can take a second look at the design and see if you can break the object up into several, smaller objects. Each object should be in charge of one "thing", but the definition of what is a "thing" can change over time as a given "thing" gets more complex.
Analogous to this is the writing of methods/commands. Each command should do one thing, and do it well. For me, this means that it's easy to write the tests for that command, because the tests can very clearly define what the command does. When the amount of things the command does grows too large (a large number of logic branches like if's causing more and more tests are a good indicator of this), break the command up into multiple, smaller ones that can each be tested.
精彩评论