What's your most reused class?

2019-03-23 19:04发布

问题:

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 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;
    }


回答2:

System.Object - almost all my types extend it.



回答3:

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;
  }


回答4:

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;
}


回答5:

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



回答6:

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



回答7:

Most reused? Hmmm...

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

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



回答8:

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



回答9:

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