The Symbian OS (779886), страница 72

Файл №779886 The Symbian OS (Symbian Books) 72 страницаThe Symbian OS (779886) страница 722018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

And we were trying to ensure thatwe had some control over what was happening behind the scenes. It’s stillimportant today, although compilers are better at implementing all of thoseodds and ends, and having a good relationship with the compiler vendormakes it easier to have confidence in the compiler being efficient.Charles Davies:We were experienced in object-oriented programming. We were battlehardened in object-oriented programming.

But, in all honesty, we were stillnovices in C++.Managing C++Beginners’ mistakes are the mistakes you make because – well, becauseyou are beginners. C++ is a powerful language and there are almostcertainly cases in which its powerful object-oriented features overrodethe better judgment of even seasoned developers.Charles Davies:We over-used inheritance, which everybody does when they get introducedto object-oriented programming.

But we weren’t new to object-oriented andshould have known better.David Wood:We probably did take some of the inheritance hierarchies too far. That wasdriven by an understandable wish to avoid duplication of code, but some of thehierarchies as a result became, shall I say, unnaturally clever. That clevernesssolved the problem of the moment, but ended up itself being difficult tomaintain.Possibly the problem was that because people felt they knew whatthey were doing with object orientation, they saw in the language onlythe opportunity to exploit object orientation more fully, rather thanthe dangers of over-abstraction and over-complexity.

However, overuseof inheritance is symptomatic of confusion between class relationships(e.g. the difference between is-a inheritance relationships and has-aPIONEERING THE OBJECT APPROACH IN PSION345composition relationships) and the misuse of so-called ‘implementation’inheritance.7Andrew Thoelke:C++ is an extremely flexible language because you can ignore all the extrasand just use raw C with all of its ability to manipulate hardware and to dowhatever you like.

But C++ also allows you to be overly excessive with theuse of things like inheritance until you get to the point where you lose track ofwhat exactly you are doing anyway.David Wood:There’s actually a spectrum of reuse. On the one hand, you end up withmultiple copies of the same code and that’s no good. At the other end of thespectrum, you end up with just a single bit of code which is so convoluted itmanages to do everything but no one can understand it.

And there’s a happymiddle ground which nowadays we occupy much more readily.Certainly there were language features which were considered dangerous, in some cases because they were not well-enough understoodin the company (there just was not sufficient grounding in the languagefor there to be enough experts to make the judgments and providethe design and coding guidelines, short of outright banning), and inother cases because they were not mature, whether in terms of thelanguage specification or of the implementation of the available tools(compiler). Templates, multiple inheritance and namespaces are threeexamples.TemplatesTemplates are a C++ mechanism for writing type-independent code,typically library-like classes that are useful for managing objects of anytype, which are then invoked in subsequent code with a parameterof a concrete type, for which the compiler generates (or selects) typespecific code at the point of invocation.

They were added to the languageparticularly to solve the problem of providing useful, generic containerclasses capable of acting as containers for objects of arbitrary type, inother words, of any type whatsoever that a program might invent (see[Stroustrup 1994, p. 339]). (Ada is another language that provides atemplate mechanism, though it is different from that of C++.)7‘Implementation inheritance’ (in which a derived class inherits its base class implementation, that is, the implementation of the base-class methods) contrasts with ‘interfaceinheritance’ (in which the derived class inherits its base-class interface but not the implementation of the base class methods); see [Stroustrup 1993, p.

413].346THE USE OF OBJECT-ORIENTED DESIGN IN SYMBIAN OSThe problem is that naive use of templates causes code bloat. As atemplate user, each time you instantiate a given template for a given type,the compiler generates a fresh copy of the complete template code forthat type. Each time, every time.Martin Tasker:All major systems that existed at that time had been written in C, and C++ wasa language that people were still getting comfortable with. There was still alot of opinion that some of the features of C++ were too expensive to use in aROM-based small device. Templates being one of them.Careful design of the initial template classes can avoid the problem,but to do so requires expertise.Andrew Thoelke:Certainly parameterized programming using templates is something that’s atleast a degree harder to understand than some other features.

It’s very easy tobury yourself in complexity that you assume the compiler will get you out of,but you really don’t know. The actual side effects in terms of size of code orperformance are hard to measure sometimes. It’s hard to write very complextemplate code well.Especially in the early days of Symbian’s adoption of C++, when thelanguage was fluid and the standard libraries (which were almost whollytemplate-based) were still evolving and had not been fully standardized,templates were regarded in the company as potentially dangerous andtherefore treated with extreme suspicion. 8Martin Tasker:The Standard Library is the basis of what people call generic programming.We do not do that at all in Symbian OS. We have a few templated types,but we don’t use them aggressively enough to call it generic programming.

