Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

November 22, 2010

97 Things Every Programmer Should Know

Originally published 8 Sep 2009

The web site for the 3rd book in the 97 Things series recently went public.  This one is targeted at programmers.  There are 88 contributions that have been edited (mine is #57) and the exact 97 entries that will go into the final book have yet to be identified.

Some of our industry's thought leaders have already made contributions.  If you'd like to contribute and possibly see your name listed alongside them, see How to Become a Contributor.

The Difference Between a Property, Field, Attribute

Originally published 3 Aug 2007

I’ve been asked a similar question at least three times this year.  It goes something like, “What’s the difference between a field and a property?”  Or, “Is there a difference between an attribute and a property?”  Given that many inexperienced developers automatically generate getters and setters for all their fields, I can understand the confusion.

I always give them the example of a circle.  Here’s some Groovy code:

class Circle {
   def radius
   
   def getDiameter() {
      2 * radius
   }
   
   getArea() {
      Math.PI * Math.pow(radius, 2)
   }
   
   def getCircumference() {
      2 * radius * Math.PI
   }
}

radius is a field, also known as an instance variable, also known as a member variable in C++.  It’s an implementation detail of the Circle, i.e., it’s a private variable that gets stored as part of the Circle object.

Properties are more public aspects of an object.  In Java, following JavaBeans conventions for getters and setters allows you to expose properties.  Those properties don’t have to be backed up by fields, but in many cases are.

Coming back to the Groovy Circle, what are its properties?  We’ll you get radius for free as a read-write property.  But because we’ve got some getters that compute other values based on radius, we also have diameter, area, and circumference properties.  These happen to be read-only properties since we didn’t provide setters, but we could have (which would update the radius field accordingly).  You can dump all of a Circle object’s properties in Groovy like this:


println myCircle.properties

The point is Circle could be implemented in different ways: by using a diameter field instead of radius, for instance, but it would have the same properties.

Now, let’s talk about attributes.  I typically think of UML when I hear attributes.  Here’s UML for Circle:



Notice that I’ve distinguished the derived diameter, area, and circumference attributes with a “/”.  This is standard UML.  radius is a regular, non-derived attribute.  We can distinguish fields from other computed properties like this.  However, because we’re modeling, and thinking in a higher level of abstraction, I like to think of attributes as more synonymous with properties.  I’d rather not make the assumption that every attribute is implemented with a field.

A similar discussion of these terms can be found here.

How to Refactor Many Arguments

Originally published 25 May 2007

The following conversation is based on a true story.  The roles are taken from Robert Martin’s Craftsman series.

Apprentice:  Hey, can I ask you something?
Journeyman:  Sure.
Apprentice:  I was looking at a big constructor on one of our domain objects and I saw some groupings and was wondering whether it would be good to create objects for those groupings.  Is there some kind of pattern for that?
Journeyman:  Well first, how many parameters are there?
Apprentice:  72.
Journeyman:  72!?  Wow.  Talk about a code smell .  PMD's ExcessiveParameterList rule will flip out on this one.  I guess the author mapped those parameters straight from the out-of-our-control XML schema, whose document instances get unmarshalled in order to create the object.  We don’t have to follow suit and create such a flat domain model that matches the schema.
Apprentice:  What do you mean?
Journeyman:  Well, what I really mean is that I'd much prefer distributing the logic among some richer objects.  That is, create more little objects with little methods that do a little of the work.  Not one big object that does it all.  There would be an impedance mismatch between XML and the domain model, but that’s typical because of the technology differences.  I suppose the only benefit of the big constructor approach is the simpler mapping... maybe, but the negatives are much too great.
Apprentice:  What are the negatives?
Journeyman:  Well, for one, trying to list all 72 parameters in the correct order would be a pain.  And trying to understand the object as a whole with all those fields would be difficult.  Here [grabbing his Refactoring book].  You were initially asking about the “Introduce Parameter Object” refactoring.  Read that refactoring.  It can probably give you better details.
Apprentice:  Martin Fowler.  Does he know what he’s talking about?
Journeyman:  Oh yeah.  He’s one of the Masters.  Let’s take a look at the class.  [Brings up the class in the IDE]

public ImportantDomainObject(
   ...
   int x, int y,
   ...
   double min, double max,
   ...)
Well, I can see a few data clumps already.  You see the x and y?
Apprentice:  Yeah.
Journeyman:  That’s probably a Point.  Also, that min and max, that looks like a Range.  What I would do is search for data clumps like these and create objects for them.  Then, see where they’re used in ImportantDomainObject and start moving behavior into the new objects.  Distribute the logic.  We can create a richer domain model this way.  You’ll probably find clumps of these clumps and can follow the same process.
Apprentice:  Okay.  This sounds great.  Thanks.  I’m on it.
Journeyman:  Thank you for recognizing this and taking the initiative to improve the code base.

Collection Utility Methods on the Object

Originally published 16 Apr 2006

I’ve been experimenting lately with a technique that I’m still unsure about. It has a little smell to it, but it has some benefits. The technique is to add static collection-related utility methods on an object. That is, I’ll add a static method that takes a collection of that object on the object itself.

Take the classic Shape example:

   public class Shape {
      // here’s a typical instance method
      public void draw();

      // here's what I’m talking about.
      public static void draw(Collection shapes) {
         for (Iterator it = shapes.iterator(); it.hasNext; ) {
            Shape shape = (Shape) it.next();
            shape.draw();
         }
      }
   }

Now, I haven’t done this kind of thing much; maybe once or twice. The first time I did it was because I noticed some duplication. The exact looping code was shared by multiple clients. I wanted to remove the duplication, but I didn’t know where to put it, so I stuck it on the object itself. The clients became (in the context of this example):

   someShapeClientMethod() {
      Shape.draw(myShapes);
      ...
   }

I think this actually improves clarity (although I could have accomplished the same thing by creating a helper draw() method in the client). This also has the benefit of grouping the iteration logic close to its source, e.g.,Shape here.

The real world example where I first used this was a query.  I had a collection of objects and I wanted to find a specific one. Say, I had a collection of Shapes and I wanted to know who was the biggest:

public static Shape getBiggest(Collection shapes);
 
I think this technique is most applicable under the following circumstances:
  1. For good reason, multiple clients share the code and you want to remove the duplication.
  2. The number of such utility methods is very small. Otherwise, it would be better to group the methods in another, separate utility class (e.g., Shapes or ShapeUtils).
What bothers me most is that I can’t recall seeing this technique used anywhere. That could mean that there’s something really bad about it. One problem is that it clutters the object with additional methods. That’s why I think it should be used judiciously. Also, from a purist view, do these methods really belong on the object?

What do you think?

A Logical Ordering of Import Statements

Originally published 3 Mar 2006

Do you care about the order of your Java import statements?  Well, maybe not, but I do.  The reason is because I like to do a visual check of my dependencies.  According to the Acyclic Dependencies Principle, there should be no cycles in packages.  Robert Martin wrote here, "Remember that the prime motivation for using Object Oriented Design is to manage module dependencies."  One way I check my dependencies is by scanning the import statements of a class or interface to make sure it depends on other, appropriate classes and interfaces.

The rule I use is that you can go up a package hierarchy and over to the right, but you can’t go down or to the left.  (Props go to Michael Gaffney for working with me to come up with this rule years ago).  Over to the right?  I’m working in the context of a layered architecture and when I say “over to the right,” I’m talking about something like this:

presentation -> business -> persistence -> general utilities

So starting on the left, dependencies flow to the right.  You wouldn't want to go back to the left.  That would introduce a cycle.  Also, within a layer, you could go up the package hierarchy, but you wouldn't want to go down.

Here’s an example.  Suppose I’m developing a web application and I’m working on a class in the presentation layer.  I might have something like (contrived):

package com.mycompany.myapp.web.struts;
 
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mycompany.myapp.utils.SomeUtil;
import com.mycompany.myapp.domain.SomeDomainObject;
import com.mycompany.myapp.domain.SomeOtherDomainObject;
import com.mycompany.myapp.web.SomethingHigher;
import com.mycompany.myapp.web.utils.SomethingToTheRightWithinModule;

Now, ideally, I’d like to list those imports in the exact opposite order.  That way, I could start at the package statement and look down and make sure the imports flow in an acceptable, directed acyclic graph kind of order, following the rule above.  In fact, I used to list them in this order, but everybody else lists them in an order more like the above, and so, I accepted defeat and now follow suit.  I just start at the bottom and look up.

I only care about ordering among packages here.  I don’t try to list the imports in dependency order among classes at the same package level.  That would be crazy.  However, I am strict within the layer of the class I’m working with.  In the example, that would be the web layer.  I’m looking at a class in ...web.struts and I want to make sure that I’m going to the right first, then up, all within com.mycompany.myapp.web in an appropriate package order.

Once I’m past the web layer, I loosen up.  I just want to make sure all the imports for the next layer are grouped together, and so on.  So in the example, all the domain imports would be together, then all the utils, and so on, all the way up to java.util.

You can set up this ordering standard in Eclipse under the Organize Imports preference.

How else could you check your dependencies?  There are useful tools out there like JDepend, and I use them.  But I still like this import ordering practice.  I typically do the manual scan right before check in time.

Small Methods: A Best Practice

Originally published 22 Jan 2006

If you've read my previous entry Coding By Intention, you know I like small methods.  Small methods are easy to understand and easy to maintain - they’re small after all.  The name of a small method can reveal your intent to those higher level methods using it.

Besides these obvious things, small methods remove duplication and thus provide chunks of reusable code.  When I’m doing test-driven development, after I’ve coded by intention and refactored by extracting methods, I wind up with several small methods that are typically private scope in the class I’m developing.  These private methods are potential candidates for reusability - reusability beyond the class I’m working with.  In another blog entry, I want to go into detail on this part, but for now, I’ll give you a little teaser: these small, private methods typically belong on another object (one of the objects passed in as an argument) or maybe on a utility class.

There are a couple of negatives to small methods.  One is performance.  There is extra overhead in making method calls.  But really, I find this impact negligible and not worth discussing.
The biggest negative is when you’re tracing through code.  Maybe you’re doing a code review, debugging, or maybe just want to understand all the details.  It is pretty annoying sometimes to keep drilling down in methods and then trying to remember how you got to where you are and then trying to find your way back to where you started.  However, I’ll make this sacrifice to get all the benefits of reusability, algorithmic clarity, etc. that small methods provide.

So how did I get to where I am today?  Early in my career, I came up with a standard of making methods fit on a printed, landscape page.  I even printed out a page to see how many lines that was.  It was about 65.  I told this to a colleague of mine, Brian Mills.  I said, “I like being able to see an entire method on one page.”  He said, “One page?  I like seeing an entire method on my screen!”  After that, I looked at Brian’s code.  It was the best code I’d ever seen.  I adopted his practice.

Shortly afterward, I remember taking an object-oriented analysis and design course.  During a break, I was discussing the method lines practice with the instructor, who said something like all methods should be 10 lines or less.  At that time, I couldn’t even understand how that was possible, with exception handling, logging and all.

Then, the agile movement started and I read books like Martin Fowler’s Refactoring and I learned about coding by intention.  I started to understand that OOAD instructor.

Today, my methods range from one line to a screenful.  A screenful in my Eclipse IDE is 36 lines.  Those 36 lines include the start of Javadoc to the ending bracket of the method.  The one line methods are either trivial or intention revealing methods (like the notTooCold() method from my earlier blog).  Admittedly, I do go over a screen from time to time.  It’s most likely because I’ve been lazy.  Whenever I feel a method is getting too long, I look for reusability and intention, and extract methods.

Coding By Intention

Originally published 10 Jan 2006

I thought I'd start blogging about something I think I'm pretty decent at - programming.  Yeah, yeah, I know, everybody thinks they are the best programmer, but I think I have some decent stuff to share.  I wanted to start with programming tips.  I'll try one tip per blog entry.
The first tip is coding by intention. The first time I learned of this was in college. I was reviewing some code with a professor of mine, Dave Binkley of Loyola College. We were reviewing a long method of mine and Professor Binkley said something equivalent to, “I like to extract a method here to make it more clear what I’m doing.” The light came on. I learned that programming was more than just a science, but an art. This was back in the early 90s, before the Extreme Programming/Agile folks coined terms like “extract method”, “refactor”, and “code by intention”.

Now, I'm a big fan of Test-Driven Development (TDD).  Since I've got to write a test first, I start there.  The real code doesn't exist yet.  The intent part starts here.  I think, "I've got this piece of functionality to implement.  What would I call if I could write anything?  What would the method name be and its arguments?  How would I call this functionality as a client so that what I'm doing is crystal clear? The world is my oyster."

Coding by intention from the point of view of the test is pretty obvious.  What I wanted to emphasize in this blog entry is to continue coding by intention all the way through until you've completely implemented everything.  So after you've created a new call in the test, you start implementing it.  It'll most likely be a public method.  When you're implementing this, you continue coding by intention.  You could just crank out a possibly long method to get the functionality implemented, but that's not what I'm talking about – that’s what I did in the early days of college.  The public method now becomes like another client.  You code by intention here, asking yourself what you would call if what you needed already existed.  You keep doing this with every method you need to implement, creating lots of small, but communicative and easy to understand methods.  Eventually, you'll get to a level where the implementation is small and simple and you're done.  What you've done is created some possibly reusable and very easy to maintain methods along the way.

It’s time for an example. Suppose I’m working with the usual Order/Line Items web site shopping example. One coding by intention technique I use when I need to process a collection like LineItems looks like this:

    public void processLineItems(List lineItems) {
        Iterator it = lineItems.iterator();
        while (it.hasNext()) {
            process((LineItem) it.next());
        }

    }

Instead of writing all the code in the while loop to process an item, I code by intention, pretending that the process(LineItem) method already exists.
Here’s another, albeit obviously contrived example. Suppose I’m working on Goldilocks’ Porridge class and need to implement the isJustRight() method. Right now I just have:

    public class Porridge {

        private double currentTemperature = 0.0;
       
        public Porridge(double currentTemperature) {
            this.currentTemperature = currentTemperature;
        }
    }

To implement isJustRight(), in coding by intention style, I would do:

        public boolean isJustRight() {
            return (notTooHot() && notTooCold());
        }

So why code by intention? There are several reasons I can think of off the bat. The first is, as I’ve stated above, you end up creating small, possibly reusable methods. My first tip was going to be “create small methods”, but I realized that coding by intention drives that. In my next entry, I’ll go into more detail on why I think creating small methods is really important. There’s a process to crafting elegant software and this is the first step.

Another reason is that the top level methods become really easy to understand.
They describe the algorithm in almost pseudo-code level. They communicate your intent of what you’re trying to accomplish step by step.

Yet another reason is that it is sometimes hard to get started on a task and by coding by intention you are delaying all the details, but still getting things done. That is, not everything you need is available, but you’re coding like it is. You’re working top down, drilling down into the details level by level until your done, making progress along the way.

Now, if you’re doing true TDD, you are writing just enough test to get a failing test, and just enough code to pass that test. Remember, compiler errors count as failures. I’m a little lenient on this practice. I like writing an entire test method for one test case scenario before going to the code. So in the isJustRight() method above, I’d first write a complete test method for a Porridge object that is too cold with all its calls and assertions. Then, I’d write just enough code to get the test to pass, but still coding by intention in the Porridge class. So, in this case, the isJustRight() method would just call notTooCold() for now.

I suppose if you truly wanted to follow TDD, and in particular, get a passing test as fast as you could, you could just write the code in isJustRight(), then extract a notTooCold() method. Just remember to do this. Sometimes, we as programmers get a little lazy. Still, I favor coding by intention top down from the beginning.

Well, that’s it for my first blog. Hope you enjoyed.