Adam Davis
Adam Davis

Reputation: 93605

What should be on a checklist that would help someone develop good OO software?

I have used OO programming languages and techniques years ago (primarily on C++) but in the intervening time haven't done much with OO.

I'm starting to make a small utility in C#. I could simply program it all without using good OO practice, but it would be a good refresher for me to apply OO techniques.

Like database normalization levels, I'm looking for a checklist that will remind me of the various rules of thumb for a 'good' object oriented program - a concise yes/no list that I can read through occasionally during design and implementation to prevent me from thinking and working procedurally. Would be even more useful if it contained the proper OO terms and concepts so that any check item is easily searchable for further information.

What should be on a checklist that would help someone develop good OO software?

Conversely, what 'tests' could be applied that would show software is not OO?

Upvotes: 25

Views: 3531

Answers (10)

RCIX
RCIX

Reputation: 39457

Gathered from various books, famous C# programmers, and general advice (not much if any of this is mine; It is in the sense that these are various questions i ask myself during development, but that's it):

  • Structs or Classes? Is the item you're creating a value of it's own, make it a struct. If it's an "object" with attributes and sub-values, methods, and possibly state then make it an object.
  • Sealed Classes: If you're going to be creating a class and you don't explicitly need to be able to inherit from it make it sealed. (I do it for the supposed performance gain)
  • Don't Repeat Yourself: if you find yourself copy-past(a/e)ing code around then you should probably (but not always) rethink your design to minimize code duplication.
  • If you don't need to provide a base implementation for a given abstract class turn it into an interface.
  • The specialization principle: Each object you have should only do one thing. This helps avoid the "God-object".
  • Use properties for public access: This has been debated over and over again, but it's really the best thing to do. Properties allow you to do things you normally can't with fields, and it also allows you more control over how the object is gotten and set.
  • Singletons: another controversial topic, and here's the idea: only use them when you Absolutely Need To. Most of the time a bunch of static methods can serve the purpose of a singleton. (Though if you absolutely need a singleton pattern use Jon Skeet's excellent one)
  • Loose coupling: Make sure that your classes depend on each other as little as possible; make sure that it's easy for your library users to swap out parts of your library with others (or custom built portions). This includes using interfaces where necessary, Encapsulation (others have mentioned it), and most of the rest of the principles in this answer.
  • Design with simplicity in mind: Unlike cake frosting, it's easier to design something simple now and add later than it is to design complex now and remove later.

