Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Desigining Proper Classes

Tags:

oop

I've read all the books about why to create a class and things like "look for the nouns in your requirements" but it doesn't seem to be enough. My classes seem to me to be messy. I would like to know if there are some sort of metrics or something that I can compare my classes to and see if there well designed. If not, who is the most respected OO guru where I can get the proper class design tips?

like image 834
jumbojs Avatar asked Feb 20 '09 05:02

jumbojs


2 Answers

Creating classes that start clean and then get messy is a core part of OO, that's when you refactor. Many devs try to jump to the perfect class design from the get go, in my experience that's just not possible, instead you stumble around, solving the problem and then refactor. You can harvest, base classes and interfaces as the design emerges.

like image 159
MrTelly Avatar answered Oct 05 '22 23:10

MrTelly


if you're familiar with database design, specifically the concept of normalization, then the answer is easy: a data-centric class should represent an entity in third normal form

if that is not helpful, try this instead:

  • a class is a collection of data elements and the methods that operate on them
  • a class should have a singular responsibility, i.e. it should represent one thing in your model; if it represents more than one thing then it should be more than one class.
  • all of the data elements in a class should be logically associated/related to each other; if they aren't, split it into two or more classes
  • all of the methods in a class should operate only on their input parameters and the class's data elements - see the Law of Demeter

that's about as far as i can go with general abstract advice (without writing a long essay); you might post one of your classes for critique if you need specific advice

like image 36
Steven A. Lowe Avatar answered Oct 05 '22 23:10

Steven A. Lowe