views:

550

answers:

9

Every programmer ends up with a set of utility classes after a while. Some of them are true programming pearls and they are reused in several of your projects. For example, in java:

 class Separator {

        private String separator;
        private boolean called;

        public Separator(String aSeparator) {
            separator = aSeparator;
            called = false;
        }

        @Override
        public String toString() {
            if (!called) {
                called = true;
                return "";
            } else {
                return separator;
            }
        }
    }

and:

public class JoinHelper {

    public static <T> String join(T... elements) {
        return joinArray(" ", elements);
    }

    public static <T> String join(String separator, T... elements) {
        return joinArray(separator, elements);
    }

    private static <T> String joinArray(String sep, T[] elements) {
        StringBuilder stringBuilder = new StringBuilder();
        Separator separator = new Separator(sep);

        for (T element : elements) {
           stringBuilder.append(separator).append(element);
        }

        return stringBuilder.toString();
    }
}

What is your most reused class?

+1  A: 

Logger class: Which logs the flow of control in a log file.

Vinay
+6  A: 

System.Object - almost all my types extend it.

Andrew Hare
+1  A: 

Configuration Reader/Setter: which reads the configuration from ini/xml file and sets the environment of the application

Vinay
+1  A: 

Most reused? Hmmm...

boost::shared_ptr<> with boost::weak_ptr<>

probably most reused (also probably most bang-for-buck ratio)

Doug T.
+1  A: 

Globals

Just a simple class with static DBConnString, and a few other app wide settings.

Have reused the simple file in about 2 dozen projects since working with .Net

Neil N
+2  A: 

A utility class that has logging and email functionality. An extensions class that contains extension methods. A reporting class that basically harness the reporting services web service and makes it easy to stream reports as excel, pdf, etc.

Examples...
1.) Utility Class (static)

   public static void LogError(Exception ex)
    {
        EventLog log = new EventLog();
        if (ex != null)
        {
            log.Source = ConfigurationManager.AppSettings["EventLog"].ToString();
            StringBuilder sErrorMessage = new StringBuilder();
            if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
            {
                sErrorMessage.Append(HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine);
            }
            sErrorMessage.Append(ex.ToString());
            log.WriteEntry(sErrorMessage.ToString(), EventLogEntryType.Error);
        }
    }

2.) Extensions Class

   public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
    {
        if (condition)
            return source.Where(predicate);
        else
            return source;
    }
RSolberg
+3  A: 

Most reused but boring:

public static void handleException(Exception e) throws RuntimeException {
 if (e instanceof RuntimeException) {
  throw (RuntimeException) e;
 }

 throw new RuntimeException(e); //NOPMD
}

Less boring (also methods for building lists and sets):

/**
   * Builds a Map that is based on the Bean List.
   * 
   * @param items Bean List items
   * @param keyField Bean Field that will be key of Map elements (not null)
   * @return a Map that is based on the Bean List
   */
  @SuppressWarnings("unchecked")
  public static <T, K> Map<K, T> buildMapFromCollection(final Collection<T> items,
                                                        boolean linkedMap,
                                                        final String keyField,
                                                        final Class<K> keyType) {
    if (items == null) {
      return Collections.emptyMap();
    }

    if (keyField == null) {
      throw new IllegalArgumentException("KeyField is null");
    }

    final Map<K, T> result;

    if (linkedMap) {
      result = new LinkedHashMap<K, T>();
    } else {
      result = new HashMap<K, T>();
    }

    BeanMapper mapper = null;
    for (final T item : items) {
      if (mapper == null) {
        mapper = new BeanMapper(item.getClass());
      }
      final K key = (K) mapper.getFieldValue(item, keyField);
      result.put(key, item);
    }
    return result;
  }
HappyCoder
+1  A: 

A ConcurrentDictionary I wrote, which I now seem to use everywhere (I write lots of parallel programs)

Martin
+2  A: 
public static short getLastDayOfMonth(short givenMonth, short givenYear)
{
    short lastDay = 31;
    switch (givenMonth)
    {
        case 4:
        case 6:
        case 9:
        case 11:
            lastDay = 30;
            break;
        case 2:
            if ((int)givenYear % 4 == 0)
            {
                lastDay = 29;
            }
            else
            {
                lastDay = 28;
            }
            break;    
    }
    return lastDay;
}
mr_dunski
Too bad this is buggy. http://www.dataip.co.uk/Reference/LeapYear.php Your algorithms will return 29 for 1900, when it should be 28.Why not use Joda time or something like that?
I82Much