Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a class?

The problem is really simple, I have a class "Stock", I want to load its property "StockName", "StockCode' from the db.

so which patten should I use?

pattern 1) Use service class to create it


 public interface IStockService{
             Stock GetStock(string stockCode);
             void SaveStock(Stock stock);
         }
         public class StockService : IStockService{
         }

         IStockService stockService = new StockService();
         Stock stock = stockService.GetStock();

pattern 2) Use static method in Stock


        public class Stock{
            public static Stock GetStock(){
                Stock stock = new Stock;
                //load stock from db and do mapping.
                return stock;
            }
            public void Save(){
            }
        } 

pattern 3) Use constructor to load

        public class Stock{
            public Stock(){
                //load stock from db and do mapping.
                this.stockName = ...
                this.stockCode = ...
            }
        }

for pattern 1: it seems it use so many code to create a stock object, and the "SaveStock" method seems a little not object-orient.
for pattern 2: the "Save" method seems ok, but the GetStock method is a static method, it seems a Utility class which always use static method.
for pattern 3: the constructor will load the data from db when on initialize. it seems confused also.

like image 512
yi. Avatar asked Oct 22 '09 06:10

yi.


1 Answers

pattern 2) is the factory (method) patten and reminds me of singletons (static = singleton). Note singletons are evil. The factory method is not not polymorph. You can't change it for tests (i.e. you can't mock it). It's evil! Avoid it!

pattern 3) violates that the constructor should not do too much. Querying the database is too much for a ctor in my opinion. The object and it's creation are different concerns and should be separated. Further more creation of an instance should be separated from the instance, so try to use factories (or injectors). You can replace the factory easier than the "new Class" spread throught your code.

pattern 1) remains, which is an abstract factory pattern. It is good. You can use another implementation for testing (a mock). It separates the creation from the object. (Single responsibility principle as Carl Bergquist calls it.)

So I would go with pattern 1.

like image 87
Peter Kofler Avatar answered Oct 11 '22 23:10

Peter Kofler