Idon’t think there were many people anywhere that understood the StandardLibrary at the time it was being designed, and we certainly didn’t. Collectivelyin Symbian, or Psion as it then was, we didn’t understand it.8Even the experts find templates hard. See, for example, Scott Meyers in his introductionto [Alexandrescu 2001].PIONEERING THE OBJECT APPROACH IN PSION347Instead, an in-house idiom called ‘thin templates’ was evolved for somegeneric, container-style classes, based around type-independent, pointerbased concrete classes (which therefore can accept pointers to any typeof object), wrapped by a template class that contains no implementation,but just serves to enforce a parameterized interface to force type-safetyfor the object type for which it has been invoked.

(The technique is quitewell known in the C++ literature, see [Meyers, p. 191, Item 42].) Beyondthis, templates are not used in the Symbian OS library classes. If usedinternally elsewhere, they are used with extreme caution.Andrew Thoelke:It was more about the fact that the compilers didn’t do a good job withtemplates. They could only do very basic things. So we were very carefulabout how we used them.

We didn’t do anything very advanced. We werealso careful to tell people that templates can lead to code bloat if you use themaggressively. So instead we used templates to give type-safety over essentiallytype-unsafe container objects. Really we were trying to make sure that wecould have more maintainable, better written, higher quality code in the firstplace, by actually constraining the use of the language and helping the externaland internal developers to help themselves.Multiple InheritanceInheritance is the basis for structuring the object relationships whichunderwrite the collaboration and delegation between objects in (classbased) object-oriented design.9 Inheritance relates objects logically andprovides the mechanism for sharing common behavior.Some object-oriented languages, and C++ is one of them, allow multiple inheritance.

(Eiffel, CLOS and Dylan are other examples; languageswhich do not allow multiple inheritance include Beta and Smalltalk).Multiple inheritance allows objects to have multiple parents. As with templates, casual use of multiple inheritance can lead to multiple instancesof identical code being generated. One of the early rules within Psionwas therefore ‘no multiple inheritance in C++’.The idea of multiple inheritance is trivial enough to grasp. For example,a police car inherits from Car, but also has Emergency properties, whichfire engines and ambulances also share, even though they are not derivedfrom Car (for example, they may be derived from Truck); multiple inheritance allows emergency vehicles to share Emergency properties, inheritedfrom an Emergency class, while deriving from different vehicle base9There are non-class-based systems for example the language Self, based on prototypes(see Chapter 4).348THE USE OF OBJECT-ORIENTED DESIGN IN SYMBIAN OSclasses.10 While the principle is simple, the implications for implementation in an object-oriented language go deep.Martin Tasker:The multiple inheritance chapter in the Ellis and Stroustrup book is staggeringlydifficult! It’s mind-bogglingly difficult! So we made a really conscious effort:no multiple inheritance at all.

And in fact our solution, Mixins, serves exactlythe same purpose as the equivalent in Java, that is, interface classes, and theyare really easy for the user.Andrew Thoelke:Some of the constraints, like ‘avoid multiple inheritance unless the additionalbase classes are interfaces only’, was partly to avoid the Evil Diamondinheritance graph, which you can acquire without always realizing it, andwhich all the text books said was a Bad Idea, unless you used virtual bases,which we always said, ‘No, don’t do it’, on grounds of performance andfootprint and questionable value.The ‘Evil Diamond’ pattern is one in which class K derives from bothclasses B and C, which both derive from A. (K, by multiple inheritance,inherits from both B and C; both B and C inherit, possibly also throughmultiple inheritance, from A.)The problem with this pattern is that, because C++ implements inheritance of behavior at compile time not run time, if class A containsconcrete method implementations then its code may be and its v-tableis compiled into the code for both B and C (because they inherit thebehavior) and appears twice in class K.The immediate problem that outlawing the use of multiple inheritancecauses is that no class can present multiple interfaces.

An example of thevalue of interface inheritance is the Observer pattern. Some object hasbehavior derived through one inheritance hierarchy, say Timer or Alarm,but is also an Observer of some event that triggers its behavior. Not alltimers and alarms are Observers, but some certainly would like to be.11ABCKFigure 14.110The ‘Evil Diamond’ patternThe example is from [Stroustrup 1993, p.

405].[Stroustrup 1994, p. 271] cites Stream I/O as an example of the value of composition ofinterfaces; another example is composing a class from an implementation and an interface.11PIONEERING THE OBJECT APPROACH IN PSION349Java (as a ‘better C++’) explicitly provides machinery for addinginterfaces to objects. But in the absence of that, multiple inheritance isthe most natural way to get it, and the only way to get it by derivation.(So-called ‘fat’ interfaces are an alternative approach, see the discussionon ‘Streams, Stores and Persistence’ in Section 4.3.)Eventually a compromise was reached and ‘mixin’ (‘M’ or interface)classes were introduced, following the solution which had actually beenfirst adopted for CLOS.12 Mixins solve the problem of how to get thebest of multiple inheritance, for example, so that objects can presentmultiple interfaces, without getting the worst of multiple inheritance,code duplication and bloat, and over-complex and over-designed classhierarchies.With the mixin pattern, while only one inheritance path may inheritbehavior, in other words inherit from (and, therefore, include the codefrom) a concrete base class, a class is allowed to inherit from as manyM classes as it likes because M classes may only define pure virtualfunctions.

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

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

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

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