آموزش Code Contracts
نویسنده: مسعود پاکدل
تاریخ: ۱۳۹۱/۱۱/۲۳ ۸:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class timeclock
{
public void clockin( int32 id, datetime clockdate )
{
if ( id < 0 )
{
throw new argumentoutofrangeexception( "..." );
}
if ( clockdate.date != datetime.now.date )
{
throw new argumentexception( "..." );
}
}
public dailyreport getdailyreport( int32 employeeid, datetime fordate )
{
var dailyreport = new dailyreport();
return dailyreport;
}
}
public class dailyreport
{
public int32 employeeid { get; set; }
public int32 hoursworked { get; set; }
} public void clockin( int32 id, datetime clockdate )
{
contract.requires<argumentoutofrangeexception>( id < 0 );
contract.requires<argumentexception>( clockdate.date != datetime.now.date );
contract.endcontractblock();
}فرق این روش با روش قبلی اینه که اگر در برنامه متد clockin رو به روش پایین استفاده کنیم، در هنگام اجرای برنامه با خطای زیر متوقف و رو برو میشیم
var timeclock = new timeclock(); timeclock.clockin( -1, datetime.now );
همان طور که مشاهده میکنید با استفاده از تعریف Contract قبل از اجرای برنامه برای ما مشخص خواهد شد مقدار پیش فرض 0 برای متغیر d درست نیست در واقع اصلا این کد کامپایل نمیشود.