Главная » Просмотр файлов » John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG

John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (779881), страница 4

Файл №779881 John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (Symbian Books) 4 страницаJohn.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG2018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

These were calledmnemonics, and while still arcane and hard to understand, they didmean that it was much easier to read and write computer code.But the processor could still only recognize 1s and 0s. So a programwas written that read in this list of mnemonics, looked up the database,and outputted 1s and 0s that could be read by the processor. Thisprogram could take something that was easy for users to read, andassemble something that was easy for computers to read. Hence, thesemnemonic words became known as Assembly Language. No longer didSPEAKING THE LANGUAGE7everyone have to work at a very low level; they could now work at ‘just’a low level.This is the principle of writing source code, and then translating it intosomething that is readable by the computer (called object code) beforestoring or running it.

It still required a lot of knowledge about how theprocessor worked, and while still very hard to program in, it made life alot easier.1.2.2 Climbing up to Higher LanguagesNowadays, there are a lot of languages out there, some of them work ata low level, like Assembly, but most people prefer to work in languagesthat are easier to read and offer other advantages.Symbian OS offers developers many choices of development languageincluding native C++, Java, Mobile Visual Basic (‘Crossfire’ from SymbianPartner AppForge) and, of course, OPL.

The two most widely usedlanguages are currently C++ and Java (specifically the Personal Java orMIDP implementation).A simple diagram (Figure 1.2) illustrates the move from lower-levellanguages to higher-level ones.Low LevelAssemblerMachineCodeFigure 1.2High LevelC++JavaOPL AppleScriptEnglishTransition from lower-level to higher-level languagesC++ – The Halfway HouseYou hear that C++ is a very powerful language. This means that it cando a lot of I/O operations, and as a programmer you have to be able tospecify exactly what has to happen.

This means you have a large amountof control over what you can make the processor do, but you also haveto understand the effects of everything.A good C++ programmer needs to know almost everything aboutevery subject that we might encounter – controlling the screen, communications devices, memory access, etc. C++ itself also offers advantagesto programmers in terms of ‘code re-use’ to save them re-implementinglots of code in multiple programs. This is a classic trade-off in programming – very often, the more power a language offers you, the steeper thelearning curve.Java J2ME (MIDP)One of Java’s strengths is that once you have written one program, itshould be able to run on any computer that contains Java.

Why is this a8PROGRAMMING PRINCIPLESstrength? Because most different types of computer have a different list ofinstructions in the processor. This is why programs written in C++ andother low-level languages that run on one computer (e.g. an Apple Mac)will not run on another computer (e.g. Windows-based PC). The ‘price’you pay for this is more limited access to some system functionalitycompared to C++.BASICOne of the earliest ‘high-level’ languages was BASIC. Commands inBASIC were very close to readable English, and meant that the learningcurve associated with the low-level languages was not present.

Many ofthe personal computers available at the start of the home computer boomin the early 1980s shipped with BASIC installed on them, and this ledto a huge cottage industry of curious programmers programming theirmachines to do whatever they needed them to do.1.2.3 Compiled LanguagesWe’ve already seen that the principle of source code being compiled tomachine code is present in Assembly Language and C++, but higher-levellanguages (such as Java) work slightly differently.

The source code forthese languages is compiled into an intermediate form, and this code isthe object code.The object c is read in by another program. This program can takethe instructions in the object code, and interpret these into the correctcommands that need to be sent into the processor. This program can becalled an interpreter, or a runtime.Runtimes are usually device-specific, but are written in such a way thatthe object code can be read by any runtime, no matter what computer theruntime is running on. This is the principle of write once, run anywhere.Many high-level languages have this capability to some extent.1.2.4 The Trade-OffSo why doesn’t everyone just use the highest-level language possible?Two considerations: speed and access to functionality.Compiled high-level languages are much slower than lower-levellanguages such as C++.

Each command in the object code has to belooked up and translated into an instruction by the runtime as you gothrough your program. In lower-level languages, the code is already in theform the processor can understand, so there is no overhead to ‘translate’or ‘interpret’ it.In order to ensure the object code is universal, it must conform tosome kind of standard – thus you might not have access to all of theLEARNING THE VOCABULARY9functionality that is available to lower-level programming (for example,the Bluetooth I/O device) if the current standard does not specify this.