I might chuck some or all of this out the door if i'm:

  • Writing a personal project
  • really in a hurry to get something done (but i'll come back to it later.... sometime..... ;) )

These principles help guide my everyday coding and have improved my coding quality vastly in some areas! hope that helps!

Upvotes: 10

Sean Copenhaver
Sean Copenhaver

Reputation: 10685

Sounds like you want some basic yes/no questions to ask yourself along your way. Everyone has given some great "do this" and "think like that" lists, so here is my crack at some simple yes/no's.

Can I answer yes to all of these?

  • Do my classes represent the nouns I am concerned with?
  • Do my classes provide methods for actions/verbs that it can perform?

Can I answer no to all of these?

  • Do I have global state data that could either be put into a singleton or stored in class implementations that work with it?
  • Can I remove any public methods on a class and add them to an interface or make them private/protected to better encapsulate the behavior?
  • Should I use an interface to separate a behavior away from other interfaces or the implementing class?
  • Do I have code that is repeated between related classes that I can move into a base class for better code reuse and abstraction?
  • Am I testing for the type of something to decide what action to do? If so can this behavior be included on the base type or interface that the code in question is using to allow more effect use of the abstraction or should the code in question be refactored to use a better base class or interface?
  • Am I repeatedly checking some context data to decided what type to instantiate? If so can this be abstracted out into a factory design pattern for better abstraction of logic and code reuse?
  • Is a class very large with multiple focuses of functionality? If so can I divide it up into multiple classes, each with their own single purpose?
  • Do I have unrelated classes inheriting from the same base class? If so can I divide the base class into better abstractions or can I use composition to gain access to functionality?
  • Has my inheritance hierarchy become fearfully deep? If so can I flatten it or separate things via interfaces or splitting functionality?
  • I have worried way too much about my inheritance hierarchy?
  • When I explain the design to a rubber ducky do I feel stupid about the design or stupid about talking to a duck?

Just some quick ones off the top of my head. I hope it helps, OOP can get pretty crazy. I didn't include any yes/no's for more advanced stuff that's usually a concern with larger apps, like dependency injection or if you should split something out into different service/logic layers/assemblies....of course I hope you at least separate your UI from your logic.

Upvotes: 11

eglasius
eglasius

Reputation: 36035

  • SOLID
  • DRY
  • TDD
  • Composition over inheritance

Upvotes: 5

RMorrisey
RMorrisey

Reputation: 7739

  • Have I clearly defined the requirements? Formal requirements documentation may not be necessary, but you should have a clear vision before you begin coding. Mind-mapping tools and prototypes or design sketches may be good alternatives if you don't need formal documentation. Work with end-users and stakeholders as early as possible in the software process, to make sure you are implementing what they need.

  • Am I reinventing the wheel? If you are coding to solve a common problem, look for a robust library that already solves this problem. If you think you might already have solved the problem elsewhere in your code (or a co-worker might have), look first for an existing solution.

  • Does my object have a clear, single purpose? Following the principle of Encapsulation, an object should have behavior together with the data that it operates on. An object should only have one major responsibility.

  • Can I code to an interface? Design By Contract is a great way to enable unit testing, document detailed, class-level requirements, and encourage code reuse.

  • Can I put my code under test? Test-Driven Development (TDD) is not always easy; but unit tests are invaluable for refactoring, and verifying regression behavior after making changes. Goes hand-in-hand with Design By Contract.

  • Am I overdesigning? Don't try to code a reusable component. Don't try to anticipate future requirements. These things may seem counterintuitive, but they lead to better design. The first time you code something, just implement it as straightforwardly as possible, and make it work. The second time you use the same logic, copy and paste. Once you have two working sections of code with common logic, you can easily refactor without trying to anticipate future requirements.

  • Am I introducing redudant code? Don't Repeat Yourself (DRY) is the biggest driving principal of refactoring. Use copy-and-paste only as a first step to refactoring. Don't code the same thing in different places, it's a maintenance nightmare.

  • Is this a common design pattern, anti-pattern, or code smell? Be familiar with common solutions to OO design problems, and look for them as you code - but don't try to force a problem to fit a certain pattern. Watch out for code that falls into a common "bad practice" pattern.

  • Is my code too tightly coupled? Loose Coupling is a principle that tries to reduce the inter-dependencies between two or more classes. Some dependencies are necessary; but the more you are dependent on another class, the more you have to fix when that class changes. Don't let code in one class depend on the implementation details of another class - use an object only according to its contract.

  • Am I exposing too much information? Practice information hiding. If a method or field doesn't need to be public, make it private. Expose only the minimum API necessary for an object to fulfill its contract. Don't make implementation details accessible to client objects.

  • Am I coding defensively? Check for error conditions, and Fail Fast. Don't be afraid to use exceptions, and let them propagate. In the event your program reaches an unexpected state, it's much, much better to abort an operation, log a stack trace for you to work with, and avoid unpredictable behavior in your downstream code. Follow best practices for cleaning up resources, such as the using() {} statement.

  • Will I be able to read this code in six months? Good code is readable with minimal documentation. Put comments where necessary; but also write code that's intuitive, and use meaningful class, method, and variable names. Practice good coding style; if you're working on a team project, each member of the team should write code that looks the same.

  • Does it still work? Test early, test often. After introducing new functionality, go back and touch any existing behavior that might have been affected. Get other team members to peer review and test your code. Rerun unit tests after making changes, and keep them up to date.

Upvotes: 7

Danny Varod
Danny Varod

Reputation: 18098

Some of the rules are language agnostic, some of the rules differ from language to language.

Here are a few rules and comments that contradict some other the previously posted rules:

  • OO has 4 principles: Abstraction, Encapsulation, Polymorphism and Inheritence.
    Read about them and keep them in mind.

  • Modelling - Your classes are supposed to model entities in the problem domain:
    Divide the problem to sub-domains (packages/namespaces/assemblies)
    then divide the entities in each sub-domain to classes.
    Classes should contain methods that model what objects of that type do.

  • Use UML, think about the requirements, use-cases, then class diagrams, them sequences. (applicable mainly for high-level design - main classes and processes.)

  • Design Patterns - good concept for any language, implementation differs between languages.

  • Struct vs. class - in C# this is a matter of passing data by value or by reference.

  • Interface vs. base-class, is a base-class, does an interface.

  • TDD - this is not OO, in fact, it can cause a lack of design and lead to a lot of rewriting. (Scrum for instance recommends against it, for XP it is a must).

  • C#'s Reflection in some ways overrides OO (for example reflection based serialization), but it necessary for advanced frameworks.

  • Make sure classes do not "know of" other classes unless they have to, dividing to multiple assemblies and being scarce with references helps.

  • AOP (Aspect Oriented Programming) enhances OOP, (see PostSharp for instance) in a way that is so revolutionary that you should at least look it up and watch their clip.

  • For C#, read MS guidelines (look up guidelines in VS's MSDN help's index), they have a lot of useful guidelines and conventions there

  • Recommended books:
    Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
    C# 3.0 in a Nutshell

Upvotes: 1

Dafydd Rees
Dafydd Rees

Reputation: 6983

  • Objects do things. (Most important point in the whole of OOP!) Don't think about them as "data holders" - send them a message to do something. What verbs should my class have? The "Responsibility-Driven Design" school of thinking is brilliant for this. (See Object Design: Roles, Responsibilities, and Collaborations, Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley 2003, ISBN 0201379430.)
  • For each thing the system must do, come up with a bunch of concrete scenarios describing how the objects talk to each other to get the job done. This means thinking in terms of interaction diagrams and acting out the method calls. - Don't start with a class diagram - that's SQL-thinking not OO-thinking.
  • Learn Test-Driven Development. Nobody gets their object model right up front but if you do TDD you're putting in the groundwork to make sure your object model does what it needs to and making it safe to refactor when things change later.
  • Only build for the requirements you have now - don't obsess about "re-use" or stuff that will be "useful later". If you only build what you need right now, you're keeping the design space of things you could do later much more open.
  • Forget about inheritance when you're modelling objects. It's just one way of implementing common code. When you're modelling objects just pretend you're looking at each object through an interface that describes what it can be asked to do.
  • If a method takes loads of parameters or if you need to repeatedly call a bunch of objects to get lots of data, the method might be in the wrong class. The best place for a method is right next to most of the fields it uses in the same class (or superclass ...)
  • Read a Design Patterns book for your language. If it's C#, try "Design Patterns in C#" by Steve Metsker. This will teach you a series of tricks you can use to divide work up between objects.
  • Don't test an object to see what type it is and then take action based on that type - that's a code smell that the object should probably be doing the work. It's a hint that you should call the object and ask it to do the work. (If only some kinds of objects do the work, you can simply have "do nothing" implementations in some objects... That's legitimate OOP.)
  • Putting the methods and data in the right classes makes OO code run faster (and gives virtual machines a chance to optimise better) - it's not just aesthetic or theoretical. The Sharble and Cohen study points this out - see http://portal.acm.org/citation.cfm?doid=159420.155839 (See the graph of metrics on "number of instructions executed per scenario")

