OOP: When & Whether to Construct a New Class?

  • Thread starter Thread starter Red_CCF
  • Start date Start date
  • Tags Tags
    Oop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 2K views
Red_CCF
Messages
530
Reaction score
0
Hi

I have a question, how does one know when and/or whether to construct a new class or not? What are some indications that one should create a class to bunch all the functions/variables together?

Thanks.
 
Physics news on Phys.org
I have no formal training in these things, but I do have about 10 years of experience in programming in which I did some OOP, so my point of view is a very practical one.

Most of the time, to me, classes logically suggest themselves. If you are writing a board game, you will start with a Game class, that will most likely contain a Board class which manages all the Fields, and the Pieces. If you are writing a simulation for an experiment, you would think about some Objects in Space, and probably some Manager class which takes care of the interactions and listing of all the objects and perhaps a set of Output classes which know how to draw the objects (e.g. on screen, on a printer, to a text file).

If you think about your program as a sort of machine in which every small part has its own task, and only the relevant data is handed from part to part to be processed in some way which other parts don't need to know about, classes often present themselves. If you find yourself writing some related functions (like SaveToFile, LoadFromFile, PrintToScreen, PrintToPrinter) with internal / local variables (filename, file_exists, file_is_open) a class (FileHandler) might be a good idea.

Also, I try to keep my classes small. A declaration should fit on one computer screen, and you should not need to copy/paste/modify code.
 
If you find yourself passing a long and annoying list of parameters to a subroutine, then you really ought to be using an object instead. Most of those parameters can just live inside the object.