简体   繁体   中英

Save as object or just a row in database?

As a practice project, I'm creating a calorie tracking app. Part of that requires creating individual food items that can be saved for reuse. A single food item would consist of a name, a calorie count, a serving size, etc. I'm thinking about the best way to save these food items, and it seems reasonable to connect the project to a database. Specifically I'm using MySQL.

The question I have then is whether each food item should simply exist in storage as a row in a database with a column for each field (name, calories, etc), or if I should create a foodItem class with an instance for each food item. This seems redundant, but at the same time, if I don't create an object, it seems to me this would be counter to OOP principles and database use would almost always replace class/object creation. Couldn't a user just write straight into the database without creating an object? What am I missing here?

As a design practice, I like to have "software objects" such as FoodItem which, among other things, know how to "persist themselves" in an underlying database. They know how to populate themselves, and how and when to update the database. As much as possible, all of the details of "database representation" are hidden within the objects' implementations.

The actual manner in which you represent the data in the database also depends very much on your reporting requirements. Think about the sort of summary statistics, catalogs, and other things which you might need to produce from these data using separate tools.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM