Tuesday, April 3, 2012
Đầu tư giá trị, văn hóa doanh nghiệp: Trò chuyện cùng CEO 8X
Friday, March 9, 2012
Factors influencing investment decision
(i) Management Outlook: lf the management is progressive and has an aggressively marketing and growth outlook, it will encourage innovation and favor capital proposals which ensure better productivity on quality or both. In some industries where the product being manufactured is a simple standardized one, innovation is difficult and management would be extremely cost conscious. In contrast, in industries such as chemicals and electronics, a firm cannot survive, if it follows a policy of 'make-do' with its existing equipment. The management has to be progressive and innovation must be encouraged in such cases.
(ii) Competitor’s Strategy: Competitors' strategy regarding capital investment exerts significant influence on the investment decision of a company. If competitors continue to install more equipment and succeed in turning out better products, the existence of the company not following suit would be seriously threatened. This reaction to a rival's policy regarding capital investment often forces decision on a company'
(iii) Opportunities created by technological change: Technological changes create new equipment which may represent a major change in process, so that there emerges the need for re-evaluation of existing capital equipment in a company. Some changes may justify new investments. Sometimes the old equipment which has to be replaced by new equipment as a result of technical innovation may be downgraded to some other applications, A proper evaluation of this aspect is necessary, but is often not given due consideration. In this connection, we may note that the cost of new equipment is a major factor in investment decisions. However the management should think in terms of incremental cost, not the full accounting cost of the new equipment because cost of new equipment is partly offset by the salvage value of the replaced equipment. In such analysis an index called the disposal ratio becomes relevant.
Disposal ratio = (Salvage value, Alternative use value) / Installed cost
(iv) Market forecast: Both short and long run market forecasts are influential factors in capital investment decisions. In order to participate in long-run forecast for market potential critical decisions on capital investment have to be taken.
(v) Fiscal Incentives: Tax concessions either on new investment incomes or investment allowance allowed on new investment decisions, the method for allowing depreciation deduction allowance also influence new investment decisions.
(vi) Cash flow Budget: The analysis of cash-flow budget which shows the flow of funds into and out of the company may affect capital investment decision in two ways. 'First, the analysis may indicate that a company may acquire necessary cash to purchase the equipment not immediately but after say, one year, or it may show that the purchase of capital assets now may generate the demand for major capital additions after two years and such expenditure might clash with anticipated other expenditures which cannot be postponed. Secondly, the cash flow budget shows the timing of cash flows for alternative investments and thus helps management in selecting the desired investment project.
(vii) Non-economic factors: new equipment may make the workshop a pleasant place and permit more socializing on the job. The effect would be reduced absenteeism and increased productivity. It may be difficult to evaluate the benefits in monetary terms and as such we call this as non-economic factor. Let us take one more example. Suppose the installation of a new machine ensures greater safety in operation. It is difficult to measure the resulting monetary saving through avoidance of an unknown number of injuries. Even then, these factors give tangible results and do influence investment decisions.
Thursday, March 8, 2012
Three Factors That Affect Purchase Decisions
Apple, Inc. was flawless in their execution when they rolled out the new iPhone and iTouch because they knew what made consumers act. They knew the emotional hot buttons. They knew how to create enough excitement about a new line of entertainment gear that for many, a simple “want” transformed into a self-justified, immediate need. The iPhone and iTouch hit the market with a fury like the Running of the Bulls and Apple’s stock skyrocketed. So did the net worth of Steve Jobs, a hard-charging and creative businessman who understands the consumer.
If you want a better understanding of how consumers act, implement these three factors into your marketing and sales plans:
The Economic Factor – This is the foundation of a purchasing decision. People can’t buy what they can’t afford no matter how badly they need it or want it. However, affordability is often a matter of perspective, which would explain why so many consumers use “creative” budgeting to get the things they really want. This practice has led to the special finance market and a struggling mortgage industry, and it has you reading this article.
In our business, the economic factor is represented in the terms of down payments and monthly payments. You will be better served to hold your considerations of this most basic of the three factors to the end, long after you’ve gained the attention and interest of your prospects. Otherwise, you will run into the common scenario of “these customers have no money” problems. To stay off that road, focus on the other two factors first.
The Functional Factor – The functional factor is all about needs. It’s about logic, what makes sense and the best interest of the customer. Although it too plays an important role in the decision to buy, it is the boring factor and typically doesn’t affect emotional appeal.
That being said, the functional factor is perhaps the most important of all three when it comes to special finance. A dealer must set the customer up for success and not for failure. It is much too easy to get a customer excited about a vehicle that is out of their price range and/or does not meet their needs. A dealer with a strong special finance program is able to weave logic into the equation and convince the customer to do what is in their best interest by taking time to learn and understand their needs first.
If you take the time to uncover the needs with a thorough analysis, you will build more rapport and be much more likely to earn the customer’s trust in the process. Then, when you introduce the logical choice later in the sale, your customer will be more apt to follow your advice and direction rather than seeing you as just another fast-talking salesperson.
The Psychological Factor – All effective advertising appeals to emotion, or the psychological side of the sale. The psychological factor is all about what the customer wants. To divert the customer from the “wrong” vehicle and effectively bypass price, a special finance salesperson must introduce the psychological elements of the sale early in the process. One effective method that I recommend is to show the customer the merits of establishing or re-establishing a positive credit score. To be effective, you have to build the vision of an easier life for them with good credit, and then, get their buy in.
Personal image is also an important emotional hot button. Having an iPhone is a social statement. Likewise are having a nice car and home. People want the best they can afford and, more often than not, the best they can’t afford. That’s why the most powerful commercials focus on image and not price. Image, fear, wants and dreams are all powerful emotional forces that drive the decision to buy. If used in a timely fashion, they will be the forces behind higher down payments and profit.
Trước khi mua cổ phiếu bạn phải tính đến...
Category: FUNDAMENTAL ANALYST
Published on Wednesday, 30 November -0001 07:06
Hits: 622
Sách dạy về chứng khoán có bán khá nhiều, song đại đa số khuyên bảo giống nhau, chỉ cho nhà đầu tư các công thức, song ít khi chỉ bảo cách nhìn nhận, đánh giá, những ranh giới được và không được để giúp nhà đầu tư "hành tẩu” đúng trên sàn và ngoài sàn. Bài viết này đưa ra một số tri thức để giúp các nhà đầu tư nhìn nhận những cơ hội thực sự cho mình.
1- Đừng chú ý đến cổ tức ngay, hãy xem Công ty đó ở trong ngành nào trước
Chính vấn đề tưởng trừng không liên quan trực tiếp đến giá cổ phiếu này lại là một trong những nhân tố quan trọng nhất quyết định cổ phiếu đó có tăng giá nhiều hày không trong tương lai. Nếu một Công ty chuyên tư vấn du học niêm yết trên thị trường chứng khoán, giá của nó đương nhiên khó có thể cao được bởi đa số các Công ty du học là các Công ty loại OMS tức chỉ hoạt động quy mô nhỏ, phụ thuộc vào tài năng và sự chăm chỉ của một hay vài người, giống như cây bonsai, khó có thể lớn lên và nhân rộng được quy mô. Trong khi đó, nếu các Công ty trong ngành tài chính, các Ngân hàng, Công ty xây dựng, bất động sản (đúng nghĩa chứ không phải là “cò nhà”), Công ty hàng tiêu dùng nhanh, Công ty truyền thông… thì khả năng mở rộng quy mô hoạt động, tăng cường kinh doanh là rất lớn. Vinamilk, Kinh Đô, REE, Sacombank, Ngân hàng ACB, Sudico... giá cao điều đầu tiên đều do họ thuộc các ngành đầy triển vọng này.
2- Có hay không khả năng mở rộng kinh doanh?
Vấn đề này chính là vấn đề phải xem xét tiếp theo. Nếu một Công ty có khả năng mở rộng liên tục quy mô sán xuất kinh doanh của mình thì giá của chúng sẽ tăng, đó là điều đương nhiên. Dẫn chứng sắc nét có thể đưa ra ngay là giả định có 2 Công ty cùng có cụm từ thủy điện trên tên giao dịch như "Công ty Thủy điện ABC" và "Công ty Đầu tư Thủy điện XYZ" thì giá của Công ty thứ hai đương nhiên sẽ cao, còn Công ty thứ nhất sẽ khó lòng lên đến đầu 4x, trong khi đó, nếu Công ty thứ hai có thể lên đến trên 10x, thậm chí 20x là bình thưởng. Giá chênh như vậy là dễ hiểu bởi Công ty thứ nhất chỉ có 1 nhà máy thủy điện duy nhất. Nhà máy này xây một lần rồi thôi, không có khả năng mở rộng sản xuất, không đắp cao đập lên được, không lắp thêm máy, không tăng công suất phát điện được, nhà đầu tư chí có thể trông vào cố tức mà thôi. Trong khi đó, ở Công ty thứ hai, vốn điêu lệ ban đầu có thể chỉ là 50 tỷ, song Công ty lại có khả năng tham gia đầu tư vào rất nhiều: 10, 100 và hơn nữa các Nhà máy thủy điện nên vốn đầu tư có thể tăng tương ứng và quyền lợi của nhà đầu tư tăng theo đà đó.
3- Nhìn vào cả quá trình thay vì chỉ vào một thời điểm
Lịch sử một Công ty nói lên nhiều điều. Trước hết nếu Công ty đó có cả một lịch sử rất dài nhưng các "chỉ số cơ thể" hiện đều nhàng nhàng thì khó có đột biến đáng mừng cho nhà đầu ra bởi thời gian đã chứng minh Công ty đó không có gì xuất sắc. Nếu 5 năm trước, các chỉ số tài chính của Công ty tốt, song vào thời điểm nhà đầu tư xem xét, chỉ số đó đang tụt dần thì hãy cẩn thận: dù chí số đó, vào thời điểm đó đã tốt song có gì đám bảo nó sẽ không tụt dốc tiếp?
4- Nhìn vào đội ngũ, hơn là chỉ nhìn vào chỉ số tài chính
Lịch sử các Công ty hay ngân hàng Việt Nam đã chứng minh là vấn đề đội ngũ nói chung và đội ngũ quản lý là vô cùng quan trọng với một Công ty. Nếu các nhân tố nói trên căn bản tốt, có đội ngũ tốt, Công ty đó sẽ ăn nên làm ra và trong trường hợp đó, lợi nhuận của nhà đầu tư sẽ cao hơn nhiều. Thậm chí lịch sử đã chứng minh nếu một doanh nghiệp đang kém nhưng xuất hiện một đội ngũ tất thì doanh nghiệp đó vẫn có thể lội ngược dòng. VP Bank là một trường bị hợp điển hình. Vào năm 2002, VP Bank vẫn đang trong tình trạngkiểm soát đặc biệt. Nhưng sau đó, với sự thay đổi nhân sự, với quyết tâm cao và định hướng đúng, ngân hàng này không những ra khỏi tình trạng bị kiểm soát đặc biệt mà còn có nhiều bước phát triển ngoạn mục, trở thành một trong những ngân hàng lớn nhất và tất nhất. Giá cổ phiếu vào thời điểm đó thường được mua bán dưới mệnh giá (thậm chí lúc thấp nhất chỉ còn 0,25 lần mệnh giá) đã nhanh chóng lên đến cao nhất khoảng 7,4 lần mệnh giá.
5- Hãy lưu ý đến các cổ đông là pháp nhân
Các cổ đông pháp nhân có vai trò khá quan trọng với cổ phiếu của một Công ty. Nếu trong số cổ đông đó, có nhiều ngân hàng, Công ty tài chính, các Công ty có tên tuổi, đó chắc chắn là một điểm căn cứ để "lên điểm” của cổ phiếu đó. Điểm của Công ty càng lên nếu đó là các Công ty hay ngân hàng nước ngoài, Công ty cổ phần, ngân hàng thương mại cổ phần.
6- Chú ý đến động thái của các quỹ đầu tư
Ở Việt Nam hiện tại, còn quá ít các quỹ đầu tư song nhà đầu tư cũng nên chú ý đến động thải của các quỹ này. Các quỹ thường có "giác quan" rất nhạy nên họ sẽ quyết định đầu tư vào những nơi nào có triển vọng nhất. Tuy nhiên, ngược lại, cũng có nhiều Công ty tốt song không muốn bán cho các quỹ này bởi nhiều quỹ chỉ muốn gặt hái lợi nhuận đơn thuần và thường đầu tư theo kiểu ngắn hạn, nếu có lời là có thể bán ngay.
7- Cần có thông tin rõ ràng
Tất nhiên, đây là một việc quan trọng khi xem xét đầu tư vào cổ phiếu của một Công ty nào đó. Không nên mua cổ phiếu khi không có đầy đủ thông tin cần thiết về Công ty đó. Hệ thống thông tin và các quy định về công bố thông tin của các Công ty khi phát hành cổ phiếu ở nước ta còn rất sơ sài. Với Công ty lên sàn niêm yết, mọi việc đơn giản hơn vì ít nhất Công ty đó phải có cáo bạch. Đối với Công ty mới có cổ phiếu OTC, bạn cũng nên đòi người bán phải cung cấp thông tin như báo cáo tài chính hàng năm, báo cáo kiểm toán.
8- Chú ý đến các chỉ số tài chính và P/E của Công ty
Có nhiều cách tính chỉ số P/E, nhà đầu tư có thể tham khảo trên các cuốn sách về chứng khoán được bán rất nhiều ở các hiệu sách khắp cả nước. Nhưng quan trọng hơn, chỉ số thế nào thì mua, chỉ số nào thì không mua?
Theo các chuyên gia chứng khoán, nếu P/E của một Công ty ở mức dưới 12, bạn có thể mua cổ phiếu đó mà không cần cân nhắc gì nhiều. Nếu P/E ở mức 12 - 18 nên cân nhắc và hỏi ý kiến chuyên gia xem có nên đầu tư hay không. Còn nếu P/E ở mức trên 18, thường chỉ nên bán. Đây là các cột mốc song chi có tính tương đối và luôn phải xem xét đến các nhân tố tương lai (nhất là các quyền lợi sắp phát sinh, yếu tố ngành nghề… để "tính lại" P/E trong tương lai gần là bao nhiêu rồi mới nên kết luận là mua hay bán.
9- Không thể thiếu các “nhân tố vô hình”
Một điều các chuyên gia của chúng ta thường không nhắc đền nhiều nhưng lại là câu hỏi mà các nhà đầu tư khôn ngoan bao giờ cũng hỏi khi tìm hiểu về một cổ phiếu, đó là các giá trị mô hình của doanh nghiệp đã được tính đến chưa và nếu tính thì giá là bao nhiêu. Giá đó là đắt hay rẻ? Giá trị mô hình này có thể là lợi thế thương mại. Thí dụ như PV Driuing có lợi thế độc tôn trong ngành dầu khí là một nhân tố phải tính đến của Công ty này. Cavico Mining có một hợp đồng khai mỏ lớn và lâu dài đến khoảng 15 năm liền đảm bảo công ăn việc làm trong một thời gian dài cũng là lợi thế. Vinamilk có thương hiệu và một loạt nhãn hiệu nổi tiếng, đã ăn vào tâm trí người tiêu dùng cũng là lợi thế lớn trên thị trường.
Nhìn chung, khi nhìn nhận một cổ phiếu phải xét đến rất nhiều nhân tố. Đó chính là điểm khởi phát cho những thành công khi nhà đầu tư bước chân vào thị trường cổ phiếu. Chúng tôi sẽ còn một số bài viết sâu hơn cho bạn đọc về những vấn đề này trong các số báo tới.
Một trong những yếu tố quan trọng nhất khi bước chân vào sân chơi chứng khoán đó là tìm kiếm công ty để bạn có thể mua cổ phiếu. Và một khi bạn đã tìm hiểu và nghiên cứu về loại cổ phiếu mà bạn quan tâm và có một nhà môi giới để giúp bạn mua thì việc mua cổ phiếu lại là một việc tương đối dễ dàng.
Tìm cổ phiếu như thế nào?
Bước 1: Hãy tìm hiểu những báo cáo tài chính công khai của các doanh nghiệp mà có những thông tin liên quan đến chứng khoán.
Bước 2: Hãy phân tích những bản báo cáo hàng quý của công ty đó trong vòng hai hoặc ba năm trở lại đây, và đặc biệt chú ý đến xu hướng lợi nhuận tính theo cổ phiếu và doanh thu của công ty.
Bước 3: Hãy tìm cho mình một công ty có xu thế tăng trưởng ổn định nhất về lợi nhuận tính trên cổ phiếu.
Bước 4: Hãy tính tỉ lệ giá cả - lợi nhuận (tỉ lệ PE) của công ty đó, vì đây là một thước đo giá trị của cổ phiếu. (Tính tỉ lệ này bằng cách chia giá cổ phiếu cho lợi nhuận hàng năm tính theo cổ phiếu.)
Bước 5: Hãy so sánh tỉ lệ PE đó với các quy chuẩn của ngành và với tỉ lệ của chỉ số S&P 500. Tỉ lệ này càng thấp thì giá cổ phiếu càng rẻ so với lợi nhuận.
Bước 6: Hãy chú ý đến cả các món nợ của công ty đó. Vì vậy phải kiểm tra bảng cân đối kế toán của công ty và tìm đến phần thông tin về các món nợ dài hạn.
Bước 7: Ngoài ra cũng cần phải chú ý đến bảng lưu chuyển tiền tệ trong các báo cáo tài chính đó để xem tiền được lưu chuyển như thế nào trong hoạt động kinh doanh của công ty. Bởi vì chắc hẳn rằng bạn sẽ muốn nhìn thấy một bảng lưu chuyển tiền tệ có lãi chứ không phải là thua lỗ.
Mua cổ phiếu như thế nào?
Bước 1: Hãy trang bị cho bản thân đầy đủ những kiến thức về loại cổ phiếu trước khi bạn quyết định mua.
Bước 2: Hãy quyết định xem mình cần những gì từ người môi giới chứng khoán. Liệu mình có cần phải gặp trực tiếp người đó không? Liệu chỉ liên lạc với người đó qua điện thoại thôi có được không? Có phải giá cả là mối quan tâm duy nhất của bạn không? Có phải bạn chỉ muốn mua hoặc bán cổ phiếu hay là bạn còn muốn đầu tư cả vào những loại khác như quỹ tương hỗ, trái phiếu hay thậm chí cả cổ phiếu của nước ngoài.
Bước 3: Hãy chọn một nhà môi giới hoặc một công ty môi giới để thay bạn mua những cổ phiếu bạn muốn. Bạn có cần thật nhiều lời khuyên hay không? Nếu câu trả lời là có thì hãy tìm đến một hãng môi giới với dịch vụ trọn gói. Các nhà môi giới càng rẻ tiền sẽ càng cung cấp cho bạn ít lời khuyên mà bạn muốn. Nếu bạn khá tự tin vào khả năng của mình rồi và muốn mua các cổ phiếu giá rẻ? Vậy thì hãy thử tìm đến những lời khuyên và môi giới trên mạng Internet xem sao.
Bước 4: Hãy liên lạc với người môi giới hoặc công ty môi giới chứng khoán để xin một lá đơn, và yêu cầu mở một tài khoản giao dịch chứng khoán.
Bước 5: Khi tài khoản đã được mở bạn có thể bắt đầu ngay việc mua hay bán cổ phiếu của mình.
Bước 6: Hãy rà soát lại các bản báo cáo bạn nhận được và đánh giá lại những gì đang diễn ra trên danh mục đầu tư của mình để xem bạn có đang đi đúng hướng để đạt được những mục tiêu trong đầu tư của bạn không?
Các mẹo vặt và vài lời nhắc nhở
Hãy hỏi bạn bè và đồng nghiệp để tìm cho mình được người môi giới chứng khoán hay công ty môi giới tốt và có uy tín. Nếu bạn không có được những lời khuyên từ một cá nhân nào, thì hãy tìm trên báo chí về tài chính để có những thông tin bạn cần.
Đầu tư chứng khoán không phải là một trò chơi, nó đòi hỏi bạn phải có những kiến thức thực sự và phải có trí thông minh nhất định. Phải nhớ là bạn luôn theo dõi chặt chẽ mọi diễn biến trên thị trường và đưa ra những quyết định sáng suốt kịp thời để bảo vệ chính bản thân mình.
vào cổ phiếu của hãng Chamber Lych, một công ty công nghệ đang nổi tại miền trung nước Mỹ mà không đầu tư vào một công ty lâu năm cũng trong lĩnh vực công nghệ là TechTech vì cho rằng công ty đang thất thế.
Trong hai tháng đầu tiên đầu tư, cổ phiếu của Lych liên tục tăng giá và cổ phiếu của TechTech thì hạ giá dần. Nhưng chỉ sau thời gian đó, đột nhiên cổ phiếu của TechTech lại tăng giá rất cao, trong khi cổ phiếu của Chamber lại đứng yên thậm chí có tin đồn là sẽ xuống giá nên không ai dám mua nữa. Kết quả, số tiền của hai người bạn Lane Jack và Peter Huge đã không phát sinh lợi nhuận, thậm chí có nguy cơ mất sạch. Cả Lane Jack và Peter Huge đều tiếc nuối vì đã không đầu tư vào cổ phiếu của TechTech.
Trong đầu tư chứng khoán việc lựa chọn cổ phiếu sẽ là rất quan trọng. Nó sẽ quyết định việc thành bại của cả quá trình đầu tư. Nhiều khi nhà đầu tư không nên nghe theo những gì nhà môi giới chứng khoán nói mà hãy dựa vào chính sự phân tích và suy xét của mình.
Mua loại cổ phiếu nào
Khi đã quyết định đầu tư vào cổ phiếu thường phải nghiên cứu xem loại cổ phiếu nào là hiệu quả nhất. Đây chính là lúc cần những thông tin về phân tích chứng khoán và tình hình công ty vì ít có cách nào mất tiền nhanh hơn là mua phải chứng khoán không tốt.
Một số tiêu thức để so sánh và lựa chọn:
- Chọn ngành cổ phiếu: ngành công nghiệp, nông nghiệp, giao thông vận tải, tài chính hay dịch vụ công cộng... Có thể đi vào nhiều ngành chi tiết hơn, ví dụ trong công nghiệp có thể là công nghiệp khai thác, công nghiệp chế biến hoặc công nghiệp sản xuất. Phân tích từng ngành kinh tế về tính chất, thị trường, khả năng phát triển, tăng trưởng bình quân, khả năng cạnh tranh, ảnh hưởng có tính chất chu kỳ;
- Chọn bất cứ công ty nào trong ngành nào thì cũng nên phân tích tình hình công ty đó trên các mặt: tình hình tài chính, lợi nhuận, lợi tức cổ phần, nhu cầu vốn, tình hình huy động vốn và những loại chứng khoán chủ yếu của công ty, đánh giá tình hình cổ phiếu của công ty về mặt tài chính, vị trí của công ty trong ngành, trình độ ban quản trị, ban điều hành và chính sách quản trị của công ty, địa điểm, vận tải, lao động, nguyên liệu, bằng sáng chế phát minh, v.v...
Muốn phân tích thấu đáo giá trị cổ phiếu của một công ty thì phải xem xét những nhân tố kể trên, đồng thời phải tham khảo sự đánh giá của các Trung tâm phân tích chứng khoán, các tổ chức xếp loại doanh nghiệp. Ngoài ra, cần chú ý đến việc đa dạng hóa cổ phiếu đầu tư để tránh được sự vận động của chu kỳ kinh doanh, sự thay đổi vị trí của một doanh nghiệp... Có thể đa dạng hóa theo nhiều cách như: mua cổ phiếu của nhiều ngành khác nhau; mua cổ phiếu của các công ty khác nhau; mua cổ phiếu của nhiều khu vực khác nhau; mua cổ phiếu của các công ty có những thành phẩm khác nhau; mua ở những thời điểm khác nhau... Tuy nhiên, nếu đa dạng hóa đầu tư quá mức cũng sẽ có những nhược điểm như: làm cho việc quản lý khó khăn, tốn nhiều công sức điều tra và phân tích, làm tăng chi phí mua bán, làm giảm bớt cơ hội đạt lợi nhuận cao.
Khi nào mua?
Một câu trả lời rất đơn giản là “khi nào cần thấy được thì mua”. Bởi vì một số không ít những nhà kinh doanh chứng khoán cho rằng họ thường sai lầm trong việc đánh giá về thị trường nói chung và một số cổ phiếu nói riêng. Nói theo một nghĩa nào đó thì những người kinh doanh chứng khoán là những người đầu tư giá trị, do vậy có những người khi thấy công ty trong giai đoạn hưng thịnh thì mua cổ phiếu và thậm chí có nhiều người thích mua cổ phiếu của những công ty đang ở giai đoạn thất thế.
Từ đầu thế kỷ XVIII ở thị trưưòng chứng khoán Tây Âu và thị trường chứng khoán Mỹ sau này đã đưa ra học thuyết “Đầu tư ngược dòng”. Thuyết này đã đưa ra lời khuyên rằng “vẫn có thể lội ngược dòng sông”. Thực tế cho thấy, đầu tư ngược dòng có khả năng rủi ro rất cao nhưng cũng có cơ may đưa đến lợi nhuận khổng lồ bởi vì rất có thể thời gian thất thế của một công ty sẽ được khôi phục trong tương lai. Có nhiều người có cùng dự đoán lạc quan đó nên số người đầu tư ngược dòng tăng lên. Chính hành động có nhiều người có cùng nhận định, cùng mua cổ phiếu đã làm cho giá trị cổ phiếu được phục hồi uy tín ngay khi công ty này còn thất thế. Do vậy, không nhất thiết cứ phải mua cổ phiếu khi công ty đang có uy tín tốt mà vẫn có thể mua cổ phiếu khi công ty đang thất thế.
Sưu tầm
Trang thông tin tổng hợp Phố Chứng Khoán
Thursday, January 5, 2012
Domain Logic and SQL
Over the last couple of decades we've seen a growing gap between database-oriented software developers and in-memory application software developers. This leads to many disputes about how to use database features such as SQL and stored procedures. In this article I look at the question of whether to place business logic in SQL queries or in-memory code, considering primarily performance and maintainability based on an example of a simple, but rich SQL query.
February 2003
Martin Fowler
Translations: Japanese
Tags: database
Contents
Complex Queries
Transaction Script
Domain Model
Logic in SQL
Looking at Performance
Modifiability
Understandability
Avoiding Duplication
Encapsulation
Database Portability
Testability
Summing Up
Look at any recent book on building enterprise applications (such as my recent P of EAA) and you'll find a breakdown of logic into multiple layers which separate out different parts of an enterprise application. Different authors use different layers, but a common theme is a separation between domain logic (business rules) and data source logic (where data comes from). Since a large part of enterprise application data is stored on relational databases, this layering scheme seeks to separate business logic from the relational database
Many application developers, particularly strong OO developers like myself, tend to treat relational databases as a storage mechanism that is best hidden away. Frameworks exist who tout the advantages of shielding application developers from the complexities of SQL.
Yet SQL is much more than a simple data update and retrieval mechanism. SQL's query processing can perform many tasks. By hiding SQL, application developers are excluding a powerful tool.
In this article I want to explore the pros and cons of using rich SQL queries that may contain domain logic. I have to declare that I bring a OO bias to the discussion, but I've lived on the other side too. (One former client's OO expert group ran me out of the company because I was a "data modeler".)
Complex Queries
Relational databases all support a standard query language - SQL. Fundamentally I believe that SQL is the primary reason why relational databases have succeeded to the extent they have. A standard way of interacting with databases has provided a strong degree of vendor independence, which both helped the rise of relational databases, and helped see off the OO challenge.
SQL has many strengths, but a particular one is extremely powerful capabilities for querying the database, allowing clients to filter and summarize large amounts of data with very few lines of SQL code. Yet using powerful SQL queries often embed domain logic, which goes against the basic principles of a layered enterprise application architecture.
To explore this topic further, let's play with a simple example. We'll begin with a data model along the lines of Figure 1. Imagine our company has a special discount, which we'll call the Cuillen. Customers qualify for the Cuillen discount if they make at least one order in the month which includes more than $5000 worth of Talisker. Note that two orders in the same month of $3000 each doesn't count, there must be a single order for more than $5000. Let's imagine a you want to look at a particular customer and determine which months in the last year they qualified for a Cuillen discount. I'll ignore the user interface and just assume that what we want is a list of numbers corresponding to their qualifying months.
Figure 1: The database schema for the example (UML notation)
There are many ways we can answer this question. I'll begin with three crude alternatives: transaction script, domain model, and complex SQL.
For all these examples, I'm going to illustrate them using the Ruby programming language. I'm going out on a bit of a limb here: usually I use Java and/or C# to illustrate these things as most application developers can read C-based languages. I'm picking Ruby somewhat as an experiment. I like the language because it encourages compact yet well-structured code and makes it easy to write in an OO style. It's my language of choice for scripting. I've added a quick ruby syntax guide based on the ruby I'm using here.
Transaction Script
Transaction script is the pattern name I coined for a procedural style of handling a request in P of EAA. In this case the procedure reads in all the data it might need and then does the selection and manipulation in-memory to figure out which months are needed.
def cuillen_months name
customerID = find_customerID_named(name)
result = []
find_orders(customerID).each do |row|
result << row['date'].month if cuillen?(row['orderID'])
end
return result.uniq
end
def cuillen? orderID
talisker_total = 0.dollars
find_line_items_for_orderID(orderID).each do |row|
talisker_total += row['cost'].dollars if 'Talisker' == row['product']
end
return (talisker_total > 5000.dollars)
end
The two methods, cuillen_months and cuillen?, contain the domain logic. They use a number of "finder" methods that issue queries to the database.
def find_customerID_named name
sql = 'SELECT * from customers where name = ?'
return $dbh.select_one(sql, name)['customerID']
end
def find_orders customerID
result = []
sql = 'SELECT * FROM orders WHERE customerID = ?'
$dbh.execute(sql, customerID) do |sth|
result = sth.collect{|row| row.dup}
end
return result
end
def find_line_items_for_orderID orderID
result = []
sql = 'SELECT * FROM lineItems l WHERE orderID = ?'
$dbh.execute(sql, orderID) do |sth|
result = sth.collect{|row| row.dup}
end
return result
end
In many ways this is a very simple minded approach, in particular it's very inefficient in its use of SQL - requiring multiple queries to pull back the data (2 + N where N is the number of orders). Don't worry about that too much at the moment, I'll talk about how to improve that later. Concentrate instead on essence of the approach: read in all the data you have to consider, then loop through and select what you need.
(As an aside, the domain logic above is done that way to make it easy to read - but it isn't what I feel is idiomatic Ruby. I'd prefer the method below which makes more use of Ruby's powerful blocks and collection methods. This code will look odd to many people, but Smalltalkers should enjoy it.)
def cuillen_months2 name
customerID = find_customerID_named(name)
qualifying_orders = find_orders(customerID).select {|row| cuillen?(row['orderID'])}
return (qualifying_orders.collect {|row| row['date'].month}).uniq
end
Domain Model
For the second starting point, we'll consider a classical object-oriented domain model. In this case we create in-memory objects, which in this case mirror the database tables (in real systems they usually aren't exact mirrors.) A set of finder objects loads these objects from the database, once we have the objects in memory, we then run the logic on them.
We'll start with the finders. They slam queries against the database and create the objects.
class CustomerMapper
def find name
result = nil
sql = 'SELECT * FROM customers WHERE name = ?'
return load($dbh.select_one(sql, name))
end
def load row
result = Customer.new(row['customerID'], row['NAME'])
result.orders = OrderMapper.new.find_for_customer result
return result
end
end
class OrderMapper
def find_for_customer aCustomer
result = []
sql = "SELECT * FROM orders WHERE customerID = ?"
$dbh.select_all(sql, aCustomer.db_id) {|row| result << load(row)}
load_line_items result
return result
end
def load row
result = Order.new(row['orderID'], row['date'])
return result
end
def load_line_items orders
#Cannot load with load(row) as connection gets busy
orders.each do
|anOrder| anOrder.line_items = LineItemMapper.new.find_for_order anOrder
end
end
end
class LineItemMapper
def find_for_order order
result = []
sql = "select * from lineItems where orderID = ?"
$dbh.select_all(sql, order.db_id) {|row| result << load(row)}
return result
end
def load row
return LineItem.new(row['lineNumber'], row['product'], row['cost'].to_i.dollars)
end
end
These load methods load the following classes
class Customer...
attr_accessor :name, :db_id, :orders
def initialize db_id, name
@db_id, @name = db_id, name
end
class Order...
attr_accessor :date, :db_id, :line_items
def initialize (id, date)
@db_id, @date, @line_items = id, date, []
end
class LineItem...
attr_reader :line_number, :product, :cost
def initialize line_number, product, cost
@line_number, @product, @cost = line_number, product, cost
end
The logic of determining the cuillen months can be described in a couple of methods.
class Customer...
def cuillenMonths
result = []
orders.each do |o|
result << o.date.month if o.cuillen?
end
return result.uniq
end
class Order...
def cuillen?
discountableAmount = 0.dollars
line_items.each do |line|
discountableAmount += line.cost if 'Talisker' == line.product
end
return discountableAmount > 5000.dollars
end
This solution is longer than the transaction script version. However it's worth pointing out that the logic to load the objects and the actual domain logic are more separated. Any other processing on this set of domain objects would use the same load logic. So if we were doing a lot of different bits of domain logic the effort of the load logic would be amortized across all the domain logic, which would make it less of an issue. That cost can be even further reduced by techniques such as Metadata Mapping.
Again there's a lot of SQL queries (2 + number of orders).
Logic in SQL
With both of the first two, the database is used pretty much as a storage mechanism. All we've done is asked for all the records from a particular table with some very simple filtering. SQL is a very powerful query language and can do much more than the simple filtering that these examples use.
Using SQL to its full extent we can do all the work in SQL
def discount_months customerID
sql = <<-END_SQL
SELECT DISTINCT MONTH(o.date) AS month
FROM lineItems l
INNER JOIN orders o ON l.orderID = o.orderID
INNER JOIN customers c ON o.customerID = c.customerID
WHERE (c.name = ?) AND (l.product = 'Talisker')
GROUP BY o.orderID, o.date, c.NAME
HAVING (SUM(l.cost) > 5000)
END_SQL
result = []
$dbh.select_all(sql, customerID) {|row| result << row['month']}
return result
end
Although I've referred to this as a complex query, it's only complex in comparison to the simple select and where clause queries of the earlier examples. SQL queries can get far more complicated than this one, although many application developers would shy away from even a query as minimally complex as this.
Looking at Performance
One of the first questions people consider with this kind of thing is performance. Personally I don't think performance should be the first question. My philosophy is that most of the time you should focus on writing maintainable code. Then use a profiler to identify hot spots and then replace only those hot spots with faster but less clear code. The main reason I do this is because in most systems only a very small proportion of the code is actually performance critical, and it's much easier to improve the performance of well factored maintainable code.
But in any case, let's consider the performance trade-offs first. On my little laptop the complex SQL query performs twenty times faster than the other two approaches. Now you cannot form any conclusions about the the performance of a data center server from an svelte but elderly laptop, but I would be surprised if the complex query would be less than an order of magnitude faster than the in memory approaches.
Part of the reason for this is that the in-memory approaches are written in a way that is very inefficient in terms of SQL queries. As I've pointed out in their descriptions, each one issues a SQL query for every order that a customer has - and my test database has a thousand orders for each customer.
We can reduce this load considerably by rewriting the in-memory programs to use a single SQL query. I'll start with the transaction script.
SQL = <<-END_SQL
SELECT * from orders o
INNER JOIN lineItems li ON li.orderID = o.orderID
INNER JOIN customers c ON c.customerID = o.customerID
WHERE c.name = ?
END_SQL
def cuillen_months customer_name
orders = {}
$dbh.select_all(SQL, customer_name) do |row|
process_row(row, orders)
end
result = []
orders.each_value do |o|
result << o.date.month if o.talisker_cost > 5000.dollars
end
return result.uniq
end
def process_row row, orders
orderID = row['orderID']
orders[orderID] = Order.new(row['date']) unless orders[orderID]
if 'Talisker' == row['product']
orders[orderID].talisker_cost += row['cost'].dollars
end
end
class Order
attr_accessor :date, :talisker_cost
def initialize date
@date, @talisker_cost = date, 0.dollars
end
end
This is a pretty big change to the transaction script, but it speeds things up by a factor of three.
I can do a similar trick with the domain model. Here we see an advantage of the domain model's more complex structure. I only need to modify the loading method, the business logic in the domain objects themselves does not need to change.
class CustomerMapper
SQL = <<-END_SQL
SELECT c.customerID,
c.NAME as NAME,
o.orderID,
o.date as date,
li.lineNumber as lineNumber,
li.product as product,
li.cost as cost
FROM customers c
INNER JOIN orders o ON o.customerID = c.customerID
INNER JOIN lineItems li ON o.orderID = li.orderID
WHERE c.name = ?
END_SQL
def find name
result = nil
om = OrderMapper.new
lm = LineItemMapper.new
$dbh.execute (SQL, name) do |sth|
sth.each do |row|
result = load(row) if result == nil
unless result.order(row['orderID'])
result.add_order(om.load(row))
end
result.order(row['orderID']).add_line_item(lm.load(row))
end
end
return result
end
(I'm telling a little lie when I say that I don't need to modify the domain objects. In order to get decent performance I needed to change the data structure of customer so that the orders were held in a hash rather than an array. But again, it was a very self-contained change, and didn't impact the code for determining the discount.)
There's a few points here. Firstly it's worth remembering that in-memory code can often by boosted by more intelligent queries. It's always worth looking to see if you are calling the database multiple times, and if there's a way to do it with a single call instead. This is particularly easy to overlook when you have a domain model because people usually think of class at a time access. (I've even seen cases where people load a single row at a time, but that pathological behavior is relatively rare.)
One of the biggest differences between the transaction script and the domain model is the impact of changing the query structure. For the transaction script, it pretty much means altering the entire script. Furthermore if there were many domain logic scripts using similar data, each one would have to be changed. With the domain model you alter a nicely separated section of the code and the domain logic itself doesn't have to change. This is a big deal if you have a lot of domain logic. This is the general trade off between transaction scripts and domain logic - there's an initial cost in complexity of database access for a domain logic which pays off iff you have a lot of domain logic.
But even with the multi-table query, the in-memory approaches are still not as fast as the complex SQL - by a factor of 6 in my case. This makes sense: the complex SQL does the selection and summing of costs in the database and only has to schlep a handful of values back to the client, while the in-memory approach needs to schlep five thousand rows of data back to the client.
Performance isn't the only factor in deciding what route to go, but it's often a concluding one. If you have a hot spot that you absolutely need to improve, then other factors come second. As a result many fans of domain models follow the system of doing things in-memory as a default, and using things like complex queries for hot spots only when they have to.
It's also worth pointing out that this example is one that plays to a database's strengths. Many queries don't have the strong elements of selection and aggregation that this one does, and won't show such a performance change. In addition multi-user scenarios often cause surprising changes to the way queries behave, so real profiling has to be done under a realistic multi-user load. You may find that locking issues outweigh anything you can get by faster individual queries.
Modifiability
For any long-lived enterprise application, you can be sure of one thing - it's going to change a lot. As a result you have to ensure that the system is organized in such a way that's easy to change. Modifiability is probably the main reason why people put business logic in memory.
SQL can do many things, but there limits to its capabilities. Some things that it can do require quite clever coding, as a browse of algorithms for the median of a dataset displays. Others are impossible to make without resorting to non-standard extensions, which is a problem if you want portability.
Often you want to run business logic before you write data into the database, particularly if you working on some pending information. Loading into a database can be problematic because often you want pending session data to be isolated from fully accepted data. This session data often shouldn't be subject to the same validation rules as fully accepted data.
Understandability
SQL is often seen as a special language, one that's not something that application developers should need to deal with. Indeed many database frameworks like to say how by using them you avoid needing to deal with SQL. I've always found that a somewhat strange argument, since I've always been fairly comfortable with moderately complex SQL. However many developers find SQL harder to deal with than traditional languages, and a number of SQL idioms are hard to fathom to all but SQL experts.
A good test for you is to look at the three solutions, and see which makes the domain logic easiest to follow and thus modify. I find the domain model version, which is just a couple of methods, the easiest to follow; in large part because the data access is separated out. Next I prefer the SQL version over the in-memory transaction script. But I'm sure other readers would have other preferences.
If most of a team is less comfortable with SQL, then that's a reason to keep domain logic away from SQL. (It's also a reason to consider training more people in SQL - at least to an intermediate level.) This is one of those situations where you have to take into account the make up of your team - people do affect architectural decisions.
Avoiding Duplication
One of the simplest, yet most powerful, design principles I've come across is avoiding duplication - formulated by the Pragmatic Programmers as the DRY (Don't Repeat Yourself) principle.
To think about the DRY principle for this case, let's consider another requirement for this application - a list of orders for a customer on a particular month showing the orderID, date, total cost and whether this order is a qualifying order for the Cuillen plan. All of this sorted by the total cost.
Using the domain object approach to handling this query we need to add a method to the order to calculate the total cost.
class Order...
def total_cost
result = 0.dollars
line_items.each {|line| result += line.cost}
return result
end
With that in place then it's easy to print the order list
class Customer
def order_list month
result = ''
selected_orders = orders.select {|o| month == o.date.month}
selected_orders.sort! {|o1, o2| o2.total_cost <=> o1.total_cost}
selected_orders.each do |o|
result << sprintf("%10d %20s %10s %3s\n",
o.db_id, o.date, o.total_cost, o.discount?)
end
return result
end
Defining the same query using a single SQL statement requires a correlated sub-query - which some people find daunting.
def order_list customerName, month
sql = <<-END_SQL
SELECT o.orderID, o.date, sum(li.cost) as totalCost,
CASE WHEN
(SELECT SUM(li.cost)
FROM lineitems li
WHERE li.product = 'Talisker'
AND o.orderID = li.orderID) > 5000
THEN 'Y'
ELSE 'N'
END AS isCuillen
FROM dbo.CUSTOMERS c
INNER JOIN dbo.orders o ON c.customerID = o.customerID
INNER JOIN lineItems li ON o.orderID = li.orderID
WHERE (c.name = ?)
AND (MONTH(o.date) = ?)
GROUP by o.orderID, o.date
ORDER BY totalCost desc
END_SQL
result = ""
$dbh.select_all(sql, customerName, month) do |row|
result << sprintf("%10d %20s %10s %3s\n",
row['orderID'],
row['date'],
row['totalCost'],
row['isCuillen'])
end
return result
end
Different people will differ about which of these two is the easiest to understand. But the issue I'm chewing on here is that of duplication. This query duplicates logic from the original query that just gives the months. The domain object approach does not have this duplication - should I wish to change the definition for the cuillen plan, all I have to do is to alter the definition of cuillen? and all uses are updated.
Now it isn't fair to trash SQL on the duplication issue - because you can avoid duplication in the rich SQL approach as well. The trick, as database aficionados must be gasping to point out, is to use a view.
I can define a view, for simplicity called Orders2 based on the following query.
SELECT TOP 100 PERCENT
o.orderID, c.name, c.customerID, o.date,
SUM(li.cost) AS totalCost,
CASE WHEN
(SELECT SUM(li2.cost)
FROM lineitems li2
WHERE li2.product = 'Talisker'
AND o.orderID = li2.orderID) > 5000
THEN 'Y'
ELSE 'N'
END AS isCuillen
FROM dbo.orders o
INNER JOIN dbo.lineItems li ON o.orderID = li.orderID
INNER JOIN dbo.CUSTOMERS c ON o.customerID = c.customerID
GROUP BY o.orderID, c.name, c.customerID, o.date
ORDER BY totalCost DESC
I can now use this view for both getting the months and for producing the order list
def cuillen_months_view customerID
sql = "SELECT DISTINCT month(date) FROM orders2 WHERE name = ? AND isCuillen = 'Y'"
result = []
$dbh.select_all(sql, customerID) {|row| result << row[0]}
return result
end
def order_list_from_view customerName, month
result = ''
sql = "SELECT * FROM Orders2 WHERE name = ? AND month(date) = ?"
$dbh.select_all(SQL, customerName, month) do |row|
result << sprintf("%10d %10s %10s\n",
row['orderID'],
row['date'],
row['isCuillen'])
end
return result
end
The view simplifies both the queries and puts the key business logic into a single place.
It seems that people rarely discuss using views like this to avoid duplication. Books I've seen on SQL don't seem to discuss doing this kind of thing. In some environments this is difficult because of the organizational and cultural splits between database and application developers. Often application developers aren't allowed to define views and database developers form a bottleneck that discourages application developers from getting views like this done. DBAs may even refuse to build views that are only needed by a single application. But my opinion is that SQL deserves as much care to design as anything else.
Encapsulation
Encapsulation is a well known principle of object-oriented design, and it's one that I think applies well to general software design. Essentially it says that a program should be divided into modules that hide data structures behind an interface of procedure calls. The purpose of this is to allow you to change the underlying data structure without causing a large ripple effect across the system.
In this case, the question is how can we encapsulate the database? A good encapsulation scheme would allow us to alter the database schema without causing a painful round of editing across an application.
For enterprise applications, a common form of encapsulation is a layering, where we strive to separate domain logic from data source logic. That way the code that works on business logic isn't affected when we alter the database design.
The domain model version is a good example of this kind of encapsulation. The business logic works only on in-memory objects. How the data gets there is completely separated. The transaction script approach has some database encapsulation through the find methods, although the database structure is more revealed through the returning result sets.
In an application world, you achieve encapsulation through an API of procedures and objects. The SQL equivalent is to use views. If you change a table you can create a view which supports the old table. The biggest issue here is with updates, which often can't be done properly with views. This is why many shops wrap all DML with stored procedures.
Encapsulation is about more than just supporting changes to views. It's also about the difference between accessing data and defining business logic. With SQL the two can easily be blurred, yet you can still make some form of separation.
For an example, consider the view I defined above to avoid duplication in queries. That view is a single view which could be split along the lines of a data source and business logic separation. A data source view would look something like this
SELECT o.orderID, o.date, c.customerID, c.name,
SUM(li.cost) AS total_cost,
(SELECT SUM(li2.cost)
FROM lineitems li2
WHERE li2.product = 'Talisker' AND o.orderID =li2.orderID
) AS taliskerCost
FROM dbo.CUSTOMERS c
INNER JOIN dbo.orders o ON c.customerID = o.customerID
INNER JOIN dbo.lineItems li ON li.orderID = o.orderID
GROUP BY o.orderID, o.date, c.customerID, c.name
We can then use this view in other views that focus more on domain logic. Here's one that indicates the Cuillen eligibility
SELECT orderID, date, customerID, name, total_cost,
CASE WHEN taliskerCost > 5000 THEN 'Y' ELSE 'N' END AS isCuillen
FROM dbo.OrdersTal
This kind of thinking can also be applied to cases where we're loading data into a domain model. Earlier on I talked about how performance issues with a domain model could be dealt with by taking the entire query for cuillen months and substituting it with a single SQL query. Another approach would be to use the above data source view. This would allow us to keep a higher performance while still keeping the domain logic in a domain model. The line items would only be loaded in if necessary using a Lazy Load, but suitable summary information could be brought in via the view.
Using views, or indeed stored procedures, provides encapsulation only up to a point. In many enterprise applications data comes from multiple sources, not just multiple relational databases, but also legacy systems, other applications, and files. Indeed the growth of XML will probably see more data coming from flat files shared via networks. In this case full encapsulation really can only be done by a layer within the application code, which further implies that domain logic should also sit in memory.
Database Portability
One reason why many developers shy away from complex SQL is the issue of database portability. After all the promise of SQL is that it allows you to use the same standard SQL on a bevy of database platforms, allowing to change database vendors easily
In reality that's always been a bit of a fudge. In practice SQL is mostly standard but with all sort of little places to trip you up. With care, however, you can create SQL that isn't too painful to shift between database servers. But to do this you lose a lot of capabilities.
The decision about database portability ends up being particular to your project. These days it's much less of an issue than it used to be. The database market has shaken out so most places fall into one of the three major camps. Corporations often have strong commitments to whichever camp they are in. If you consider that changing databases is very unlikely due to this kind of investment, you might as well start taking advantage of the special features your database provides.
Some people still need portability, such as people who provide products that can be installed and interfaced with multiple databases. In this case there is a stronger argument against putting logic into SQL since you have to be so careful about which parts of SQL you can safely use.
Testability
Testability isn't a topic that's tended to come up enough in discussions about design. One of the benefits of Test Driven Development (TDD) is that it's rekindled the notion that testability is a vital part of design.
Common practice in SQL seems to not test. Indeed it's not uncommon to find essential views and stored procedures not even held in configuration management tools. Yet it's certainly possible to have testable SQL. The popular xunit family has a number of tools that can be used for testing within a database environment. Evolutionary database techniques such as test databases can be used to provide a testable environment very similar to what TDD programmers enjoy.
The main area that can make a difference is performance. While direct SQL is often faster in production, it can be much faster to run tests on business logic in memory if the database interface is designed in such a way that you can replace the actual database connection with a Service Stub.
Summing Up
So far I've talked about the issues. Now it's time to draw conclusions. Fundamentally what you have to do is to consider the various issues I've talked about here, judge them by your biases, and decide which policy to take to using rich queries and putting domain logic in there.
The way I look at the picture, one of the most critical elements is whether your data comes from a single logical relational database, or is scattered across a mass of different, often non-SQL, sources. If it's scattered then you should build a data source layer in memory to encapsulate your data sources and keep your domain logic in memory. In this case the strengths of SQL as a language isn't an issue, because not all of your data is in SQL.
The situation becomes interesting when the vast majority of your data sits in a single logical database. In this case you have two primary issues to consider. One is the choice of programming language: SQL versus your application language. The other is where the code runs, SQL at the database, or in memory.
SQL makes some things easy, but other things more difficult. Some people find SQL easy to work with, others find it horribly cryptic. The teams personal comfort is a big issue here. I would suggest that if you go the route of putting a lot of logic in SQL, don't expect to be portable - use all of your vendors extensions and cheerfully bind yourself to their technology. If you want portability keep logic out of SQL.
So far I've talked about modifiability issues. I think these concerns should come first, but be trumped by any critical performance issues. If you use an in-memory approach and have hot-spots that can be solved by more powerful queries, then do that. I would suggest looking to see how much you can organize performance enhancing queries as data source queries, as I outlined above. That way you can minimize putting domain logic into the SQL.
Sunday, January 1, 2012
ActiveX Can't Create Object
Don't Panic!
Despite the mysterious appearance of this error message, you should find it pretty easy to solve. The error message itself can occur for one of four reasons (listed in order of likeliness):
You do not have a required TLB or ActiveX DLL/OCX file.
A TLB or ActiveX DLL/OCX needed by the project is present but not registered on your system.
The VB runtimes are an earlier version than the one you need to run the project.
A required TLB or ActiveX DLL/OCX file is corrupt.
To solve the error is a process of elimination. The first and most important step is to make sure you know what the dependencies are for the project.
Know Your Dependencies
This site lists all the dependencies for a project at the top of the sample in the section Before You Begin. Currently, this information is not always included in the zips so I strongly recommend that you save a copy of the HTML page from which you download a project from as well as downloading the project.
Here is a sample dependency list:
Before you Begin
These projects require the SSubTmr.DLL component. Make sure you have loaded and registered this before trying any project.
This tells you which components you must have and any registration requirements for them; in this case you must have SSubTmr.DLL on your system and it must have been registered. If you try to run the executable with the project before you have done this, the executable will fail at start up with Error 429. If you try to run the project code in VB, it will fail as soon as you try to create the object. With control projects, this is whenever you show the form (whether at run-time or design-time), and with DLL projects this is whenever the first method is called on the DLL.
Tip Download and Register SSubTmr.DLL first
Almost all of the samples on this site need SSubTmr.DLL. This DLL is the library I use to get consistent and reliable subclassing to work in VB. Although VB5 and 6 allow you to write subclassing code directly into your project, it is difficult, error-prone and makes your code very difficult to debug. I isolated the code into this DLL to make things more managable.
If you download and register this file on your system before trying anything else, you'll almost certainly have an easier time! Don't forget either to include this file and mark it for registration in any setup kit you write if you include vbAccelerator controls.
Registering ActiveX DLLs and OCXs
There are various ways of registering a TLB or ActiveX DLL/OCX on your system, all of which ultimately do the same thing, which is to call the DLLRegisterServer method exposed by all in-process ActiveX components.
The methods are:
Use VB as a registration tool.
Run Regsvr32.exe.
Call DLLRegisterServer from your own code.
1. Using VB as a registration tool.
The dialog boxes you get when you choose Project-Components (Ctrl-T) for controls and Project-References for DLLs both allow you to register components automatically. Choose the appropriate box, click Browse... and locate the OCX, DLL or TLB. Click OK. The component will be registered. Note that you should do this before you try to load a project which requires one of these components.
Note: I have discovered that VB fails to register TLBs correctly through the Project-References dialog. Use the vbAccelerator TLB Registration Utility instead if you use Type Libraries frequently.
2. Run Regsvr32.exe
Regsvr32.exe is a small executable provided with Win95 and NT systems which calls DLLRegisterServer on a specified file. To use it, just click Start-Run, type regsvr32 and then drag the file you want to register from Explorer onto the Start-Run box.
Click OK to do the registration. If it succeeds, there will be a message box saying registration succeeded, otherwise the message box will tell you it failed with some uninterpretable COM error code. If it fails, you have a bad VB runtime or a corrupt file, or you have got the file name wrong.
Regsvr32 has a number of command line options which let you control what it does. By default it registers a control or DLL and gives a message box saying what it has done. The following command options let you modify this behaviour:
/u - Unregister server.
/s - Silent; display no message boxes
/c - Console output
You can use these options when writing simple install scripts in batch files.
3. Call DLLRegisterServer in code
The code for the VB Setup Wizard shows you how to call DLLRegisterServer yourself, albeit using the DLL supplied with the SetupKit (VB5STKIT.DLL for VB5). Search for DLLSelfRegister in the code to see how its done.
Registering ActiveX EXEs
You can register ActiveX EXEs on your system either using VB as registration tool (as described above) or by using the little documented command line switch /REGSERVER (not case-sensitive) when you run the executable.
Registering Type Libraries (TLB)
You can register TLBs either by using VB as a registration tool (as described above) or by using the VB TLB registration utility, which comes with complete source code.
If You Can't Register a File
First thing is to check the VB5 run-time files to see if you have the right version. If this reveals the VB runtime version is ok, then you may have a corrupt copy the file itself. Download a fresh copy and try it again. If you still don't have any success, then there is something seriously wrong, and perhaps its time to perform that rebuild you had been looking forward to for so long :)
Conclusion
By following these steps you should have no problem getting any code to run off this site. Hope it helps!
Wednesday, December 7, 2011
Amazon EC2 + Tesseract + OCR = Thank You!
There is a default web service setup with params:
img: uri to the jpg image that you want to transform
callback: used for crossdomain services
format: deafults to json but you can also supply txt to get just raw text
To build a machine you can follow these steps or if you are interested in the image let us know and I will contact you with more information.
sudo yum -y update
sudo yum -y install libtiff libtiff-devel libjpeg-devel libpng-devel gcc gcc-c++ libtool
cd /tmp/
sudo wget http://www.leptonica.org/source/leptonlib-1.67.tar.gz
sudo gunzip leptonlib-1.67.tar.gz
sudo tar -xvf leptonlib-1.67.tar
cd leptonlib-1.67/
sudo ./configure
sudo make
=== WAIT 10 min ===
sudo make install
cd /tmp/
sudo wget http://tesseract-ocr.googlecode.com/files/tesseract-3.00.tar.gz
sudo gunzip tesseract-3.00.tar.gz
sudo tar -xvf tesseract-3.00.tar
cd tesseract-3.00/
sudo ./runautoconf
sudo ./configure
sudo make
=== WAIT 20 min ===
sudo make install
#===================
#Install English Data
#===================
cd /usr/local/share/tessdata
sudo wget http://tesseract-ocr.googlecode.com/files/eng.traineddata.gz
sudo gzip -d eng.traineddata.gz
=====================
Additonal Tools:
=====================
sudo yum -y install httpd php
sudo chkconfig httpd on
sudo service httpd start
cd /var/www/html/
sudo wget http://tools.silverbiology.com/tesseract/index.txt
sudo mv index.txt index.php
sudo mkdir tmp
sudo chown apache:apache tmp
TEST:
your-machine-address.amazonaws.com/?img=http://www.biosurvey.ou.edu/bebb/imgs/BigLabel.jpg
/?img=http://www.anbg.gov.au/bryophyte/illustrations/flecker-macro.jpg&format=txt
Sample results from Image:
{
success: true
, img: http://www.biosurvey.ou.edu/bebb/imgs/BigLabel.jpg
, value: "PLANTS OF OKLAHOMA ROBERT BEBB HERBARIUM The Umversuly ol oklahoma Oklahoma County Scrophulariaoeae Penslemon oklahomensis Penn. SE Comer ol Tinker AFB. T11N RZW Sec. 26. Topography: rolling upland. Habitat: Mixed-Grass Prairie. Herbaceous perennial, 2-3 dm (all. Flowers while. F L Johnson TNK017 4 May |994 r»~n.~»¢y¢v»~~r~un»»,a|».¢»qus.-M, "
}
Saturday, November 19, 2011
A Selenium CaptureNetworkTraffic Example in Java 2
When I learned about Selenium’s ability to capture network traffic I was really excited. This opened up a whole new world of testing possibilities. I could capture the Ajax requests made to the server and check them for validity. When I visit pages I can check the web analytics messages sent back and check their correctness. So this post explains a little about how to use CaptureNetworkTraffic.
I found two blog posts useful when learning about capturenetworktraffic:
Testing Nexus with Selenium: A lesson in complex UI testing (Part 4) by Brian Fox
Automated Web/HTTP Profiler with Selenium-RC and Python by Corey Goldberg
Corey has an open source tool which uses Selenium to provide some profiling stats for web visits.
If you would like to learn Selenium but have trouble following the examples here, then you might want to have a look at my book "Selenium Simplified" which provides a tutorial approach to learning Selenium using Java - no programming experience required.
A few months ago, I was looking for a proxy server that I could automate alongside my Selenium tests. I did a lot of web searches but found nothing suitable. And it never occurred to me that Selenium had this functionality out of the box until I found Corey’s post.
Basically, you start a Selenium session with:
selenium.start("captureNetworkTraffic=true");
And then, after a few requests you can get the dump of the html traffic as a string by issuing:
String trafficOutput = selenium.captureNetworkTraffic("json");
Simple. (you can use “xml”, “json” or “plain”)
I use the json format because when I returned it in xml some of the urls that returned were the wrong format. So in Java this means I use the gson library to parse json.
And when I run this conversion of Corey’s profiler I see the following output from visiting the EvilTester.com homepage:
Warning you may get a concurrent modification exception reported when running the test. If this happens run it again. On some machines this happens more often than others and might seriously impact your ability to use this great function :( http://jira.openqa.org/browse/SEL-713
--------------------------------
results for http://www.eviltester.com
content size: 120617 kb
http requests: 22
status 200: 21
status 403: 1
file extensions: (count, size)
jpg: 4, 9.365000
png: 2, 1.969000
js: 4, 30.733000
ico: 1, 1.244000
unknown: 8, 53.546000
gif: 2, 16.319000
css: 1, 7.441000
http timing detail: (status, method, url, size(bytes), time(ms))
200, HEAD, http://www.eviltester.com/, 0, 406
200, GET, http://www.eviltester.com/, 30052, 641
...
To learn how to use this functionality you could read the source code to Corey’s tool, in Python. Or if you prefer Java you can follow the source below. I have done a quick, partial conversion of Corey’s tool in Java to illustrate how to use Gson and captureNetworkTraffic.
You can download the full source-code for this here.
Prerequisites to using this source-code:
You need to download Google-gson and add this lib to your project.
Also, since I have illustrated the basic principles in a @Test you will need to add either JUnit 4 or TestNG.
You also need to add selenium-server.jar to your project since we start Selenium automatically in this example
When you issue the selenium.captureNetworkTraffic(“json”) you receive a json string which has a collection of HTML Response Messages, e.g.
[{
statusCode: 200,
method: 'HEAD',
url: 'http://www.eviltester.com/',
bytes: 0,
start: '2010-05-26T13:33:37.048+0100',
end: '2010-05-26T13:33:37.314+0100',
timeInMillis: 266,
requestHeaders:[{
name: 'Host',
value: 'www.eviltester.com'
},{..}],
...
}]
When I parse this with gson
Gson gson = new Gson();
Type collectionOfHTMLRequestsType =
new TypeToken
Collection
gson.fromJson(trafficOutput, collectionOfHTMLRequestsType);
Gson will automatically build a collection of objects for me.
I created two objects to help with my Gson parsing:
HTMLRequestFromSelenium.java
package com.eviltester.captureNetworkTraffic;
import java.util.List;
public class HTMLRequestFromSelenium {
public int statusCode;
public String method;
public String url;
public int bytes;
public String start;
public String end;
public int timeInMillis;
public List requestHeaders;
}
and ValuePair.java
package com.eviltester.captureNetworkTraffic;
public class ValuePair {
private String name;
private String value;
}
Gson is well covered by the following articles
http://sites.google.com/site/gson/gson-user-guide
http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://www.softwarepassion.com/android-series-parsing-json-data-with-gson/
So this is my SeleniumTrafficAnalyserExampleTest.java where the bulk of the work is done. Commented to explain the basics.
package com.eviltester.captureNetworkTraffic;
import static org.junit.Assert.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;
import com.google.gson.Gson;
import com.google.gson.Gson.*;
import com.google.gson.reflect.*;
import com.thoughtworks.selenium.DefaultSelenium;
public class SeleniumTrafficAnalyserExampleTest {
@Test
public void testProfileEvilTester() throws Exception{
// Start the Selenium Server
SeleniumServer srvr = new SeleniumServer();
srvr.start();
// Create a Selenium Session with captureNetworkTraffic ready
String site = "http://www.eviltester.com";
DefaultSelenium selenium = new DefaultSelenium("localhost", 4444, "*firefox", site);
selenium.start("captureNetworkTraffic=true");
// open a page to get the traffic
selenium.open("/");
// dump the traffic into a variable in Json format
String trafficOutput = selenium.captureNetworkTraffic("json");
System.out.println(trafficOutput);
// parse the json using Gson
Gson gson = new Gson();
Type collectionOfHTMLRequestsType =
new TypeToken
Collection
gson.fromJson(trafficOutput, collectionOfHTMLRequestsType);
// get ready to analyse the traffic
TrafficAnalyser ta = new TrafficAnalyser(seleniumRequests);
// this is pretty much copied from Corey's python example
int num_requests = ta.get_num_requests();
int total_size = ta.get_content_size();
HashMap
HashMap
System.out.println("\n\n--------------------------------");
System.out.println(String.format("results for %s",site));
System.out.println(String.format("content size: %d kb",total_size));
System.out.println(String.format("http requests: %d",num_requests));
Iterator
while ( statusIterator.hasNext ( ) )
{
int key = statusIterator.next();
System.out.println(String.format("status %d: %d", key, status_map.get(key)));
}
System.out.println("\nfile extensions: (count, size)");
Iterator
while ( extensionIterator.hasNext ( ) )
{
String key = extensionIterator.next();
System.out.println(String.format("%s: %d, %f", key,
file_extension_map.get(key)[0],file_extension_map.get(key)[1]));
}
System.out.println("\nhttp timing detail: (status, method, url, size(bytes), time(ms))");
for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium) iterator.next();
//totalContentSize += hr.bytes;
System.out.println(String.format("%d, %s, %s, %d, %d",
hr.statusCode, hr.method, hr.url, hr.bytes, hr.timeInMillis));
}
// close everything down
selenium.close();
selenium.stop();
srvr.stop();
}
}
Then the helper class TrafficAnalyser.java
package com.eviltester.captureNetworkTraffic;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
public class TrafficAnalyser {
private Collection
public TrafficAnalyser(Collection
this.seleniumRequests = seleniumRequests;
}
public int get_num_requests() {
return seleniumRequests.size();
}
public int get_content_size() {
int totalContentSize = 0;
for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium) iterator.next();
totalContentSize += hr.bytes;
}
return totalContentSize;
}
public HashMap
HashMap
for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium) iterator.next();
if(statusCodes.containsKey(hr.statusCode)){
statusCodes.put(hr.statusCode, statusCodes.get(hr.statusCode)+1);
}else{
statusCodes.put(hr.statusCode, 1);
}
}
return statusCodes;
}
public HashMap get_file_extension_stats() {
HashMap
for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium) iterator.next();
URL url = null;
try {
url = new URL(hr.url);
String file_extension;
double size = hr.bytes/1000.0;
file_extension="";
String doc = url.getPath();
if(doc.contains("."))
file_extension = doc.substring(doc.indexOf(".")+1).trim();
if(file_extension.compareTo("")==0)
file_extension = "unknown";
if(extensions.containsKey(file_extension)){
Object[] stats = extensions.get(file_extension);
stats[0] = (Integer)stats[0] +1;
stats[1] = (Double)stats[1] + size;
extensions.put(file_extension, stats);
}else{
Object[] stats = new Object[2];
stats[0] = 1;
stats[1] = size;
extensions.put(file_extension, stats);
}
} catch (MalformedURLException e) {
}
}
return extensions;
}
}
Hopefully this gives a small overview of the capturenetworktraffic functionality in Selenium.
Related Reading:
http://coreygoldberg.blogspot.com/2009/10/automated-webhttp-profiler-with.html
http://www.sonatype.com/people/2009/10/selenium-part-4/
http://selenium-profiler.googlecode.com/
http://code.google.com/p/selenium-profiler/source/browse/trunk/web_profiler.py
http://stackoverflow.com/questions/2354827/checking-http-status-code-in-selenium
http://testautomationblog.com/tag/capture-network-traffic/
http://groups.google.com/group/selenium-users/browse_thread/thread/85208a5db7609722/8e95d5ec813d4844?lnk=gst&q=captureNetworkTraffic#8e95d5ec813d4844
If you would like to learn Selenium but have trouble following the examples here, then you might want to have a look at my book "Selenium Simplified" which provides a tutorial approach to learning Selenium using Java - no programming experience required.
Sunday, October 30, 2011
Selenium XPath Tutorial
Thu 18 Sep 2008
In the last tutorial we learnt how to create your first basic script by recording and replaying in the IDE. We are now going to learn how to work with XPathes in your scripts
XPath is a really good way to navigate your site when there are no IDs on elements that you need to work with or is near the element you want to work with.
Note: Web browsers were never designed to handle large amounts of XPath so this means that your scripts may run slowly. You will notice this especially in Internet Explorer.
Start the tutorial by creating a script similar to the one in the last script. Only create a script for the first set of elements on this page. You will be working on the other elements later. I have made a number of programming faux pas which you need take account of in your script.
- Enter numbers into each of the text boxes and then click on one of the buttons Value 1Value 2Total=
- I have created a basic version of what a script should look like here. You will notice that instead of the click targets having a nice ID you have a very odd looking item like the following: //input[@value='divide'].
- Let's see about creating your own XPaths from whats on the pages. Selenium IDE has a very useful tool making sure that the XPath that you entered is on the screen. So we take the XPath for the divide button //input[@value='divide'] and put it in the target textbox of Selenium IDE and click on the find button.
When you click on the find button it will highlight the element as shown in the image above.
- You can specify, in a XPath any of the attributes that is in the element that you want. If you put //img[(@alt='Element Find Button')] into the IDE what element does it highlight? It will show the image that I put above.
- Now what if you had an image with no ID and a partially dynamic alt tag what would you put? My quick answer would be //img[contains(@alt,'Partial')]. This searches all the images on the page and looks for an Alt that contains "Partial". If you wanted to try the use it for this page try //img[contains(@alt,'Element')]. Selenium IDE would highlight the image above again. I am sure that you can guess by now how powerful that can become.
-
I have created the same elements again below and would like you to create another script to test the items at the top and the items at the bottom.
Value 1Value 2Total=
I have created an example here. My example will be different to yours and I will explain next why. XPath example 2
-
I have used different syntaxs in my script. Each of these is just to show you a different way of finding elements by using different kinds of syntax. There is one example where the target is defined by a number of attributes and another is defined by finding one element and then finding its sibling. Another reason for doing this is because the buttons at the top and the bottom are programmed exactly the same. It allows us to have unique identifiers for elements.
In my opinion, if an item hasn't been programmed properly, i.e., lacks an id attribute, it is best to code the Selenium test to find that item in relation to an item that *has* been programmed properly rather than to rely on meaningless indexes. This means that when reading through your script you are more likely to understand where //input[@id='BottomTotal']/following-sibling::input[contains(@value,'Add')] is compared to //li[6]/input[4]. This becomes more obvoius when you have a large number of tests in your test suite.
- We have now come to the end of this tutorial. There are a number of other items on this page that will produce a XPath for your script. Have a play and try different combinations. You can find very good examples of XPath syntax at W3C Schools. I hope that you found this tutorial very informative but if you ever find that your script is using a lot of XPath go back to the developers and remind them that it is good programming practise to put IDs on elements.
Hàng hóa ở khắp nơi
Các công ty sản xuất hàng tiêu dùng, hãy nhớ: Đây có thể là lúc dọn sạch đống lộn xộn.
Các nhà sản xuất và những người bán lẻ đã mở rộng các dịch vụ sản phẩm của họ với tỷ lệ chưa từng thấy trong thập kỷ qua, thường là bằng việc đưa ra những sản phẩm phổ biến và bán chúng với mọi kích cỡ, nhãn hàng, màu sắc, kết cấu và hương vị.
Một vài trong số các công ty này nghĩ rằng bằng việc làm ra mọi sản phẩm cho mọi người, họ có thể tăng doanh thu và ngăn chặn các đối thủ cạnh tranh tham gia vào thị trường. Những người khác lo ngại bỏ đi những sản phẩm đã tồn tại một thời gian – hay giảm số hàng bán – sẽ làm mất đi những khách hàng quan trọng. Và đôi khi, các nhà bán lẻ lớn yêu cầu nhà sản xuất tạo ra một phiên bản duy nhất của một sản phẩm dành riêng cho họ, để họ có thể tránh được sự so sánh trong khi mua hàng của khách hàng.
Nhưng thay vì gia tăng lợi nhuận, những chiến thuật này thường dẫn đến danh mục sản phẩm cồng kềnh, làm tăng chi, giảm hiệu quả của chuỗi cung ứng sản phẩm, gây hoang mang cho người tiêu dùng và dẫn đến việc thiếu những sản phẩm phổ biến.
Mặt khác, một danh mục sản phẩm gọn nhẹ hơn có thể mang lại rất nhiều lợi ích. Các giám đốc marketing có thể giám sát việc bán hàng, phát triển cạnh tranh và khủng hoảng tốt hơn bằng cách thu hồi lại sản phẩm. Các nhà sản xuất có thể cắt giảm chi phí chuyển đổi dây chuyền lắp ráp và khoản chi họ đưa ra cho các nhà bán lẻ để đảm bảo không gian trưng bày sản phẩm. Các nhà bán lẻ đưa ra một sự lựa chọn nhỏ hơn cho các sản phẩm tương tự, có ít nhà cung cấp hơn để quản lý, nhiều không gian trưng bày cho những hàng hóa bán chạy nhất, và ít khách hàng rời khỏi cửa hàng của họ trong tình trạng quá tải và không thể đưa ra quyết định.
Vì việc cắt bớt danh mục sản phẩm mà không làm mất đi những khách hàng và người tiêu dùng quan trọng có thể là một thử thách, dưới đây là vài gợi ý để làm cho đúng:
Đừng hỏi người tiêu dùng (về danh mục sản phẩm của bạn).
Nếu bạn hỏi người tiêu dùng họ có muốn sự đa dạng không, họ có thể nói ngay với bạn: Có. Trên hết, ai chẳng muốn có nhiều lựa chọn. Và việc người tiêu dùng vừa buồn bã vừa bực bội khi sản phẩm họ thích ngừng bán là điều bình thường.
Thế nên đừng viện đến việc hỏi khách hàng quá nhiều. Tốt hơn hết, hãy dựa vào số liệu thay vì một câu trả lời thường là theo cảm tính.
Hãy tập hợp thông tin từ hệ thống các điểm bán hàng và chương trình lòng trung thành, phân tích số liệu sản phẩm như doanh số bán hàng mỗi mét vuông, và tiến hành những thí nghiệm trên từng lĩnh vực để quyết định điều gì ảnh hưởng đến việc đưa ra một sự lựa chọn rộng rãi cho các sản phẩm tương tự trên tổng doanh thu với các loại sản phẩm nhất định.
Sử dụng các kết quả để nhận diện sản phẩm nào không tiêu thụ tốt, sản phẩm nào có doanh thu cao nhưng lợi nhuận thấp và/hoặc chi phí hàng tồn kho thực tế cao. Hãy xem xét mục tiêu để loại bỏ.
Phân loại hàng hóa theo tầng lớp
Một cách khác để nhận diện các hàng hóa có thể bị loại bỏ mà không làm ảnh hưởng đến việc kinh doanh của bạn là phân loại danh mục hàng hóa theo tầng lớp dựa trên thói quen của người tiêu dùng.
Trong khi có rất nhiều cách phân loại, một cuộc nghiên cứu trước đây miêu tả một công ty sản xuất đồ ăn nhanh đã chia sản phẩm của họ thành sản phẩm cốt lõi, sản phẩm thích hợp, sản phẩm theo mùa và ngày lễ, và sản phẩm phụ khác. Sản phẩm cốt lõi từng được sử dụng bởi 1/3 người tiêu dùng và được mỗi hộ gia đình tiêu thụ 2 lần mỗi năm. Nhóm này chiếm 20% số sản phẩm của công ty, nhưng chiếm 70% doanh số bán hàng. Ngược lại, nhóm sản phẩm thích hợp được mua không thường xuyên, đặc biệt là bởi những phân đoạn nhỏ của người tiêu dùng tại các thị trường địa lý tập trung. Những sản phẩm này chiếm 10% tổng sản phẩm của công ty và 10% doanh số bán hàng. Sản phẩm theo mùa và ngày lễ cũng chiếm 10% doanh thu, và được mua bởi 1/3 trên tổng số các hộ gia đình nhưng chỉ vào một lần trong năm. Cuối cùng, các sản phẩm phụ khác – được mua bởi sự thuận tiện thay vì yêu thích – chiếm 65% tổng sản phẩm nhưng chỉ 10% doanh số bán hàng.
Sự phân tích dẫn công ty đến việc giảm bớt số lượng những sản phẩm phụ và tập trung vào việc có thêm không gian trưng bày tại các cửa hàng đối với những sản phẩm được sử dụng nhiều nhất.
Tạo ra bộ phận rà soát và loại bỏ sản phẩm.
Hãy cân nhắc việc tạo ra một nhóm cắt giảm sản phẩm bao gồm những người trong lĩnh vực marketing, bán hàng, tài chính, sản xuất, R&D. Để họ gặp nhau thường kỳ để quyết định xem sản phẩm nào phải ngừng sản xuất.
Nhà sản xuất sản phẩm gia đình Clorox Co. cho biết họ có một đội liên chức năng làm việc suốt cả năm để đảm bảo các đơn vị kinh doanh khác nhau của công ty đang thêm vào những sản phẩm tạo ra giá trị và loại bỏ những sản phẩm không tạo giá trị. Kết quả là khoảng 80%-90% trong số các sản phẩm công ty bán đạt được khối lượng... và mục tiêu lợi nhuận.
Cũng có những nguy cơ trong việc cắt giảm những sản phẩm không hiệu quả một cách quá mạnh mẽ - tức là một sản phẩm bị loại bỏ có thể phá hoại mối quan hệ với khách hàng quan trọng Clorox cố gắng tránh cạm bẫy này bằng cách gặp gỡ các nhà bán lẻ để đảm bảo họ có danh mục sản phẩm thuận lợi nhất cả về nhãn hiệu lẫn kích cỡ với từng thể loại để phù hợp với nhu cầu của người tiêu dùng.
Giới hạn lựa chọn sản phẩm
Một cách khác để tránh cái bẫy tăng nhanh số lượng sản phẩm là đặt ra một giới hạn tuyệt đối cho số sản phẩm mà bạn đưa ra.
Trader Joe's, một chuỗi thực phẩm đặc sản tư nhân, tuyên bố trên website của họ rằng nếu như một sản phẩm "không thể hiện tầm quan trọng" trong các cửa hàng, nó sẽ bị bỏ đi để dành chỗ cho một sản phẩm khác có khả năng đó. Chiến lược tạo ra nhiều hàng hóa có liên quan hơn cho người tiêu dùng và doanh số bán hàng trên một foot vuông cao hơn.
Các nhà bán lẻ có được thành công lớn nhất với chiến lược này thường phục vụ cho những khách hàng sẵn lòng chấp nhận ít lựa chọn hơn như là một sự đánh đổi lấy mức giá thấp hơn.
Làm theo yêu cầu của khách hàng trên quy mô lớn
Một cách để cung cấp sự lựa chọn mà không cần tăng thêm số lượng sản phẩm là trải qua bước "Mass Customization" – một cách tiếp cận trong đó sản phẩm được tạo ra bởi người tiêu dùng đặt hàng.
Các nhà sản xuất có thành công lớn nhất với cách này là những người có sản phẩm được tạo ra từ các thành phần có thể được cấu thành bởi rất nhiều sự kết hợp. Nó đòi hỏi một hệ thống cho phép người tiêu dùng hiểu và giao tiếp với những nhu cầu riêng của họ, và nó dựa trên việc sản xuất linh hoạt để giữ mức giá thấp và thời gian tạo sản phẩm ngắn.
Dell Inc thường được trích dẫn như là một ví dụ về công ty sử dụng mass customization hiệu quả. Nó xây dựng cấu hình bộ nhớ của mỗi máy tính cá nhân, ổ cứng và card đồ họa sau khi khách đặt hàng. Dell có thể cung cấp hàng trăm kết hợp khác nhau của cấu hình máy tính với một vài thành phần khác nhau.
|