Ifyour runtime does allow you to access these features, it may be muchslower than accessing it from a low-level language.1.2.5 Where does OPL Fit in?OPL, in a similar way to Java, is an interpreted language that needs aspecial ‘OPL Runtime’.

This runtime can be packaged with every OPLapplication or downloaded separately from the Internet (we’ll show youwhere when we gather all our tools in the next chapter). If the runtimeis included in the actual package, the file size will be much larger, so itis common to provide a download reference in your documentation onwhere to download the runtime.The OPL Runtime is written in C++, to make sure the speed penalty ofusing a high-level language is minimized. OPL can be extended to accessthe device functionality through a feature called OPXs.

An OPX is an‘OPL eXtension’, and is a small piece of C++ code that can be loaded intoyour phone. OPL can then call this extension with a simple line of code.1.3 Learning the VocabularyNow we’ve had a look deep inside your phone, at how it works andthe basics of what a program is, we can start looking at OPL and howit works.Like any language, OPL has a grammar that you need to follow to beunderstood. You have words (commands) that have to be followed bycertain things to make them work. These make up lines of code (sentences)and these lines of code can be grouped to make procedures (paragraphs).From now on, we’re only going to concern ourselves with how thecomputer reacts to the OPL code you write.

Remember that once itis compiled, the runtime will do the work required to allow it to talkcorrectly to the processor, and OPL developers never need to concernthemselves with this.1.3.1ProceduresWhen an OPL program is run, the first procedure (here called PROCMain:, though commonly the first procedure is named after the program)is opened. The lines are then read and processed in the order they arelisted, until the ENDP (end of procedure) command is reached, at whichpoint the program stops itself.Within a procedure, you can call another procedure.

Do this simplyby typing the name of the procedure you want to run next. All procedurenames must have a colon after them (:) in both the PROC command andwhen calling that PROC from inside the code.10PROGRAMMING PRINCIPLESPROC Main:SetupApp:DoSomethingNice:SaveStatus:ENDPPROC SetupApp:rem Do something interesting hereENDPetc...In this example, PROC Main: is opened, it calls three other proceduresin order, then reaches ENDP and the program closes. Note that eachprocedure must start with PROC <a name>: and end with ENDP onseparate lines.

When the end of the first procedure is reached, your OPLprogram stops. The only way to run other procedures is to call them inthis way.Procedure names cannot have spaces in them, so you’ll see that eachnew word is signified by a capital letter. While OPL is not case-sensitive,this is the recommended style for writing code. If you follow this style, itmakes it easier for you (and other programmers) to read your code.1.3.2 The Remark StatementSpeaking of making code easier, you’ll see in the example above that wehave a line with a new command.rem Do something interesting hererem stands for remark, and it’s a powerful statement for anyone readingthe code.

You see, the rem statement does absolutely nothing. Theinterpreter ignores anything after the rem statement on the same line, soyou can use it to add notes, thoughts, and descriptions throughout yourcode. For example, a procedure may have something like this at the start:PROC WhereIsTheCursor:rem This routine calculates the cursor positionrem FooX%% represents the temporary x co-ordinaterem FooY%% represents the temporary y co-ordinateetc...Not only are these rem statements useful when you come back to thecode in six months’ time and can’t remember what something is for, theyare also useful if other people are going to read your code.1.3.3 VariablesA variable is something you want your program to remember for acertain amount of time – either throughout the entire time the programLEARNING THE VOCABULARY11is running, or just during one particular procedure.

A variable can be asmall number, a big number, or a string of letters and numbers. Eachof these variables is given a name, and a small sign to indicate whattype of information it represents. You should also remember these namescannot have a space in them either, so don’t forget to use capital lettersfor YourVariableNames.Types• A small number (called a ‘short integer’) is followed by a % sign. Forexample, HighScore% is a short integer that stores a number, andcan be referred to as HighScore% in your code.

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

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

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

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