Upvotes: 37

CRice
CRice

Reputation: 12567

UML - Unified Modeling Language, for object modeling and defining the structure of and relationships between classes

http://en.wikipedia.org/wiki/Unified_Modeling_Language

Then of course the programming techniques for OO (most already mentioned)

  • Information Hiding
  • Abstraction
  • Interfaces
  • Encapsulation
  • Inheritance / Polymorphism

Upvotes: 1

Rob Scott
Rob Scott

Reputation: 449

One of the best sources would be Martin Fowler's "Refactoring" book which contains a list (and supporting detail) of object oriented code smells that you might want to consider refactoring.

I would also recommend the checklists in Robert Martin's "Clean Code".

Upvotes: 6

Michael Borgwardt
Michael Borgwardt

Reputation: 346377

  • Data belongs with the code that operates on it (i.e. into the same class). This improves maintainability because many fields and methods can be private (encapsulation) and are thus to some degree removed from consideration when looking at the interaction between components.
  • Use polymorphism instead of conditions - whenever you have to do different things based on what class an object is, try to put that behaviour into a method that different classes implement differently so that all you have to do is call that method
  • Use inheritance sparingly, prefer composition - Inheritance is a distinctive feature of OO programming and often seen as the "essence" of OOP. It is in fact gravely overused and should be classified as the least important feature

Upvotes: 7

Alex
Alex

Reputation: 36596

Make sure you read up and understand the following

  • Encapsulation
    • (Making sure you only expose the minimal state and functionality to get the job done)
  • Polymorphism
    • (Ability for derived objects to behave like their parents)
  • The difference between and interface and an abstract class
    • (An abstract class allows functionality and state to be shared with it's descendants, an interface is only the promise that the functionality will be implemented)

Upvotes: 3

Related Questions