views:

139

answers:

5

I have a question, here is an example
I have a Model class: Stock


    public class Stock{
     //some properties, stock name, stock code;
     public String StockName{
      get,set
     }
     public String StockCode{
      get,set
     }
    }

Also I have a service class StockService, which will load the data from database and create the stock and setting the properties value.


    public class StockService:IStockService{
     public Stock CreateStockByStockCode(string stockCode){
      Stock stock = new Stock();
      //load the data from db and set the stock's properties.
      stock.StockName = ...
      stock.StockCode = ...
     }
    }

so, my question, i have a "Save()" method, where should I put,
Option1 : put it in the Stock class,


    public class Stock{
     public void Save(){
      //use the repository to save into db.
     }
    }

Option2: put it in the service class


    public class StockService:IStockService{
     public void Save(Stock stock){
      //use the repository to save into db.
     }
    } 


i think for the option1: the stock seems a little smart, it can save itself and more ojbect-oriented. And for the option2, I saw a lot of guys use this kind of pattern. What's you idea?

+8  A: 

Putting the Save() method into the service will prevent the Stock class from requiring any knowledge about the database structure. Putting Load() and Save() into two different classes would probably be pretty confusing, too.

longeasy
+1  A: 

I prefer Option 2 because of what you just said because then "the stock seems a little smart". I believe this makes a little more sense, for example, when you want to Delete your stock.

Dave
A: 

The Stock shouldn't care about where it's stored, thus both save and load should be in the service class imo.

sindre j
A: 

I agree, go for option 2 so that you decouple your data entity classes from the actual data storage. By the way, you may want to take a look at the Repository Pattern.

Konamiman
+5  A: 

You may want to read up on both the Active Record pattern and the Repository pattern. You are somewhere in between here.

Active Record is considered 'simpler', while Repository is more 'pure' in that you get a better separation of concerns (your entities don't need to be concerned with data access).

jeroenh