Unit 4 - Learning Aim A
AI-enhanced title
is used to denote the start and end of a paragraph, as shown in Figure 4.5. A new paragraph< > graphLet’s Dance > Figure 4.5 Bowie, David 1983 » ae markup languages can be used to represent complex data structures ioe ee manner, such as entries from a CD library stored in » as shown in Figure 4.6. Rubber Soul > a is often used as the preferred format to transfer data between petal face A ‘ ifferent Computer systems and applications, such as when exporting and 1965 importing data between relational database systems that are normally incompatible. > Figure 4.6 Programming Paradigm Programming languages Scripting © Perl © JavaScript * Ruby © PHP Features and characteristics Different types of scripting languages are used for different purposes. #!/usr/bin/ruby JavaScript is used in web design to automate processes and add interactive : features to web pages. filename = ARGV[®] PHP is a popular server-side scripting language used to create complex online applications used in e-commerce. aFile = File.new(filename ) Perl and Ruby are often used to automate system processes on a computer by linking and executing tasks that may have originally been run separatel i a Y ig iB y iginally pi ry af aPile by a user. For example, Figure 4.7 shows a Ruby program to display the first 3 255 bytes of a specified file on screen. content = aFile.sysread(’'») puts content else puts 1able t pen file! end > Figure 4.7Hardware to use: PC, Apple Mac etc. Operating system ‘Operating system to use: tou: Microsoft Windows Apple Mac 0S X, Microsoft Windows, Linux etc. Preferred programming, Preferred programming environment: environment to use: Visual Studio Various > Figure 4.8: Contrasting hardware and software requirements for selected programming languages Hardware and software needed for running and developing a program Some programming languages require specific hardware and software for running and developing a program, Preferred requirements for popular programming languages are shown in Figure 4.8. fs, such as C, are considered to be ‘cross-platform. d on many different combinations of hardware and ain why itis still so popular with commercial sed back in 1972. Some programming languag' This means that it is supportes operating system. This is likely to expl programmers, despite the fact that it was initially releas Special devices required 8 samy pevinter When programming solutions Seon oncsta deve for external hardware, itis quite ‘common to connect a desktop PC toa special device, typically a Serial Programming Interface (SPI) or Joint Test Action Group (JTAG). This special device is usually connected tothe desktop PC via a universal ___ Serial bus (USB), serial or parallel able, and it allows the developer to Perform a process called in-syste™ Programming (ISP). ISP allows devices to be reprogrammed without being from their original circuit. ‘a.common use of ISP is a okPerformance ao can perform more or less efficiently than one another. Typically, performance is measured by anes ability to execute complex algorithms against . For example, some programming languages make better use of the CPU by having more efficient translators that generate tightly optimised machine code. Some programming languages manage RAM more efficiently than others by having aggressive garbage collection measures. Garbage collection is nota mandatory process and some languages, such as C, require the programmer to remember to manually deallocate ‘memory which is no longer in use. Aggressive garbage collection may make the language faster but runs the risk of memory ‘leaks’ occurring. Garbage collection - an automated process which attempts to reclaim RAM reserved by a program to store data, e.g. an identifier (variable or object) that is no longer needed. Preferred application areas Some programming languages are better suited for some areas of application. > Cis considered to be a general-purpose language, but it is particularly effective for controling external hardware ‘and electronics because of its low-level control of the computer system. > Java is used to create applets for webpages and Android mobile apps. Its ‘write once, run anywhere! (WORA) approach means itis incorporated into many iferent forms of home entertainment device, eg. TV set-top boxes and Blu-ray players. > PHP is used to create server-side applications for businesses in e-tail, e-commerce et. > Cis used to create videogames for Microsoft Windows and popular games consoles, particularly because of its ease of use with Microsoft's XNA, which is a popular set of tools used in videogame development and management. > Objective-C is used to create mobile apps for Apples i devices, ie. iPad, iPhone etc. Development time Development time is an i choosing a programming paradigm. For example, as we have seen, programs written Using machine code and assembly are efficient and execute very quickly, eee lopment time when using these languages can important consideration when ie | be much longer than when working with high-level languages in modern integrated development environments. inccommercial programming, time is equated direc money, 30 there isa strong emphasis on writing relate Code with a minimum of DUBS as quickly as possible As» Consequence, programing languages Supported by feature-rich development tools which claim to reduce development time are popular. However, it can be difficult to measure development time This is because acceptable metrics are hard to determine and agree upon within the industry For example, you could consider the number of lines of code (LOQ) writen per hour to be an acceptable metric, but this may not Consider the number of related bugs that are generated. Inaddition, ifa programmer knows that their productivity ig measured by the number of LOC that they create in an hour, this may encourage them to write overly verbose code. Key terms Metric - an agreed form of measurement that enables | ‘comparison and evaluation. | Verbose - using more words or code than necessary. Ease of development As noted earlier, some programming languages are ease" to use than others, This is because some languages present the software developer with advanced tools that can offer hints or auto-generated program code. For example Microsoft Visual Basic .NET converts input forms created using drag-and-drop functionality into program code automatically. The quality of other tools available within a program'"é language editor can also have an impact on the ease of development and a programmer's productivity These tools include help systems, syntax highlighting a”? debugging tools. > Syntax highlighting isa feature in many programn"s language editors which displays different program" constructs in specific colours. For example, core may appear in green, a string of text in red and so ie Most developers find the resulting code easier 0°" understand and debug. > Debugging tools offer the programmer a rang> of features that help them to identify bugs in thelr < and remove them. Popular debugging tools include traces, watches and breakpoints.ee F esearch and explore different programming you can" ages online through the use of virtual development ‘environments. These environments let you select a particular language, Key some basic program code and ite it. You will be able to find examples through an 1 intemet search. — which programming language, platform t tools you use, you will need to. sp and demonstrate professional behaviour propriate for the programming industry. ciplined - you should set relevant int targets and work to realistic cting others and their opinions, especially they are giving you essential feedback on am and its suitability when assessed original user needs ‘outcomes to help you justify your dations and decisions, particularly in design or implementation of your and contrasting set targets with their comes, as this will help you to understand your performance as a developer and others as part of a team ~ this is ‘when contributing to a ing task which involves others. colleagues with support, rkload, respond common across a number of languages, which means ferred between that your knowledge can be easily trans! languages, Code samples from a number of different popular programming languages have been used to help you compare and contrast their constructs and techn However, the larger code samples in this chapter have been written in Microsoft C#, which is a very popular language within the software development industry. ‘As your skills progress, you should find it relatively simply to convert these code samples to another target language. Command words The concept of command (or reserved) words is at the core of most programming languages. These reserved words cannot be used by a programmer to name things (cee Identifiers). Instead, they are used to command a specific action, such as open a file, ‘clear the screen’ or put text on the screen’. The quantity and purpose of reserved words can vary greatly between different programming languages but, as you become more experienced as a developer, you will start to identify recurring concepts. ‘A list of reserved words for Java is shown in Unit 7: Mobile Apps Development. Identifiers ‘An identifier is a programmer-friendly name which nts a quantity stored in the computer's RAM. represe! identifier are used in programs, but some of Many types of the most common types are: > aconstant - this is an identifier representing a value that ‘will not change while the program is running > a variable - this is an identifier representing a value that ge while the program is running Jerson logs into a program, their ame and password would typically be stored as variables, pe these details would be different for each different tier, However, a program calculating the price ofanew television in ashop's electronic til would need to ensure that the current rate of value added tax (VAT) is added to the price. This value would nat change for every sale, so it could be set asa constant. leclare) a constant or a variable, you mming language with two things: may chan For example, when a p' Inorder to create (or de must provide the prograr > aname ia ae. yures801g SuYou should always choose a sensible and meaningful Name. For example, a good variable name for storing the user's name would be ‘username’, Some names cannot be used because they are reserved by the language for & Particular use, typically because they are a command word. These reserved words vary between different Programming languages, so be careful There are many different naming conventions used in Programming. CamelCase or snake_case are perhaps the two most popular in modern programming, for example if Wwe want to store a user's age in years in C#: camelCase int userAge; The first word is in lower case. The initial letter of each successive word is capitalised snake_case intuser_age; All words are in lower case. Words are linked with an underscore symbol. Most programming languages also contain the concept of local and global variables. The easiest way to think about this is to remember that global variables can be used anywhere in your program code. Local variables are limited to being used in the block of code (e.g. a function) in which they are declared. This also applies to mobile apps development, as shown in Unit 7: Mobile Apps Development. Data types Almost all programming languages support the concept of data types. A data type is used to define what kind of value a variable or constant can store, what operations can be performed upon it and its behaviour within the program. Most programming languages offer many different data types for the programmer to use. The most common data types used are: > character - this stores a single character (a character isa letter of the alphabet, a digit, a blank space or a punctuation mark) > string - this stores a collection of characters > integer - this stores a whole number (ie. a number without decimal places) > real (sometimes called floating point) - this stores a number with decimal places Boolean - this is a logical value which stores either true (1) or false (0). pecause these data types are quite common, iis possible to compare their implementation in q iffere rt programming languages, as shown in Table 4.4 Some languages are said to be strongly typed while others are weakly (or loosely) typed, This makes a fundamental difference to the formality of the programming language. Strongly typed programming languages require data and data types to be consisteny when used. For example, in Java, ifa variable has been declared an integer, it should only be used to store integer variables, otherwise errors may occur. This is because Java is a strongly typed language. However, C is loosely typed: it will implicitly convert the data to the correct data type that the variable expects without the programmer needing to add any specific code to do so. This is a convenient feature, but it can lead to unexpected results. Be careful when dealing with data types. Always think about the data you want to store and which data type is the most appropriate to use. Getting the data type wrong can lead to problems such as truncation of decimal places and incorrect rounding, both of which could be disastrous in an application dealing with money, Statements Statements are the core aspect of many programming languages. They define the basic actions that can be performed and often combine a number of language constructs. Common examples of basic statement types with direct language equivalents are shown in Table 4.5. There ar® many similarities between them. For example, they 3 are very case-sensitive, but only some of them requl® semi-colons to mark the end of a statement. Case-sensitive - when a programming langu26® recognises the difference between upper-case 2" lower-case characters, such as ‘a’ and ‘A. For exam| if command word is expected in lower case, 47 | yee pleJe 4A: Variable declarations using different dat ral ata types in different programming languages 3 Pr rogramming language implementation in... 2 aan Cre Microsoft Visual Basic NET 3. ; char initials initial a har username | 201 201 string usernames Cee int age: int ages a float price: Agen oat. prices Tok Not available bool valid: Din wail Boolea Statement types, their purposes and expressions in diferent languages : Purpose Store a value in an identifier (variable or constant. Microsoft c# coe Ruby | userage = 177 userage = 177 userage = 17 “Allow input from the user, typically from the keyboard or a file. Microsoft Ci coe med userName = Console.ReadLine()i cin >> userName; userName = inter, a speaker, a file and so on. Microsoft C# Cee Ruby cout << “Hello”: puts “Hello” Generate output for the user, typically to the screen, a pr Console.WriteLine ("Hello"); control programs are typically built using a combination of smming building blocks known as contro structures, These control selection and iteration. The C# code for r, none missed, none repeated. ; fas ee ‘supplied condition which is evaluated to selections and iterations Oa is very similar to the i iti found intl a condition is no Java examples Kg in Unit 7: Mobile Apps Development. of times, typicalh 235Care should be taken when moving between languages. For example, in some languages (e.g, Visual Basic LNET) the single «sign is used to test for equality yy, in other languages Java, C, C++, C#, PHP) the ==" is used instead, Take the time p® investigate the different types of operators available in your target prograrnmn, > language, ; if (customerorder > 50 && deliveryDistance < 25) { fonsole.Writebine("You have qualified for free shippiy : : ; > Figure 4.10; #if statement using a logical And (8) operator ‘A detailed list of common Java operators (including logical types) is provided in >) Unit 7: Mobile Apps Development. Subroutines, functions and procedures Subroutines, functions and procedures are terms used in procedural programming where code is split into a number of different modules. Each module may be called a subroutine, function or procedure depending on the programming language used Each module is responsible for performing a single task and is typically somewhere between 5 and 50 lines of code in length. The C# code shown in Figure 4.11 demonstrates the use of a programmer-defined function to calculate the area of a circle when given a specific radius. const float PI = 3.14£; static void Main(string[] args) t float radius; float area; radius = 10.0£; area = calcAreaCircle(radius); // function call e.WriteLine("Area of circle is {0} -ReadKey(); > area); //fanction declaration public static float calcAreaCircle (float radius) { return PI “ radius * radius; , > Figure 4.11: Code to calculate the area ofa circle given the radius 5 Programmingeof these Modules Means that code sews tend ode writer 5 10 be casi eee ee ny C€0 Usually be reused three OMe read and Ear Nich metas lvided and worked on iy lel solutions and ‘anbereduced "* Tip sumest all programming languages have ir hen solving canuse when solving complex problems. theses common but crucial tasks on data, such as formatter oBranamer to perfor Jength of as : Data structures _adata structure is a programming techni que used to collect Tf inaformal atl which helps the data to be processed Se Giteten ae aualbilty of certain data structures vary between different Poaeete lies = many are very common. These common data structures include string, mere enc two-dimensional), stack, queue and record, Bae an Sometimes itis possible to program more efficiently through the selection and use ‘ofspecific data structures, especially when this is combined with iteration control structures (loops). Software developers become familiar with different data structures asthey learn about different programming languages. Here are some of the most common data structures. String (or text) Thisis a data structure which is used to store a collection of characters with one character minimally requiring one byte of RAM. Strings may be ‘fixed length’ {for example, only containing 10 characters), Alternatively, they can use a special ‘terminator’ character to mark their end. This may mean that a string requires an ‘additional character to be included, but it allows them to have flexible lengths. fach individual character in a string can be accessed by using its positional index. For example, in Table 4.6, Planet(2] is'r This example is demonstrated in Ct strings in Figure 4.12. 3 | String Planet; Planet); — ing is (0)", le.WriteLine ("whole string Planet (2]) le.WriteLine("3rd character is (0}". ‘Working with C# strings ters to simulate a string, al array of charac 2 eis very similar. use a static one-dimension ae ific string data type. However. imple text entered by the used to store simp| reece more Co! ‘ may aso be used to enter Move rm substring Se carve ‘Bar isa substring of Earth’ it ae user, such as a ¢tfor processing, such used to | SumuesBorg > Table 4.6: Each character in a string has a positional index PlanetArray (one-dimensional) Traditionally, this isa static data structure, which means that it has a fixed size. However, modern programming languages are generally more flexible and allow an array be resized. yy to Typically an array can only store one type of data. Any type of data, such as integers, characters and Booleans, is acceptable. If we wanted to store seven daily maximum temperatures in degrees Celsius for a local weather station, we would create an array of seven decimal numbers, as shown in Table 47. > Table 4.7: One-dimensional array of seven decimal numbers ‘Temperatures 0 1 z a 4 5 6 1250 1045 1230 14.60 1770 11.20 12.50 This appears to be similar to a string. In fact, you can think of a string as an array of characters. As with a string, itis possible to access individual elements or items in the array by using the required index. For example, Temperatures{4] is 1770. Figure 4.13 demonstrates the creation and access of this simple one-dimensional array in CF Array (two-dimensional) ‘Atwo-dimensional array is similar to a one-dimensional array, but it can store multiple rows of data. Imagine that we still wanted to store seven daily maximum (//exeate ray float[] temperatur | //initialise each element = new float(7]; | temperature[0] = 12-50f; | cemperature[1] = 10.45£; tenperature(2] = 12-30; | cemperature[3] = 14-60£; | eemperature[4] = 17 -70£; | cemperature(5] = 11.208; | temperaturel6] = 12.508; | /Jaelect Thursday’ ® and output it | console Write Jiweit for keypress to continue ReadLine (); whine ("Temperature on Thursday is {0} degrees Cc", temper n degrees Celsius for local weather stay put that we needed 10 do this over three consecutive Ggaelcsitn this case, We Would ate area dimensional by three decimal numbers, as shown in temperatures i" array of seven Table 4.8. > Table 4.8: Two-dimensional acray Temperatures TT eee 4750 1045 1230 1460 17.70 11.20 1259 11,00 10.00 2000 27.00 1400 1559 1400 1450 1460 1230 1400 1460 0 1 1222 2 13.00 possible to access individual elements ay by using both indices, for example is the value found where column 4 and As before, or items in the arr Temperaturest4](1] row 1 meet: 21.00. dices may vary between different | programming languages. The general rules thatthe Blement access order will reflect the declaration order of the array, ie. you could not access an elementin Temperature [14] as these indices do not reflect the declaration order of the array. The actual order of in« {tis possible to use higher orders of dimensions For example, a three-dimensional array could be used '0 store the twenty-one temperatures that we have stored fo each of five different weather stations he array of decimal temperatures ature (4)!Le Tae i sgplitand joined. In some languages, th an bes? i. this is called explodin ca en languages where strings are ston ygartays and arrays. languag rings are stored as arrays of characters, the Suwuesdor4 | “rs $e tings and concatenation of iferentsringsare praca uses of pease operation. See String handling for more on. este 1g handling for m« substring extraction and ancatenation re (uro) Hexnown asa LIFO data structure, Ithas two basic operations: Push and Pull asta known as Push and Pop). LiFO - this stands for ‘ast in, first out’ and it describes how data is treated in some data structures, It means that the last item of data pushed on is sea vital partof any computer platforms operating system, and they are Seno ol a programmer to use when developing solutions tacks ae actualy viewed vertically. as in Figure 14, Pull C 4 sui D also the first item of data that ff. stack Top Stack Top may be pulled back of Stack Top Stack Top You can see a stack operation in C# in Figure 4.15. > Figure 4.14: Stack operations using System; using System.Collections; namespace stack { class Program { static void Main(string[] args) { char data; //single item of stack data Stack st = new Stack(); | //our stack \ //pash onto stack st.Push('A') st.Push("B") st.Push('C'); //show the stack Console.Writebine ("Current stack: "); foreach (char ch in st) | { Console.Writebine (ch)? t /iremove from stack top - it should be data = (char)st-Pop(); Console.WriteLine ("The popped value: {0}", data);wash onto stack again st.Push('D') //show the cl Sonsole.Writebine ("Current foreach (char ch in st) { mi Console.WriteLine (ch) 7 + J/wait for keypress to continue Console.ReadRey (); > Figure 4.15: Stack operation in C# Unlike an array, where elements may be accessed in any order, a stack can only be ‘accessed in a last in, first out manner. This can be particularly useful when processing recursive algorithms. Stacks are often included in a programming language's library complete with the necessary methods to process them. Queue (FIFO) In contrast to a stack, a simple queue is known as a FIFO data structure and has two basic operations: > add (to tail of queue) or ‘enqueue’ > remove (from head of queue) or ‘dequeue. ‘Only data at the head of the queue can be accessed and removed. Recursive algorithms - a piece of programming code that executes itself repeatedly until it reaches an end condition where the calculated result can be returned FIFO - this stands for ‘frst in, first out. It means that the first item of data added is also the first item of data that may be removed, Like stacks, queues are a vital part of any computer platform's operating system For example, you may be familiar with the concept of a printer queue. For a programmer, they are an excellent way of managing task processing, Queues are conceptually viewed horizontally as shown in Figure 4.16. Head Eee << a od i Figure 4.16: Queue operations> gre 417 demonstrates the creation and access ofa simple queue tein Co, going Systems Geing System-Collections; (eing system-Ling; (sing System. Text; SunuuesBoig class Program tati id Main(stri . atic void Main(string[] args) cha: a; f char data; //single item of queue data Queue q = new Queue(); //our queue J/add to queue q-Enqueue ("A") q.Enqueue (‘5") q-Enqueue(*C"); //sbow the queue Console.Writebine("Current queue: "); foreach (char ch in q) Console.Write(ch +" "); ‘//xemove from head - it should be ‘A’ ta = (char)q-Dequeue(); 10)", data); Console.Writebine ("the removed value: to queue again e('D');ae A record of student details Student StudentiD. Forename Surname Age Enrolled 2001 Preston Myla a True In this example, ‘studentiD’ and ‘Age’ are stored as integers, ‘Forename’ and Surn,, are strings and ‘Enrolled’ is a Boolean. A C# implementation of a simple recorg structure is shown in Figure 4.18. using system; using System.ting; using System.text; — Consoleapplication! public class teststry { //exreate the record structure struct Student { public int student1p; | public string surname; public string Forename; public int age; public bool Enrolled; public static void Main(string[] args) | 1 Student mystudent; //declare mystudent of type Student structure //initialise the elements in the record structure mystudent.StudentID = 2001; | mystudent.Surname = "Preston"; | mystudent. Forename = "Myla"; mystudent.Age = 21; | mystudent.Enrolled = true; //print the data in the record Console.Writebine ("ID | Console.WriteLine ("Surname | Console.WriteLine ("Firstname : | Console .WriteLine ("Age | Console.WriteLine ("Enrolled structure mystudent. StudentID) ; mystudent. Surname) ; mystudent. Forename) ; mystudent age) ; mystudent .Enrolled) ; //wait for a keypress to continue Console.ReadRey()7 > igure 4.16: C¥ simple record structure sing struct Programming Bicalcreate an array of structures to store mult ecord (or struct!) can be seen as the a binary data file, iple instances of a record 80 basis for sim 0 peason at pase table or iple record storage are simply a collection of ch ; ask is commonly known by ae at need tobe often need to perform certain operations on sti iene specialist library functions to help. Here are ane ar most high-level Bie sarnples showing theie implementation, Sinilarstine a tasks, with ‘other programming languages. 1g functions. th of a string in characters e length property of the ‘month’ string object is used to access the ‘of characters. In this example, the string is the word January: ut will be ‘Character 3 of January is u’ This is because ‘u’ is the 3, The string starts with a Jin position 0. 13 cer {0} of {1} is (2)"s n is ua’ Thisis output because we start evexaract the next2 characters including he whichLetter, month, singleletter); |rings: January’ and has 31 days. The outp, joining two stl Bore ee ne days, Thisis output because we use the oper, {Joined string is January has 31 days re available in Ci, but this i join the two strings together. Other techniques are ut this isp the simplest to use. string month = "January"s string saying =” has 31 days." string combined; combined = month + sayings one emeinuerestine(raoined string is {0}", conbined)s > Figure 4.22 File handling Data storage is a key aspect of modern programming, The ability to open data fies for reading (.e. geting data from afile) and writing (i.e. sending data to afi) na programming language is essential. In order to use a file, it must be opened, and when you have finished it should be closed. Some programming languages require special Commands to perform these operations. For example, C uses fopen() and flose( ‘Asimple form of file handling is the ability o read data from an ASCII or text file. Ths can be achieved in Microsoft C# using a few simple constructs, as shown in Figure 423, using System; using System.10; using System.Collections.Generic; using System.Ling; using System.Text; namespace ConsoleApplication! { class Program { static void Main(string[] args) | t | //Jexception handling cry | t // attempt to read the named file using (StreamReader file = new StreamReader("c:/customer-txt")) { string line; //stores a single line of text read from the * //loop which continues to read a line of rea ne of text until //end of file (EOF) is reached a while ((line = file.Readbine()) null) { //outpat the line of text read Console.WriteLine (line) ; , : } catch (Exception e) | ——— Bho iith ie ee . Aohow UROL the oo: OF monnn Writebine ("9 ia srry, Writebine (®. Message) — +ReadKey (); CH file handling demonstrating the reading of an ASCH/Aext fle simple Cl While’ loop is used to iterate through each line of the As the line of text is read, its output to the screen, Exception to ensure that the program does not fatally crash if the named text file uMMINg languages (Such as Microsoft C#, PHP, Ruby and so on) tion to relational databases such as Microsoft SQL and MySQL complex data handling, monly found in form-based applications, such as those which ce (GU!) elements to allow the user to interact with the to create simple event-handling applications that work in the ‘pased on the delegate Key terms ) Graphical user interface (GU!) - a modern user interface comprised of windows and icons which is controlled by a mouse and a cursor/pointer. Examples include Microsoft Windows 10 or Apple OS X. Command line interface (CLI) - an older style of text- based user interface that is still in use. Users interact with the computer via commands entered from the keyboard. Examples include Microsoft Command Prompt or a Linux terminal te, needed to define an event inside a class woid SecondHandler (myClock clock, EventArgs evt); AQ ynwwesGo14//Subscriber - accepts the event and provides the event handler (showc) public class Listener { Public void Subscribe (myClock clock) { Glock.second += new myClock.SecondHandlex (showClock) + } /7event Handler - shows the clock in the top-left corner of the sc: Private void showClock(myClock clock, EventArgs evt) | { Console.CursorLeft _; Console.cursorfop = 1; | DateTime now = DateTime.Now; | Console.Writebine (now) ; | } } //class used to test the event-driven clock class Test { static void Main() { //create a new clock object myClock clock = new myClock(); //ereate a new listener object Listener myEventListener = new Listener(); //link the event and the handler myEventListener. Subscribe (clock) ; //start the clock ticking... clock. Start (); > Figure 4.26: Using C# console events to create a real-time clock In this example, a one-second event is used to provide a real-time clock on the console screen. This is an example of C#’s Publisher-Subscriber model. The Publish" defines the event and the delegate. Once the Publisher invokes or triggers the eve"" other objects in the program such as the Subscriber are notified. The Subscribe! then accepts the event and provides an appropriate event handler. In this case, the appropriate event handler is a function which displays the clock in the top-left of the screen. corner Form-based event handling plays a significant role in developing mobile app®: demonstrated in Unit 7: Mobile Anne ana ee nepocumentation of code code should always be documented to good sti it Peake the code more readable Bi landards. Doing this will: te pother programmers understand the code when programmers are debugging the code reith maintenance of the program code, especially if this wil ensener y if this will be performed by can use various techniques to document their code. These techniques gcumenting identifiers - this means using meaningful names which explain the se (and sometimes the data type) of the value represented by the identi ing identifier names can vary greatly between programming ses, Some identifiers can only use certain characters (e.g. no spaces) or with certain characters (e.g. digits 0-9). In addition, stylistic advice is eg. do not abbreviate or use acronyms when naming identifiers. comments - these are short comments that explain the purpose of aline comments - these are longer comments that explain the purpose of mplex section of code or preface a separate section of code, such as a procedure or class ts - this means replacing multiple insta etc) scattered throughout a program wit ied at a single point in the program code. nces of fixed ‘literal’ values ith named identifiers which ws these most common techniques in Cf. tation of code in Microsoft C# WN i [iio ce int userAge; fart ‘ /7/ stores user's age This sec age when entered. XL ifiers. ds for naming ident containing * é tion of code validates the user’s Tools are also available which generate HTML documentation directly from comments placed in SurwwreisoigPrinciples of logic applied to program design ee logic is the set of principles beneath the as ements ofa program or system that lows aa eect nce to function, Successful program = pests a the application of simple logic. This is aes . than the ability to think ina particular cea ing language, Being able to hink logically will help var lata correctly, form complex conditions which le you to test data appropriately and build powerful algorithms to solve even the most complex problems. The principles of logic used in computing include mathematical logic, iterations, propositional logic and the use of sets, These concepts help programmers to understand problems more fully and build the logic that is incorporated into their programs. Mathematical logic Mathematical logic can be applied to help developers understand and accurately describe the basic facts in a problem and their relationships to one another. For example, inference is the process used to reach a logical conclusion from premises (situations) which are thought or known to be true. This can be seen in the following example. > Premise: All meat comes from animals. This is true. > Premise: Lamb comes from sheep. This is true. > Inference: Therefore lamb comes from animals This inference is true because sheep are animals. False inferences are called fallacies. -e is important when using Jog (Programming bases which can be The concept and use of inferenc programming languages such as Pro| in Logic) to build simple knowledge queried to reveal new facts. Other logical concepts can also be considered For example, consistency tries to see if a statement (and its opposite) are both true in order to determine whether there are contradictions in the statement. Iteration tion occurs when a computational procedure is Iterat previous application. applied to the result of Completeness Completeness is a logical concept that states that you can ‘prove' anything that is correct. Here is a simple assertion which uses the following symbols: > © (the Greek letter sigma) > @(theGreekletterphi) > & (turnstile) means ‘proves’ or ‘yields en —— Writing the assertion’: +! means from ¥, | kngy More simply, it means that 3: proves’ "a There are many different forms of completeness, such functional and semantic. In programming, complet, can be used to prove whether algorithms would successfully work given certain rules, goals and logic Truth tables You can verify simple algorithmic logic through the use oy truth tables. For example, a customer can only og in aystem if they have a valid username (U) and passyorg {Py and have not been locked out (0) within thelas 30. minutes. ina truth table for this example, 1 is used to represent ‘true’, while ‘0’ means false. The '’ symbol means logical ‘and" The bar above the ‘0’ means logical ‘not: This means that we can express this logical expression as L= (UP). Oo, ‘successful login = username and password and not locked out! After the expression is evaluated, we can prove the only combination which is valid, as shown in Table 41), The resulting expression could be converted to any target programming language, as its underlying logic is proven by the truth table. > Table 4.11:A truth table showing possible combinations an the only valid permutation (row in bold) u Pp oO fE (u.P).0 =lo|—|ol|-|o|-|o Propositional logic Propositional logic is based on the simple concer sentence can be considered to be either true o false not both true and false. Consider these examples. > The Sun is hot. > Two plus three is six pt that a but itions and they have atuth ‘example is ue ynd example > is five, not basic Both sentences are proposi value of either ‘true’ or ‘false’. The first because the Sun is indeed hot. The seco! a false proposition, because two plus three six. These types of simple sentences are known # propositionssore copies propositions can be created using There are five basic connective ’s. Each one co symbol rmjasshewninthe hose onae N Vv > AND >oR imply) > IF_AND_ONLY IF nective symbols allow us to represent ions in a very mathematical fashion. the expression, ‘if | have money or a ticket cha film’ could be expressed as: (M V1) er words: F is true if M or Tis true. ple, the expression, ‘If | have no money, is due, a bank fine must occur’ could “= M—> (DD —> BF): In other words: if DD is true, BF must be true. le logic statements use a formal tation, itis possible to test their validity code is produced. Its also possible al logic to derive new knowledge from ‘called propositional dynamic logic (POL) rate the function of algorithms. PDL is ‘the states and the events of dynamic ing programs) in mathematically ne of its most important features is ether completed algorithms can esired state: that is, calculate the organise data and define een different sets of data. search and filter potentially amming languages have data «functionality, and this logic ple with For example, you may have two groups of Peo Set Ais the different access rights in a particular program Admin group, which contains John, Ahmed and Jo. This can be expressed as Set A = (John, Ahmed, Jo). Set B is the Finance group, which contains Claire, Jo, Niamh and Phil This can be expressed as Set 8 - (Claire, Jo, Niamh, Phill We can represent these sets as a Venn diagram, as shown in Figure 4.25. > Figure 4.25: Venn diagram showing two sets of people There is a particular function in the program that can only be accessed by administrators (members of the Admin group) who work in the Finance department (members of the Finance Group). Looking at Figure 4.25, we can easily see that the only user who exists in both sets is Jo. This means that only Jo has access to this function. Quality of software applications When faced with the same problem, different programmers can arrive at very different solutions. This usually occurs because problem solving is a very personal process and most programming languages have enough flexibility to permit a variety of solutions to the same problem. However, the actual design and implementation of the software solution has a direct impact on its overall quality The quality of a software solution is judged by assessing its efficiency or performance, maintainability, portability, reliability, robustness and usability in small groups, share your experiences of having roblems with unreliable software applications bo you think that these problems could have been prevented? Why do you think these problems were rot fixed before the application was released? Efficiency or performance The performance of an application is usualy assessed by measuring the system resources consumed by the program. For example, CPU clock cycles, processor time, ilocated RAM and the rate at which storage media is oad from and written to. A complex process may be verya CPU intensive. It may be possible to revise the program code to be more econ, which, in turn, may improve performance (work faster) and use fewer resource and so on). This type of revision is common in programs which rely on speed... as videogame programming (where screen frame rates can suffer due to inetficiers coding) or talking to external devices in real-time systems where timing issues critical, for example traffic control systems or missile guidance systems, Maintainability Maintainability is the ease with which a program can be modified by present or futy, developers in order to carry out corrective, perfective or adaptive maintenance For example, code that is written in a maintainable way will be easier to adapt or modify, and this will save both development time and money. There is always a trade off to be made between writing code efficiently to reduce initial development costs and considering how long future maintenance will take. Corrective maintenance - fixing an error or bug that has been identified, ) Perfective maintenance - making an improvement to a program that enhances its performance Adaptive maintenance - making modifications to a program, by adding, changing or removing functionality to reflect changing needs. Portability Portability is a measure of the number of different computer platforms that the source code can target, such as hardware, operating systems and so on. Some programming languages, such as C, are particularly portable, as they have compilers that translate the existing code to the required target machine code on many different platforms. For example, a program written using Microsoft Visual Basic INET may limit its execution to a Microsoft operating system, while programs written in C can be ported for use in Microsoft or Linux operating systems with few platform-specific code changes. Reliability The reliability of an application is determined by the overall accuracy and the consistency of its outputs across multiple runs. Consistency is particularly important in reliability testing. A program may calculate answers very accurately, but, ifitcannot replicate this every single time it runs, itis not considered to be reliable. Thiss eve more important in environments where people's safety depends on the reliabilly o1® program, such as in safety systems in a power station or collision detection in aircrat traffic control systems. We have already seen a couple of examples where reliability is crucial. In pals discuss and write down three more examples of situations in which a program Ns to be completely reliable. Robustness Robustness is a measure of the program's code quality, particularly when the PO# is tested to ensure that extreme and erroneous data can be processed without ca a anabil it ve out the desi miejgn many times before being full Close the book and m: How does the type of, solution? ment practice 4.1 school is launching a campaign to promote ming. You have been asked to write a student- blog post which explains and promotes the tion of computational thinking skills when solving ms and developing software applications the blog post as helpful as possible for your dience, you should explain the principles uter programming, especially how different an be used to create solutions. You should also basic principles of software design and how plied to produce the high-quality software that audience needs and uses on a daily basis. Your blog post by analysing and evaluating the Computational thinking on software design and Of the software produced. ‘are writing your blog post, think carefully about Audience and their level of knowledge about + Consider how you will explain technical 8M audience that may contain both experts ake alist of the features of com, the principles of computer programming, [Key term ) Assistive technologies ~ hardware or software designed to assist users with a specific disability or special need, such as screen readers for users with visual impairments or learning disabilities. find iputational thinking skills and Programming language affect the development of a software Plan + What is the task? What am I being asked to do? How confident do | feel in my own ability to ‘complete this task? Are there any areas | think | may struggle with? * Amusing appropriate language for the target audience? + Do understand the difference betwes and evaluation? Do + I know what | am doing and what | want to achi en analysis e. lean identify where | have gone wrong and adjust my thinking or approach to get myself back on course. Review + I-can explain what the task was and how | approached it. + lean explain how | would approach the more difficult elements differently next time ___ would do differently). Sunuues8o1ging an appropriate recipe to follow ating the correct quantity of ingredients for the recipe and the family size ing appropriate ingredients ing the ingredients the ingredients in the right order king the ingredients using the correct methods the ingredients for the correct duration igthe meal the meal on plates, ready to be eaten, pis way, a single problem (making a family meal) can be decomposed into at sub-tasks, each of which could be further decomposed, if necessary, until Tequired to solve each task are relatively straightforward to understand ling, decomposition involves the following four stages. stage, you will list problems and processes concisely, using language that es the problem's source. For example, if you are dealing with a financial sstage, you will decompose complex problems and processes into separate Bs which, when taken together, can be reassembled correctly. There is no specific o the number of steps included or of levels to which you may decompose. llsimply continue to decompose each step until you reach an acceptable level tanding, For example, the problem of calculating someone's net pay (salary js deducted) is decomposed into several steps in Figure 4.2. SuyunusesS01g 223
A new paragraph< > graph