Precautions

Although the generic types provided by the framework significantly enhance development convenience, they should be used with caution for business models (not abused), as generic types can obscure the actual data types. This can be more detrimental than beneficial for long-term maintenance in business projects, especially complex ones. The data types of a business model should be as clear, meaningful, and immutable as possible to facilitate type checking and optimization during the compilation stage, and to benefit long-term maintenance.

For example, here is a real business model case provided by an enthusiastic community member:

  1. type MiDispatchData struct {
  2. Status *g.Var `json:"status"`
  3. BrandId *g.Var `json:"brand_id"`
  4. AreaId *g.Var `json:"area_id"`
  5. Year *g.Var `json:"year"`
  6. Month *g.Var `json:"month"`
  7. Day *g.Var `json:"day"`
  8. Hour *g.Var `json:"hour"`
  9. RequestTime *g.Var `json:"request_time"`
  10. Source *g.Var `json:"source"`
  11. BikeId *g.Var `json:"bike_id"`
  12. BikeType *g.Var `json:"bike_type"`
  13. Lon *g.Var `json:"lon"`
  14. Lat *g.Var `json:"lat"`
  15. SiteId *g.Var `json:"site_id"`
  16. BikeMac *g.Var `json:"bike_mac"`
  17. }

While this approach allows the program to run normally and covers business scenarios, it loses the compiler advantage of compiled languages (similar to PHP variables), making it difficult to determine the data type of fields during later project maintenance.

Recommendations

  • Generics are more frequently used in foundational components and middleware projects.
  • If a field has multiple meanings or types in a business scenario, generics can be used instead of types like interface{}.