Главная » Просмотр файлов » 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), страница 10

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

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

The reason for this is thatState classes, derived from TAVStreamState, which are by designexpected to receive ‘Set Configuration’ events must explicitly overridethe SetConfigurationL() function to provide an implementation todeal with the event. Failing to provide a way to handle the implementationis considered to be a fault.Other Known UsesThis pattern is used widely throughout Symbian code and here we givejust a select few:• DescriptorsSymbian OS descriptors panic when an out-of-bound access isattempted. The prevalent use of descriptors for buffers and stringsin Symbian OS means that the possibility of arbitrary code executionthrough a buffer overflow attack against Symbian OS components isvastly reduced.

This type of panic is an external panic, as it forms partof the API to a bounded region of memory.• Active ObjectsThe active scheduler panics if it detects a stray signal rather than justignoring it as it indicates that there is an error with an asynchronousrequest made via an active object. By panicking as soon as thiscondition is detected, debugging the defect is much easier than tryingto track down why some notifications do not occur occasionally.• Symbian Remote Control FrameworkThis component auto-generates the panic reason for its internal assertswhich are compiled only into debug builds. These asserts are liberallyused throughout the component.FAIL FAST31Variants and Extensions• Passing Additional Debug Information when PanickingThe usual procedure for assigning the category and reason for a panicis to give the component name for the category and then just assigna fixed number for the reason.

However, the category can be up to16 letters and the reason is 32 bits so there are usually opportunitiesfor additional information to be given here. For instance the ALLOCpanic is used when a memory leak has been detected and the reasoncontains the address of the memory. Also, some state machines thatraise panics use the bottom 16 bits of the reason to indicate whichassert caused the problem and the top 16 bits to indicate the state thatit was in at the time.• Invoking the Debugger when Failing an AssertSymbian OS provides the __DEBUGGER() macro which can be usedto invoke a debugger as if you had manually inserted a breakpointwhere the macro is used. This does not result in the thread beingkilled.

The debugger is only invoked on the emulator and if ‘Just InTime’ debugging has been enabled for the executing process.12 In allother circumstances, nothing happens.This variant combines the use of this macro with __ASSERT_DEBUG() calls but otherwise applies the pattern described above.This allows you to inspect the program state when the assert failedand so better understand why it happened.References• Escalate Errors (see page 32) is related because it may be useful forthose domain and system errors for which this pattern cannot be used.• Code that tests itself: Using conditions and invariants to debug yourcode [Weir, 1998].• en.wikipedia.org/wiki/Assertion(computing) is an article on the general use of assertions when developing software.12 Itis enabled by default but can be changed using User::SetJustInTime() orRProcess::SetJustInTime().32ERROR-HANDLING STRATEGIESEscalate ErrorsIntentEnhance your error handling by using the Symbian OS Leave mechanismto escalate the responsibility of handling an error up to the point whichhas enough context to resolve the error.AKALeave and Trap, Error Propagation, Exception Handling, and SeparatingError-Handling Code from ‘Regular’ CodeProblemContextYour component is part of or contains a layered software stack13 and hasto appropriately handle non-fatal domain or system errors.Summary• Non-fatal errors must be resolved appropriately so that an applicationor service can continue to provide the functionality the user expects.• There should be a clear separation between code for error handling and the normal flow of execution to reduce development timeand maintenance costs by reducing code complexity and increasingsoftware clarity.• Error-handling code should not have a significant impact at run timeduring normal operation.DescriptionMost well-written software is layered so that high-level abstractionsdepend on low-level abstractions.

For instance, a browser interacts withan end user through its UI code at the highest levels of abstraction. Eachtime the end user requests a new web page, that request is given to theHTTP subsystem which in turn hands the request to the IP stack at a lowerlevel. At any stage, an error might be encountered that needs to be dealtwith appropriately.

If the error is fatal in some way, then there’s little youcan do but panic as per Fail Fast (see page 17).Non-fatal error conditions, however, are more likely to be encountered during the operation of your application or service and yourcode needs to be able to handle them appropriately.

Such errors can13 As per the Layers pattern described in [Buschmann et al., 1996] or Model–View–Controller (see page 332).ESCALATE ERRORS33occur at any point in the software stack whether you are an applicationdeveloper or a device creator.

