I want to I can improve myself, and then I can design a class as a masterpiece. But I don't how to do that, and what rules I should follow? any suggestions?
Thanks in advance !
I want to I can improve myself, and then I can design a class as a masterpiece. But I don't how to do that, and what rules I should follow? any suggestions?
Thanks in advance !
The only real way to get to that is by practice and more practice (i.e programming). In time you will feel what is right and what is not. Peer code review by more experienced developers can greatly help in that. Sorry for not knowing any good short-cuts.
Yup, your going to need to provide significant more detail in order for anyone to answer this properly.
Ignoring the fact that there are entire books written on this subject, here's a quick incomplete list.
A well designed class should:
- Have one purpose, not just a mashup of several random functions
- Clean up any resources it uses, not rely on other classes to do it
- Fully unit tested
- Have proper exception handling
- Have ToString and Equals overloads (that just might be me though)
- Have descriptive function names
I'll make this a community wiki so others can add as they see fit.
Especially in OO (but it can be applied to writing any function), you want to be the class. That is, you want to roleplay:
Define the class's (or the function's) responsibilities. A good function does only one thing, and does it well; a good class is responsible for only one thing (it's internal state, which includes its relations to other objects):
OK, I'm class Foo. I do this, this is my responsibility. But I don't do that, or that, or that.
Define the state it has (its internal member variables):
OK, this is what I carry around, this is what I'm made of, this is all that I know. Everything I do or can do is determined by what I carry around and the (usually much smaller) amount of stuff that gets passed to me.
Define its collaborations. Very very often, the majority of a class's work is done by things it has or uses; often a class may just coordinate (order, apply, mediate between) the work its collaborators do. Most GOF Patterns are like this.
OK this is the kind of stuff I'll get passed, and these other objects are what I'll use to do my work.
Define what role the class itself plays, which gives insight into what interfaces it implements (its public interface). (Its private inheritance, in C++ D : private B
or in Java extends
, is more of a collaborator, though in Java that gets smeared a bit):
OK, I'm really a Foo, to public clients, even though internally I'm a could re-use a lot of what a Baz does.
Roleplay. Be the class, limit your vision to only that which the class sees (its members, superclass(es), and arguments passed to its functions). And then ask yourself, "what would/should/can I do when I'm asked to do whatever? What do I need, what do I have, what other classes do I need to help me to do it?