Avoid having Object in the method signature if a more specific type can be used instead.

For example, imagine a simple ReportGenerator class with a generate method that can accept a number of different kinds of objects as parameters to generate a report.  It also has a deepClone method to make a copy of the report generator.

public class ReportGenerator
{
    public String generate(Object[] parameters)
    {
        :
    }
}

The caller has no idea what kind of parameters the generate() method can accept.  A report parameter has some basic attributes, like type and question to display, so it can be encapsulated in a ReportParameter base class.

public class ReportGenerator
{
    public String generate(ReportParameter[] parameters)
    {
        :
    }
}

If for some reason, the generate method needed to accept an array of ReportParameter AND String types (hence the original Object parameters), two generate(..) methods should be written.

public class ReportGenerator
{
    public String generate(ReportParameter[] parameters)
    {
        :
    }

    public String generate(String[] parameters)
    {
        // convert String[] parameters to ReportParameter types.
        ReportParameter[] newParams = new ReportParameter[
                                                 parameters.size];
        for (int i=0; i<parameters.size; i++)
        {
            newParameters[i] = new StringParameter(parameters[i]);
        }
        // call the other main generate method
        return generate(newParameters);
    }
}

Unless writing for library code where the returned value or parameters can be any type, avoid using Object – use a concrete class instead.  If there is a chance for a method to return two different unrelated types, create two methods, but avoid returning Object unless there is no alternative.

Which of these methods would you prefer to see as a caller?

public Object[] getHistory()
{
    :
}

public Object deepClone()
{
    :
}

The deepClone() method returns a non-specific Object, presumably to future-proof some code that has clearly not been written in a reusable fashion.  The following would be much nicer to call.

public HistoryInfo[] getHistory()
{
    :
}

public Customer deepClone()
{
    :
}  

Tip: Always use strongly typed return values if you can. Never return Exception or Object.

blog comments powered by Disqus