If your software is not written to handleerrors or handles them inappropriately14 then the user experience willbe poor.As an illustration, the following example of bad code handles a systemerror by ignoring it and trying to continue anyway. Similarly it handlesa recoverable missing file domain error by panicking, which causes theapplication to terminate with no opportunity to save the user’s data or totry an alternative file. Even if you try to set things up so that the file isalways there, this is very easily broken by accident:void CEngine::Construct(const TDesC& aFileName){RFs fs;fs.Connect(); // Bad code - ignores possible system errorRFile file;err = file.Open(fs,aFileName,EFileRead); // Could return KErrNotFoundASSERT(err == KErrNone);...}In general, it is not possible for code running at the lowest layers ofyour application or service to resolve domain or system errors.

Considera function written to open a file. If the open fails, should the functionretry the operation? Not if the user entered the filename incorrectly butif the file is located on a remote file system off the device somewherewhich does not have guaranteed availability then it would probably beworth retrying. However, the function cannot tell which situation it isin because its level of abstraction is too low. The point you should takeaway from this is that it may not be possible for code at one layer to takeaction to handle an error by itself because it lacks the context present athigher layers within the software.When an error occurs that cannot be resolved at the layer in whichit occurred the only option is to return it up the call stack until itreaches a layer that does have the context necessary to resolve theerror.

For example, if the engine of an application encounters a diskfull error when trying to save the user’s data, it is not able to startdeleting files to make space without consulting the end user. So insteadit escalates the error upwards to the UI layer so that the end user can beinformed.It would be inappropriate to use Fail Fast (see page 17) to resolve sucherrors by panicking. Whilst it does have the advantage of resolving thecurrent error condition in a way which ensures that the integrity of datastored on the phone is unlikely to be compromised, it is too severe a14 Suchas by using Fail Fast (see page 17) when there was a possibility of a safe recovery.34ERROR-HANDLING STRATEGIESreaction15 to system or domain errors that should be expected to occurat some point.Unfortunately, the C++ function call mechanism provides no distinctsupport for error propagation by itself, which encourages the developmentof ad-hoc solutions such as returning an error code from a function.

Allcallers of the function then need to check this return code to see if it is anerror or a valid return, which can clutter up their code considerably.As an example of where this is no problem to solve, consider theerror-handling logic in the TCP network protocol. The TCP specificationrequires a peer to resend a packet if it detects that one has been dropped.This is so that application code does not have to deal with the unreliabilityof networks such as Ethernet. Since the protocol has all the information itneeds to resolve the error in the layer in which it occurred, no propagationis required.ExampleAn example of the problem we wish to solve is an application that transmits data via UDP using the Communication Infrastructure subsystem16of Symbian OS, colloquially known as Comms-Infras.

The application islikely to be split up into at least two layers with the higher or UI layerresponsible for dealing with the end user and the lower or engine layerresponsible for the communications channel.The engine layer accesses the UDP protocol via the RSocket API buthow should the engine layer handle the errors that it will receive fromthis API? How should it handle errors which occur during an attempt toestablish a connection?• Clearly it should take steps to protect its own integrity and clean up anyresources that are no longer needed that were allocated to perform theconnection that subsequently failed.

But to maintain correct layeringthe engine shouldn’t know whether the connection was attempted asa result of an end user request or because some background task wasbeing performed. In the latter case, notifying the end user would beconfusing since they’d have no idea what the error meant as theywouldn’t have initiated the connection attempt.• The engine cannot report errors to the end-user because not onlydoes it not know if this is appropriate but doing so would violatethe layering of the application and make future maintenance moredifficult.• Ignoring errors is also not an option since this might be an importantoperation which the user expects to run reliably. Ignoring an error15This is especially true for system-critical threads since any panic in such threads willcause the entire device to reboot.16 For more information see [Campbell et al., 2007, Chapter 3].ESCALATE ERRORS35might even cause the user’s data to be corrupted17 so it is importantthe whole application is designed to use the most appropriate errorhandling strategy to resolve any problems.For system errors, such as KErrNoMemory resulting from the failureto allocate a resource, you might think that a valid approach to resolvingthis error would be to try to free up any unnecessary memory.

Thiswould resolve the error within the engine with no need to involve theapplication at all. But how would you choose which memory to free?Clearly all memory has been allocated for a reason and most of it toallow client requests to be serviced. Perhaps caches and the like can bereduced in size but that will cause operations to take longer. This mightbe unacceptable if the application or service has real-time constraintsthat need to be met.SolutionLower-level components should not try to handle domain or system errorssilently unless they have the full context and can do so successfully withno unexpected impact on the layers above.

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

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

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

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