Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 9

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 9 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 92018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 9)

A panic is most commonly issued on the local thread, by calling User::Panic(const TDesC& aCategory, TInt aReason)which is declared in e32std.h. The category is a textual value,6 and the6 Atmost KMaxExitCategoryName or 12 characters long.FAIL FAST25reason is a numeric value; together they form a description of the causeof a panic. This description is shown on the screen in a dialog box aswell as being sent to the debug output.

For instance:_LIT(KPanicCategory, "Fail Fast");enum TPanicCode{EInvalidParameter,EInvalidState,EInappropriateCondition,...};void CClass::Function(const TDesC& aParam){__ASSERT_ALWAYS(aParam.Length() == KValidLength,User::Panic(KPanicCategory, EInvalidParameter));__ASSERT_DEBUG(iState == ESomeValidState,User::Panic(KPanicCategory, EInvalidState));// Function implementation}Using the parameters passed to Panic() in a disciplined way provides useful debugging information. Notably, if the category and reasonuniquely map to the assert that caused the panic then even if a stack traceor trace data for the fault is not available7 then someone investigating thefault should still be able to identify the condition that caused the problem.For external asserts, time spent explicitly creating a unique panic category and reason combination for every assert in the component is oftentime well spent.

Taking the example above, EInvalidParametercould become EInvalidParameterLengthForCClassFunctionand EInvalidState may become EInvalidStateForCallingCClassFunction, and so on.One of the reasons for explicitly setting the category and reason forexternal asserts is that they form part of the API for clients of yourcomponent. Developers using the API will expect consistency not onlyfor its run-time behavior but also in how they debug their client code,for which identifying a particular panic is key.

The use of external assertshelps to maintain compatibility for the API of which they form a part.By documenting and enforcing the requirements for requests made onan interface more rigidly (by failing fast), it becomes easier to changeimplementations later as it is clear that clients must have adhered to thespecific criteria enforced by asserts.One problem with this is that the development cost of explicitly assigning the category and reason for each separate panic is proportional tothe number of asserts and so can become time consuming. An alternativethat is well suited to internal asserts is to have the panic category assigned7 Ascan be the case for those rare issues that are only seen on a release device.26ERROR-HANDLING STRATEGIESautomatically as the most significant part of the filename and the reasonas the line number:#define DECL_ASSERT_FILE(s) _LIT(KPanicFileName,s)#define ASSERT_PANIC(l) User::Panic(KPanicFileName().Right(KMaxExitCategoryName),l)#define ASSERT(x) { DECL_ASSERT_FILE(__FILE__);__ASSERT_ALWAYS(x, ASSERT_PANIC(__LINE__) ); }This does have one big disadvantage which is that you need to havethe exact version of the source code for the software being executed tobe able to work out which assert caused a panic since the auto-generatedreason is sensitive to code churn in the file.

Not only might the developerseeing the panic not have the source code, even if he does the personattempting to fix the problem will probably have difficulty tracking downwhich version of the file was being used at the time the fault wasdiscovered. However, for internal asserts that you don’t expect to be seenexcept during development of a component this shouldn’t be a problem.Panicking the Correct ThreadIt is critical to fail the appropriate entity when using this pattern. Forinternal asserts, it is not necessarily an issue since it is nearly always thelocal thread.

However, for external asserts policing requests from clients,it is not so straightforward:• In libraries, either statically or dynamically linked, it is the currentthread.• In services residing in their own process, it is the remote thread thatmade the request.For the latter case, when using Client–Server (see page 182), the clientthread can be panicked using the RMessagePtr2::Panic() function:void CExampleSession::ServiceL(const RMessage2& aMessage){...if(InappropriateCondition()){aMessage.Panic(KPanicCategory, EInappropriateCondition);return;}...}Alternatively you can use RThread::Panic() to panic a singlethread or RProcess::Panic() to panic a process and all of its threads.FAIL FAST27Ultimately the choice of where and how to fail fast requires consideration of users of the software and some common sense.ConsequencesPositives• The software quality is improved since more faults are found beforethe software is shipped.

Those faults that do still occur will have areduced impact because they’re stopped before their symptoms, suchas a hung application or corrupted data, increase.• The cost of debugging and fixing issues is reduced because of the extrainformation provided by panic categories and reasons, in addition toproblems being simpler because they’re stopped before they causeknock-on problems.• The maintainability of your component is improved because theasserts document the design constraints inherent in its construction.• Security is improved because faults are more likely to stop the threadexecuting than to allow arbitrary code execution.Negatives• Security can be compromised by introducing denial-of-service attackssince a carelessly placed assert can be exploited to bring down athread.8• Carelessly placed external asserts can reduce the usability of an API.• Code size is increased by any asserts left in a release build. On nonXIP devices, this means increased RAM usage as well as additionaldisk space needed for the code.• Execution performance is impaired by the additional checks requiredby the asserts left in a release build.Example ResolvedThe Symbian OS GAVDP/AVDTP implementation applies this patternin several forms.

It is worth noting that the following examples do notconstitute the complete usage of the pattern; they are merely a small setof concise examples.API GuardsThe GAVDP API uses the Fail Fast approach to ensure that a client usesthe API correctly.

The most basic form of this is where the API ensures8 Oreven the whole device, if the thread is system critical.28ERROR-HANDLING STRATEGIESthat the RGavdp object has been opened before any further operationsare attempted:EXPORT_C void RGavdp::Connect(const TBTDevAddr& aRemoteAddr){__ASSERT_ALWAYS(iGavdpImp, Panic(EGavdpNotOpen));iGavdpImp->Connect(aRemoteAddr);}The implementation9 goes further to police the API usage by clients toensure that particular functions are called at the appropriate time:void CGavdp::Connect(const TBTDevAddr& aRemoteAddr){__ASSERT_ALWAYS((iState == EIdle || iState == EListening),Panic(EGavdpBadState));__ASSERT_ALWAYS(iNumSEPsRegistered, Panic(EGavdpSEPMustBeRegisteredBeforeConnect));__ASSERT_ALWAYS(aRemoteAddr != TBTDevAddr(0),Panic(EGavdpBadRemoteAddress));__ASSERT_ALWAYS(!iRequesterHelper, Panic(EGavdpBadState));...}Note that the above code has state-sensitive external asserts which, ashas been mentioned, should be carefully considered.

It is appropriate inthis particular case because the RGavdp class must be used in conjunctionwith the MGavdpUser class,10 whose callbacks ensure that the clienthas sufficient information about whether a particular function call isappropriate or not.Invariant, Pre- and Post-condition CheckingA lot of code written in Symbian OS uses asserts to check designconstraints and AVDTP is no exception. For performance reasons, themajority of these asserts are only active in debug builds:void CAvdtpProtocol::DoStartAvdtpListeningL(){LOG_FUNC// Check that we haven’t already got an iListener.// NOTE: in production code we will leak an iListener.9 Note that the RGavdp and CGavdp classes are the handle and the body as a result ofthe use of the Handle–Body pattern (see page 385) in their design.10 See Event Mixin (page 93).FAIL FAST29// These are fairly small so not too severe.__ASSERT_DEBUG(!iListener, Panic(EAvdtpStartedListeningAgain));...}The example shows a good practice: using a comment to explicitlystate what will happen in release builds if the particular fault occurs.

Inthe code above, although we do not want to leak memory, the debugassert combined with comprehensive testing should give us confidencethat this condition will never actually arrise.The use of asserts is not limited to complex functions. Even simplefunctions can, and should, check for exceptional conditions:void CManagedLogicalChannel::ProvideSAP(CServProviderBase* aSAP){__ASSERT_DEBUG(aSAP, Panic(EAvdtpPassingNullSapOwnershipToChannel));__ASSERT_DEBUG(!iLogicalChannelSAP, Panic(EAvdtpPassingSapOwnershipToChannelThatAlreadyHasASap));iLogicalChannelSAP = aSAP;iLogicalChannelSAP->SetNotify(this);}The above example shows the use of a pre-condition check, firstly thatthe parameter to the function is not NULL, and secondly that the objectupon which the function is called does not already have a Service AccessPoint (SAP) bound to it.These last two example code snippets demonstrate the use of panicreasons that are unique across the whole component by design andprobably across the whole of Symbian OS through the use of the EAvdptprefix.

Although the names of the particular panic reason enumeration values can be fairly long, they are self-documenting and thus noaccompanying comment is required. Furthermore, they provide a gooddemonstration of how asserts can document the design constraints of animplementation.11State Transition CheckingThe checking of state transitions can be thought of as a special caseof invariant checking. The following function is the base class implementation of the ‘Set Configuration’ event for an abstract class representing11 From the ProvideSAP() function, it is apparent that the CManagedLogicalChannel class is only ever intended to have a single logical channel (represented by a SAP)bound to it and that it takes ownership of the SAP passed into the function.30ERROR-HANDLING STRATEGIESan audio–video stream state as per the State pattern [Gamma et al.,1994]:void TAVStreamState::SetConfigurationL(CAVStream& /*aStream*/,RBuf8& /*aPacketBuffer*/,CSignallingChannel& /*aSignallingChannel*/,TBool /*aReportingConfigured*/,TBool /*aRecoveryConfigured*/) const{LOG_FUNC DEBUGPANICINSTATE(EAvdtpUnexpectedSetConfigurationEvent);User::Leave(KErrNotReady);}In this particular example, we can see the base class implementationtriggers an assert if in debug mode, but in a release build the faultwill be handled as an exceptional error.

Характеристики

Тип файла
PDF-файл
Размер
2,96 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6353
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее