jeudi 6 janvier 2022

library design patterns - single generic API VS specific APIs

Working on DailyStatsLib, a library for getting some stats based on the day of the week.

Is it better for DailyStatsLib to expose

  • option 1: a single generic API
  • option 2: expose a specific API for each day of the week

Option 1 (single generic API)

  • pros: simple interface and all logic is handled by DailyStatsLib
  • cons: AllInfoStruct (shown below) feels like a dumping ground for info for all days (and some of that info may not be available on a given day)

main.cpp

//using "std::optional" because not all info may be available on a given day
struct AllInfoStruct {
  std::optional<MondayStatsInfo> monday_info; //if day is Monday, this info will be available
  std::optional<TuesdayStatsInfo> tuesday_info; //if day is Tuesday, this info will be available
  std::optional<WednesdayStatsInfo> wednesday_info; //if day is Wednesday, this info will be available
  ...
} all_info_struct; //has all necessary info for getting stats on any day of the week

Day today = dayUtil.getDay();
Stats my_stats = DailyStatsLib::Manager.getInstance().getStats(today, all_info_struct); //single generic interface

Option 2 (day-specific API)

  • pros: APIs are more focused and easier to understand and test. Not much is hidden.
  • cons: Is main.cpp doing part of the work that DailyStatsLib should really be doing?

main.cpp

Stats my_stats;
Day today = dayUtil.getDay();
if(today == e_day_Monday){ 
    MondayStatsInfo ms;
    my_stats = DailyStatsLib::Monday.getInstance().getStats(ms);
}else if(today== e_day_Tuesday){
    TuesdayStatsInfo ts;
    my_stats = DailyStatsLib::Tuesday.getInstance().getStats(ts);
}else if(today== e_day_Wednesday){
    WednesdayStatsInfo ws;
    my_stats = DailyStatsLib::Wednesday.getInstance().getStats(ws);
}
...

Aucun commentaire:

Enregistrer un commentaire