Difference between Mocks and Stubs.
There are nowadays two terms that are used by the developers : 'stub' and 'mock'. As I found in
the article of Martin Fowler 'Mocks Aren't Stubs', he is using the vocabulary of Gerard
Meszaros's book, where there is the division into : 'dummy', 'fake', 'stub' and 'mock' points.
I'll metnion only what 'dummy' and 'fake' are, and I'll try to concentrate over 'mock' and
'stub'. So 'dummy' objects as Thesaurus says represents a copy, figure, form, model in its mean.
In reallity passing to developper language, the goal of dummy objects is to be passed, in this
sence the general use of dummy objects is to fill parameter lists. I should metion that 'dummy'
objects do not have their working implementation. If we are speaking about 'fake' objects, than
from the beginning we must emphasize that these type objects have their implementations, an
important point of distinguishing here is that 'fake' objects are not used for production, they
represent something like an alternate route, timesaving method. For example an SQLLite database
represents a 'fake' object.
In the following part of this article I'll try to concentrate on two important concepts: 'stub'
and 'mock'. Many often confuse these terms speaking about them as about the same thing. From the
conceptual point of view they both represent methodologies that share some common things. I
thinks there is also an historical motivation of the confusion between them: from the first
appeared the therm 'stub' and it was used for a long period of time, when in some communities
appeared and started to be used the them of 'mock'. On the first glance they are suitable to
accomplish the same things. I can caracterize a 'mock' as an imitation or make-believe, and a
'stub' as a dock. The 'mock' object request the behavior check, while 'stub' is for state check.
The 'mock' represents an object that englobes a specification of expectations for the calls it is
expected to receive, while 'stub' represents preserved answers to requests that are made during
the test ( as a rule, the 'stub' does not respond to smth else that's programmed especially for
the test).
We'll examine an example of using 'mock' and 'stub' in the same scenario and we'll get deeper
into discussion based on some code. So we have the situation that based on the number of users on
a portal, the owner of the portal receives an sms on his mobile phone to be informed about the
event. Let's assume that at 100.000 visitors he gets a message about this. We'll use Rhino Mocks
and NUnit for our testing purposes.
Class Msg - a simple CLR object that encapsulates the message to be send via SMS:
public class Msg
{
private string message;
public Msg(string message)
{
this.message = message;
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
}
Interface IServiceSMS contains the method Send() for sending the SMS:
using TheDiff.BusinessObjects;
namespace TheDiff.Interfaces
{
public interface IServiceSMS
{
bool Send(Msg msg);
}
}
Class for tests MockTests:
using Rhino.Mocks;
using NUnit.Framework;
using TheDiff.BusinessObjects;
using TheDiff.Interfaces;
namespace TheDiff
{
[TestFixture]
public class MockTests
{
private IServiceSMS serviceSMS;
[SetUp]
public void SetUp()
{
serviceSMS = MockRepository.GenerateMock
}
[Test]
public void Mocker()
{
var msg = new Msg("Online users are 100.000!");
serviceSMS.Expect(x => x.Send(msg)).Return(true);
var wasSent = serviceSMS.Send(msg);
Assert.IsTrue(wasSent);
serviceSMS.VerifyAllExpectations();
}
}
}
Class for tests StubTests:
using Rhino.Mocks;
using NUnit.Framework;
using TheDiff.BusinessObjects;
using TheDiff.Interfaces;
namespace TheDiff
{
[TestFixture]
public class StubTests
{
private MockRepository mocks;
private IServiceSMS serviceSMS;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
serviceSMS = mocks.Stub
}
[Test]
public void Stuber()
{
var msg = new Msg("Online users are 100.000!");
using (mocks.Record())
{
SetupResult.For(serviceSMS.Send(msg)).Return(true);
}
var wasSent = serviceSMS.Send(msg);
Assert.IsTrue(wasSent);
}
}
}
Best .NET ORM Tool
My Considerations
Until now I used some custom orm tool (written by me), it was working with stored procedures, because my idea is that the best optimization you may accomplish in sql code. But now as the project increased and its fonctionality has blow up, I realise that in the future must be used some more adapted orm for supporting Domain Model and Data Mapper, with wich can be used in a more simple fashion the concepts of Unit of Work, Repositories etc. I indeed fell the necessity to pass to this kind of aproach because Transaction Script approach that I used in conjuction with Data Mapping leads in hard maintenace problems when in enterprise application you have sophisticated workflows and transactions to be performed.
I spent some time searching through the existing ORM Mappers (commercial and not only), of course my idea was to find a free mapper, but if another commercial tool is more powerful in the sence that it offer more access in using the enterprise patterns and it's more flexible, than it can be used instead.
My decision was in favor of NHibernate. First of all it's ported from java environment and has proven its viability over the years and the multitude of serios projects based on it. Of course we can describe different pros and cons of using it, and other OPRMs such as SubSonic or LBLGEN. But in fact with some more or less effort the things are pretty well done with NHibernate. Second of all it's not as complicated as it seems at first glance, you'll discover that at first examples that you'll do with it. Third it offers very clean and separated approach to perform the necessary operations, I was excited of the granularity that it offers comparing to other similar tools.
I dislike the fact that more and more vendors try to make their ORMs more simple to use by not allowing the developper to dive into some subtle things that in the end lead to optimisations, that's crucial for serios applications. From my point of view the best approach are stored procedures, because you may fine tune their granularity as you wish, but from the maintenace point of view it's not the best solution. After this approach the best one will be this NHibernate. During surfing the web you can find different tests on the efficiency of this tool compared to other such as EntityFramework and LINQ. I can emphasize that in practically all cases NHibernate generates less sql code than those mentioned. NHibernate is the most closely to pure ADO.NET efficiency. That's why I recommend it.
Performance Tests
Next I'll show you the results of some tests:
The results of the tests several unusual. First, I ran the queries of each test in one set and looked at Query cost for each query, which is about the whole set.
In the first test, I got the following results:
Classic ADO.NET - 15%
LINQ 2 SQL = 48%
Entity Framework - 23%
Active Record (NHibernate) - 15%
The interesting thing here is that LINQ 2 SQL is indeed slowerthan the request performed by EntityFramework.
In the second test, I have a complex query with joins for LINQ 2 SQL:
Complex queries with joins - 24%
A set of simple queries - 76%
As you can see, one request has won, it's not surprising. However, in general, we can say that in terms of databases losses are not as lazy loading too long.
The third test was for EntityFramework:
Complex queries with joins - 19%
A set of simple queries - 71%
As you can see, the results are practically similar.
The forth test was for NHibernate:
Complex queries with joins - 8%
A set of simple queries - 92%
So now you can see by yourself and make some base ideas on how it is.
List of .NET ORM Tools
Next I'll give a list with good .NET ORM Tools, and you may compare them by yourself:
Domain Driven Design
I want to mention SharpArhitecture project. This represents a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate.
What I want here is to show some advantages/disadvantages and the points of interested that I faced up. So when analysing the possibilities that this code offers, I discovered that :
1) NHibernate validation is not suitable for a series of scenarious that mostly enterprise level applications require. Let's assume that we have the following scenario: there is the entity 'case' and this entity should be introduced (inserted) in our system by the worker with position 'Secretary'. The Secretary shoul introduce only the CaseName. Later the worker that is in position 'President' should alter the case and set the number.
public class Case
{
public virtual int Id { get { return id; } }
[NotEmpty, NotNull]
public virtual string CaseName { get ; set ; }
[Email]
public virtual string Email { get ; set ; }
[Min(20000, Message="The number should be greater than 20000!")]
public int Nr{ get ; set ; }
///...
}
In the scenario described above we better have also 2 validation scenarious. It's a simple case, but assume that when creating the record the number should be greater than 20000 and when updating the record the Number should be less 2000. Of course non-sense here, but assume it's a custom scenario. Than in this case the NHibernate validators are not suitable for accomplishing the validation.
I solved this issue by eliminationg the Nhibernate validators and pass to FluentValidation framework. Now I have different validator classes for different scenaious. It's more flexible approach and gives the power of more deep validation.
The advantage is considerable we don't tie the validation to the entity. We have in my case:
public class Case
{
public virtual int Id { get { return id; } }
public virtual string CaseName { get ; set ; }
public virtual string Email { get ; set ; }
public int Nr{ get ; set ; }
///...
}
and some classes for validation with structure similar to:
public class CaseValidator:AbstractValidator
{
public CaseValidator(){}
RuleFor(x=>x.CaseName).NotEmpty();
RuleFor(x=>x.CaseName).NotNull();
//..
}
that have different set of rules for validation that meets my custom scenarious.
What is C#? Windsor CT
C# is a new programming language introduced by Microsoft. This article, excerpted from Sams Teach Yourself C# in 21 Days provides an overview of what C# is and why it is important.
Have you heard of C# (pronounced See-Sharp)? It would not be unusual if you didn't know a lot about the language. Released to the public in June 2000, C# has not been around for very long.
C# is a new language created by Microsoft and submitted to the ECMA for standardization. This new language was created by a team of people at Microsoft led by Anders Hejlsberg . Interestingly, Hejlsberg is a Microsoft Distinguished Engineer who has created other products and languages, including Borland Turbo C++ and Borland Delphi. With C#, they focused on taking what was right about existing languages and adding improvements to make something better.
C# is a powerful and flexible programming language. Like all programming languages, it can be used to create a variety of applications. Your potential with C# is limited only by your imagination. The language does not place constraints on what you can do. C# has already been used for projects as diverse as dynamic Web sites, development tools, and even compilers.
C# was created as an object-oriented programming (OOP) language. Other programming languages include object-oriented features, but very few are fully object-oriented. In my book you can learn how C# compares to some of these other programming languages. My book also covers what it means to use an object-oriented language as well as the details of doing object-oriented programming with C#.
Why C#?
JavaScript ile resim boyutlandırma
Yaptığım projede büyük boyutlu resimler tasarımı kaydırıyordu.
Aşağıdaki kod sayfa tamamen yüklendikten sonra, Genişliği 800px den büyük olan resimleri 800px haline getiriyor. Yüksekliğinide buna göre ayarlıyor…
[tag light="true"]
window.onload= function() {
ims = document.images;
for (var i in ims) {
if (ims[i].width > 600) {
ims[i].width=600;
ims[i].height=Math.round(ims[i].height*600/ims[i].width);
}
}
}
[/tag]
Interface mi, Abstract mı?
Genellikle Nesneye Yönelik Programlamaya yeni başlayanların kafasındaki büyük soru işaretlerinden bazıları "Interface ile Abstract arasındaki farklar nelerdir?, Ne zaman Interface ne zaman Abstract sınıfları kullanmalıyız ? …." gibi sorulardır.
Acı ve komik bir anımdan bahsetmeden olmaz. Okulda Java hocama neden Interface kullanırız diye sorduğumda bana "Genelde pek kullanılmaz. Fakat benim daha önce çalıştığım bilmem ne işyerinde bi abi interface kullanarak yazılım geliştirirdi. Biz 2 haftada yapıyorsak o bir haftada bitirirdi" demişti. Tabi daha sonra interface,abstract gibi kavramların nesneye yönelik programlamada ne kadar önemli kavramalar olduğunu öğrenince neden o abinin 1 haftada bitirdiğini anladım.
Interface ve Abstract kavramları nesneye yönelik programlamanın en temel ve önemli kavramlarından biridir.Önceki yazılarımızda Interface nedir ne zaman kullanılır?, ve Abstract nedir ne zaman kullanılır? ile bu kavramların nerede nasıl kullanıldığına ayrı ayrı konular altında değinmiştik. Eğer okumadıysanız öncelikle eski yazıları okumanızı tavsiye ederim. Aslında iki yazıyıda dikkatlice okuduğunuzda hangi durumda hangisi kullanılabilir diye karar verebilirsiniz. Bu yazıda da genel bir özet yapıp bu kavramlar hakkında son düşüncelerimi ve kişisel tercihimi yazmak istedim.
Öncelikle daha önceki yazılarda Abstract sınıfların genellikle IS-A(dır,dir) ilişkilerinde,kalıtım(inheritance) özelliğini kullanarak kod tekrarını azaltmak için kullanıldığını söylemiştik. Interface sınıfların ise daha çok CAN-DO(yapabilir..) tarzı ilişkilerde değişen kavramları uygulamadan soyutlamak için kullanıldığını söylemiştik. Birde bu iki kavramın avantaj ve dezavantajlarına bakalım.Sonuçta Abstract bir sınıfın bütün metodlarını abstract yaparak onu da aynı bir interface gibide kullanabiliriz.
Öncelikle bence en büyük fark Abstract sınıfların tekli kalıtım(inheritance ) kullanması Interface sınıfların ise çoklu kalıtıma(multiple inheritance) izin vermesidir.Bildiğiniz gibi bir sınıfı başka bir sınıftan,ya da abstract bir sınıftan türettiğiniz zaman başka bir sınıftan daha türetme imkanınız olmuyor. Fakat interface sınıflarda durum daha farklı. Bir sınıfı istediğiniz kadar interfaceden türetebilirsiniz. Bu bakımdan interface sınıflar abstract sınıflardan oldukça daha esnek diyebiliriz. Fakat interface sınıflara baktığımızda abstract sınıflardan daha yavaş çalıştığı için hız bakımından devavantajı var diyebiliriz.
Şimdi hız mı esneklik mi diye bana soracak olursanız tabiki tercihim esneklikten yana olacaktır. Bu soruyu 2-3 sene önce sorsaydınız önce hız derdim büyük ihtimalle
Kendi kişisel tercihim olarak eğer soyutlamak istediğim yapıda ilişki CAN-DO ise ve hiç ortak kod yoksa sadece interface kullanırım. Fakat ortak kod içeriyorsa öncelikle bir interface(dikkat edin yine interface koyarım) koyup ardından ortak kodu kullanan bir abstract sınıf koyup onu o interfaceden türetir ve diğer sınıfları interface sınıfını kullanır hale getiririm.Burada interface i koymasakta olur fakat koymamın sebebi esnekliği arttırması ve özellikle Test Driven Development açısından Mock objelerin oluşturulması için interface kullanan sınıfların test edilmesinin çok daha kolay olması.Mock objelere ayrı bir konu başlığı altında değiniriz fazla uzatmayalım.
Eğer soyutlamak istediğim yapı IS-A ilişkisi ise sadece Abstract sınıf kullanırım. Abstract sınıfların sevmediğim yanı kalıtım(inheritance) diyebilirim.Kalıtım ilişkisi herzaman bağımlılığı(coupling) fazla olan bir ilişkidir. Yani türettiğiniz sınıfa tamamen bağımlı oluyorsunuz. Türettiğiniz sınıftaki herhangi bir değişiklik alt sınıfları etkiliyor. Fakat interface sınıflarda bu tarz bir problem daha az interface içindeki bir metodu değiştirmedikçe hiç bir sınıf bundan etkilenmiyor.Geliştirdiğiniz sınıflar tamamen plug-in mantığı ile interface sınıflar sayesinde hiç problemsiz değiştirilebiliyor. Bu yüzden kalıtıma her zaman şüpheyle yaklaşıyorum. Zaten Object OOP nin insanlar tarafından uzun yıllar kullanıldıktan sonra da aynı fikre varılmış. Kalıtımın bu problemli yapısı görüldüğü için daha sonra kalıtım yerine birleşim(Composition over Inheritance) kullanmak çoğu durumda tercih edilen bir yöntem.OOP için oldukça önemli olan bu konuyuda başka bir yazı konusu olarak ileriye bırakıyorum.
Konu ile ilgili yazıyı yazdığım gün konu ile alakalı çok güzel bir webcast e denk geldim. Buradan sizde izleyebilirsiniz. Konu Interface vs Abstract sınıflar. Burada konuşmacı benden daha katı olarak tamamen interface kullanılması gerektiğini savunuyor.Kısmen katılsamda bu şekile katı bir interface kullanımı her zaman doğru olmayabilir. Ayrıca konu ile ilgili daha derin bilgi edinmek için okumaya fırsat bulamadığım Interface Oriented Design kitabını okuyabilirsiniz. Ayrıca Wikide de kısa bir bilgi verilmiş(Interface Based Programming).
Bu konuda şuanda aklıma gelenler bu kadar.Dediğim gibi konu bir blog yazısına sığmayacak kadar detaylı. En azından biraz ışık tutabilmiştirim. Ne kadar örneği bol tutmaya çalışsamda kendiniz yazmadıkça projelerinizde kullanmadıkta biraz havada kalabilir. O yüzden eller klavyeye diyorum…
Inheritance (Kalıtım)
Diyelim ki elinizde A diye bir sınıf var. Ancak B diye bir sınıf daha oluşturmanız gerekiyor. Ancak bu B sınıfının içinde A sınıfındaki özellik ve metotların da bulunması gerekiyor. İşte bu durumda B sınıfını A sınıfından türetmeniz gerekir. Türetme kalıtım yoluyla olduğu için A sınıfının bütün üye elemanları B sınıfına adeta kopyalanır. Daha sonra B sınıfının kendine özel üye elemanlarını yazabiliriz. .Net kütüphanesindeki birçok sınıf birbirlerinden türetilmiştir. Örneğin temel veri türleri dediğimiz byte, int, uint, short, float ve bezerlerinin tamamı object sınıfından türetilmiştir. Bu sayede normalde object sınıfında bulunan ToString() metodunu bu yapı türünden nesnelerde de kullanabilirsiniz. Sınıflar türetilebilmesine rağmen yapılar türetilemez. Ancak bir sınıfın türetilmişinden yapı oluşturulabilir. C#'ta türetme şöyle yapılır:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kalitim
{
//Temel özelliklerimizin olduğu Motor ve Araba classlarında tekrar tanımalak yerine ortak bir class'da belirterek oradan kalıtıcağız özellikleri.Base Class özelliklerimizi yazıyoruz ve erişim belirleyici olarak public veriyoruz.Böylece özelliklerimizi ve metotlarımzı heryerden erişime açıyoruz.Kalıtılan sınıflarda sorunsuz bir şekilde kullanılabilecek.Fields'lerimize public değilde private yetkilendirseydik kesinlikle başka bir sınıf üzerinden erişmemiz mümkün olmayacaktı.
class Arac
{
public string _renk;
public byte _yolcuSayisi;
public byte _tekerSayisi;
public void TemelAracOzellikleriniGoster()
{
Console.WriteLine("Renk : " + _renk);
Console.WriteLine("Yolcu Sayısı : " + _yolcuSayisi);
Console.WriteLine("Teker Sayısı : " + _tekerSayisi);
}
}
//Yazmış olduğumuz temel Arac sınıfını daha sonra nesnelerimizden biri olan Motor classına kalıtıyoruz.Bunu yapmak için bulunduğumuz class adının yanına : koyduktan sonra kalıtmak istediğimiz yani temel sınıfın adını belirterek artık o özellikleri yeni sınıfımızda kullanıma açmış oluyoruz.
class Motor:Arac
{
public string _MotorClassi;
public void MotorTurGoster()
{
Console.WriteLine("Araç türü : " + _MotorClassi);
}
}
//Aynı şekilde burada da Motor class'ı gibi Araba classı oluşturup base class olan Arac classından kalıtıyoruz.
class Araba : Arac
{
public string _ArabaClassi;
public void ArabaTurGoster()
{
Console.WriteLine("Araç türü : " + _ArabaClassi);
}
}
class Program
{
static void Main(string[] args)
{
//Motor classından bir nesne yaratıyoruz.Motor classını Arac classından kalıttığımız için dikkat ederseniz Arac classındaki fields'lerede ulaşmış olup deger verebildiğimizi görmüşsünüzdür.MotorClass adında nesnemizi oluşturup tüm fields'lerine değerleri atadıktan sonra motor ve arac classındaki metotları çağırarak bilgileri ekrana yazmasını sağlıyoruz.
Motor motorClass = new Motor();
motorClass._MotorClassi = "Motosiklet";
motorClass._renk = "Mavi";
motorClass._tekerSayisi = 2;
motorClass._yolcuSayisi = 2;
motorClass.TemelAracOzellikleriniGoster();
motorClass.MotorTurGoster();
Console.WriteLine("--------------------------");
//Motor class'ında yaptığımız işlemlerin aynısı yapıpı Araba classından oluşturulmuş olan arabaClass nesnesinede değerleri atayıp iki classtaki metotları kullanarak ekranda görebiliriz.
Araba arabaClass = new Araba();
arabaClass._ArabaClassi = "Araba";
arabaClass._renk = "Siyah";
arabaClass._tekerSayisi = 4;
arabaClass._yolcuSayisi = 4;
arabaClass.TemelAracOzellikleriniGoster();
arabaClass.ArabaTurGoster();
Console.ReadLine();
}
}
}
Böylece diyelim ki Araba ve Motor sınıflarına yeni bir özellik ekleyeceğiz.Teker teker iki class'ada özellikleri eklemek yerine temel katılılan class olan Arac sınıfına özelliği eklersek zaman tasarrufu yapmış oluruz.Aynı işlemin tersi olan özellik silmek içinde düşünürsek ve 2 tane değilde 15-20 tane class'ımız olduğunu hesaba katarsak kalıtımın önemini anlamış oluruz
Bu makalede OOP prensiplerinden biri olan inheritance'yi inceledik.OOP'da 3 tane prensip vardır.Diğer iki tanesi ise encapsulation ve polymorphism'dir.İlerleyen yazılarımızda bu iki prensibi de temel olarak incelemiş olacağız.