The most common way I've seen of saving an entity into a database is through a class in a business / service layer. For example, when adding a new entity called
User user = new User(); user.Name = "Foo"; UserService userService = new UserService(); userService.Add(user);
This works, and objects are being used, but I feel that the style leans toward the procedural side. Usually, the
UserService class mostly contains methods for interacting with the database. You could almost make the
UserService class static, and then it won't really be considered as an object anymore.
In a purely object-oriented manner, I feel that the code would look like this:
User user = new User(); user.Name = "Foo"; user.Add();
My question is not about specific implementation details but about object-oriented design in general. Does using classes like the example
UserService indicate a procedural way of coding? If so, what could be a better object-oriented approach?
An example from the .NET framework that I feel is more object-oriented is
SqlConnection. How do we open a connection? Is there a
SqlService class from which you can call
sqlService.Open(sqlConnection)? No, but it is done from the
SqlConnection object itself:
Open method may use other classes in turn, but what's interesting to me is that it is exposed on the
SqlConnection class itself, much like how the
Add method is exposed in the
User class in the second snippet above.