A+ will be down for a version upgrade on Thursday October 17th 2024 at 09:00-12:00.
This course has already ended.

The latest instance of the course can be found at: O1: 2024

Luet oppimateriaalin englanninkielistä versiota. Mainitsit kuitenkin taustakyselyssä osaavasi suomea. Siksi suosittelemme, että käytät suomenkielistä versiota, joka on testatumpi ja hieman laajempi ja muutenkin mukava.

Suomenkielinen materiaali kyllä esittelee englanninkielisetkin termit.

Kieli vaihtuu A+:n sivujen yläreunan painikkeesta. Tai tästä: Vaihda suomeksi.


Chapter 1.2: Introduction to Programming

About This Page

Questions Answered: What are programs and programming like? Where do I write my program code? How do I run a program I’ve written? How do I submit programming assignments for assessment?

Topics: Basic concepts and characteristics of programming. The tools of a programmer: programming languages, program code, programming in an IDE, packages.

What Will I Do? Read. Experiment with programming tools. Modify given application programs.

Rough Estimate of Workload:? One and a half hours. Could be more if you also install the programming environment onto your own computer.

Points Available: A12.

Related Modules: GoodStuff (new), O1Library (new), Pong (new).

../_images/person01.png

Creating and Running Programs

A traditional way to describe programming is to compare it to cooking. Here is that comparison in interactive form:

Running a program

../_images/computer_as_cook.png

The programmer defines how they want the computer to act as it runs the program. For instance, if the programmer is writing an application for handling course enrollments at a university, they might include an instruction to this effect: “Whenever the user clicks this particular button, add the user to the list of people enrolled in the course.”

The user of an application program has access to a copy of the program, perhaps stored on the user’s own computer. When the user starts up the program, the program is run (or executed; ajaa, suorittaa) and the computer follows the instructions that are set down in the program.

Consider an example. A user clicks an icon to tell the operating system that they wish to launch a word-processing application. The computer will now act as defined in the chosen application program. Assuming the programmers who created the application have done their job well, what happens next is what the user wants: a new window pops up onscreen and provides useful word-processing functionality.

Does the user really have a copy of each application?

The above description of running programs in a computer is a traditional one. It still applies to many present-day situations, and it’s sufficient for our purposes in O1. However, developments in computing have affected how some programs are run.

Optional exercise: with the help of the internet, find out what the following terms mean: web application (web-sovellus), cloud computing (pilvilaskenta), Software as a Service.

Programming languages

The processor, which causes the computer’s behavior, does exactly what it’s instructed to do, and nothing else. It executes commands one by one, in order. Unlike the knowledgeable cook who reads a recipe, the processor comprehends nothing about the purpose of each command within the overall program. It doesn’t know how to interpret meanings from context, how to conjecture, or how to adjust to new situations. Ultimately, the computer is stupid. It is, however, fast and precise and has a reliable memory.

As we write a program, we need to describe, literally and in great detail, what we want the computer to do when the program is run. For that, we need instructions that are precise and unambiguous. Natural human language is neither precise nor unambiguous and isn’t well suited for programming: consider expressions such as “add salt to taste” or “until it has a beautiful brown crust”.

Programs are written in a programming language (ohjelmointikieli). Programming languages are formal and allow only a limited set of well-defined words and expressions. Any acceptable expression in a programming language has a precise meaning. A perhaps useful point of comparison is the molecular formulas used in chemistry, which are likewise governed by precise rules; those formulas are, however, rather simpler than most programming languages.

A huge number of programming languages have been developed over the past several decades. Wikipedia, for instance, has a list thiis long, and even that is by no means comprehensive.

Some programming languages are better suited for some purposes, others for other purposes. Some are intended as general-purpose tools; others have a more specific raison d’etre. Some have been consigned to the trash heap of history; others march on from one decade to the next. New languages continue to be created, as do new versions of existing languages.

../_images/ohjelmointikieliä.png

The names of some programming languages. We’ll be using one of them.

../_images/scala_logo.png

The Scala logo. In Italian, a staircase is called scala.

Scala, a programming language

In this course, we’ll use a modern and versatile programming language by the name of Scala. As you use Scala, you’ll learn general programming concepts that you can also apply when programming in other languages. An experienced programmer can pick up new programming languages relatively quickly.

Just as an example of what the language looks like, here are three commands written in Scala. The theme for these commands is a simple (and imaginary) accounting application that keeps track of employment information.

val hiredPerson = Employee("Sophie Student", 1992, 3200.0)
hiredPerson.workingTime = 0.5
hiredPerson.raiseSalary(1.2)

At this point, you don’t have to know what this example code means precisely. But you can read a short commentary on it. Move the mouse cursor over the explanations in the green boxes and the associated bits of the Scala example will be highlighted. Try it! You can also click the explanations to “lock” a highlight.

The first line instructs the computer to record information about a new employee in its memory. An employee has a name, a year of birth, and a monthly salary.

The second line marks the person as a part-time employee: their working hours are set to be 0.5; that is, 50 percent.

The third line records a 20-percent raise for the employee.

Programmers are free to name many of the concepts and entities in their programs. Some of the words in this example are specific to this program and have been chosen by the programmer using English words as a basis. The programmer could just as well have used words in Finnish or Latin here without affecting what the program does.

Some of the words are part of the Scala language itself and have not been chosen by the programmer. Scala’s vocabulary is based on English words; val is short for “value”.

You’ll learn more and more Scala throughout O1. Nevertheless, we won’t be covering all aspects of this multifaceted language in one course. Scala is also used in multiple other courses at Aalto and in many contexts outside the academic world.

We use version 3 of the language. (More precisely, we use Scala 3’s subversion 3.2). Scala 3 was released in 2021 and differs from the older Scala 2, so if you study from other web sites or external sources, keep an eye on version numbers.

A program — is what exactly?

Right from the start, it’s good to notice that the word “program” refers to two separate things:

  1. the program text, known as the program code (ohjelmakoodi), which defines a sequence of instructions for a computer to follow; and

  2. a program run: the things that happen as a computer executes the instructions in the program code.

This is why you can say of a program you wrote “My program has 15,000 lines of program code.” as well as “Go ahead and click that button, and my program will send the results to the printer.”

To rephrase the above, a program is, on the one hand, a static (staattinen), passive piece of writing on what a computer should do. On the other hand, a program is a dynamic (dynaaminen), active process that acts within a computer and may interact with its users. A similar duality exists in many programming concepts as well, and we’ll be returning to this theme multiple times as we go.

Inside and Outside an Application Program

../_images/app_components-en.png

An end user and an app’s components.

Application programs have two main components:

  • A user interface or UI (käyttöliittymä), which is the part of the program that is visible or otherwise observable by the user and that the user may interact with. Many modern applications have a graphical user interface (GUI) that consists of windows, buttons, and the like.

  • A model of the program’s domain: what the program is about. This is the program’s “guts”; it’s what defines the program’s internal logic. For instance, the domain model of a word-processing application defines how proof-reading works and how documents are internally structured as paragraphs, headings, etc.

An application’s user will usually be familiar only with how to use the app (if that). In contrast, the programmer needs to be able to describe both the user interface and the program’s internals. Moreover, unlike the user, the programmer needs manipulate both the program’s dynamic behavior and its static representation as program code.

In the remainder of this chapter, we’ll explore two existing application programs. We’ll look at them from the inside as well as the outside. As we do so, you’ll get to grab your programmer’s toolbox.

The Tools of Programming

Programmers routinely use auxiliary programs previously created by other programmers, which help them create new programs. For instance:

  • Program code is written and saved in files with an editor program. (More about that shortly.)

  • A compiler (kääntäjä) is a program for automatically converting program code written by a human into a form that’s more readily executable by a computer. (More on that in Chapter 5.4.)

  • A debugger helps the programmer monitor a program’s behavior as the program is being run. This is particularly useful when looking for errors and when learning to program.

  • A complex piece of software may be easier to develop if the programmer or team uses version control (versionhallinta). (More on that in O1’s follow-on courses.)

  • Virtual machines are commonly used as an enabler when running programs. (More on that in Chapter 5.4.)

Integrated Development Environments (IDEs)

Editor
Compiler
Virtual Machine
Debugger
Version Control
Debugger
Compiler
Editor
Version Control
Virtual Machine

Integrated or separated?

A programmer may use a standalone utility for each need such as editing or debugging. The alternative is to use an integrated development environment (IDE). An IDE provides a combination of tools for authoring software and helps the programmer divide their work in modules, which is often convenient.

In O1, we recommend that you use an IDE. This ebook text assumes that you use one particular IDE:

IntelliJ IDEA

../_images/ij_logo.png

The IntelliJ logo.

O1’s official programming toolkit is an IDE called IntelliJ IDEA, or just IntelliJ or IJ for short.

All in all, IntelliJ is versatile and complex, as IDEs tend to be. However, we’ll use only a small subset of IntelliJ’s functionality.

IntelliJ can be further extended with various plugins. We use its Scala plugin and a custom plugin named A+ Courses, which makes it easier for you to access our programming assignments and submit them to A+ (among other conveniences).

We use version Community Edition 2023.2 of IntelliJ. The Community Edition and the plugins are free to install and use.

Local students at Aalto may use IntelliJ on Aalto IT’s Linux workstations, which have the right version of IntelliJ installed.

This isn’t the only way

Some students in O1 already know programming tools that they’d prefer to keep using. Even though we officially use IntelliJ, you’re free to use other tools instead. However, you choose to do so at your own risk, counting on your own ability to work out any kinks that may arise. O1’s staff will probably not be able to assist you with unofficial tools. Moreover, by not using the A+ Courses plugin for IntelliJ, you will make it less convenient for yourself to access and submit assignments.

IntelliJ at Aalto

The right version of IntelliJ has been installed on Aalto IT’s Linux workstations. These workstations are O1’s official working environment.

Please note that at least most of Aalto’s Windows workstations do not have the necessary tools installed. (If you do wish to use IntelliJ on Aalto’s Windows computers, you can try the OOD environment that works in a web browser; see below.)

Installing IntelliJ on Your Own Computer

If you want to program on your personal computer, you’ll need to install IntelliJ and the plugins. We have a separate page that explains how to do that. To ensure that you install the right versions, follow the instructions on that page.

You should read the rest of this ebook on a computer with IntelliJ installed.

If you’re using IntelliJ on your own computer and have already installed it as per the instructions linked above, you can skip the section immediately below and continue from Programs in This Ebook, further below.

An alternative: IntelliJ in your browser, no installation

Aalto is experimenting with a virtual environment called Open OnDemand (OOD), which you can access with your web browser and which has IntelliJ pre-installed. This enables you to use IntelliJ over the net instead of installing it locally on your own computer. Or maybe you just want to try it despite installing IntelliJ yourself as well?

Our first experiences with the OOD environment suggest that IntelliJ runs surprisingly smoothly there, assuming you have a good internet connection. However, we must note that OOD is now (Fall 2023) only in a testing phase, and we cannot guarantee it works perfectly. If you use it, please do drop us some feedback about your experiences!

(Note: In some O1 assignments, particularly in the first few weeks, we’ll use the computer to produce sounds. However, OOD does not support this, so you won’t hear anything. It’s nevertheless possible to complete those assignments in OOD, but it will be less fun.)

Here’s how you to use OOD:

  1. Log in at https://ood.cs.aalto.fi/ with your Aalto account.

  2. In the menu at the top, select Interactive Apps and then the server named IntelliJ IDEA (O1). There’s a session length setting that defaults to one hour, but feel free to change that.

  3. Press Launch to set up a session. (This may take a while.)

  4. When the session is ready, press Connect to the Container. IntelliJ should show up in a separate browser tab.

  5. The OOD environment comes with the appropriate version of IntelliJ and the relevant plugins. You can therefore skip the next few steps of the installation instructions that follow and jump straight to Creating a project folder, below.

Launching IntelliJ for the First Time

When you launch IntelliJ for the first time, there are some settings that you’ll need to adjust. Here’s how.

Launch IntelliJ

On Aalto IT’s Linuxes, you’ll find IntelliJ in the menu as IntelliJ IDEA. (If not, launch IntelliJ by opening a Terminal window and entering idea at the prompt. Launching IntelliJ like this once should ensure that it is available via the menu later.) In other environments, you can launch IntelliJ from the Start menu or by clicking the executable file (named Idea, idea64.exe, or similar) within the installation folder.

../_images/ij_start.png

On first launch, IntelliJ may ask you about sharing usage data and importing old settings. If so, you can pick Do not import settings and press OK.

IntelliJ welcomes you with view that looks like this:

../_images/ij_welcome.png

The A+ Courses plugin

Install the A+ Courses plugin in IntelliJ as follows.

  1. In IntelliJ’s welcome screen, select Plugins from the list on the left.

  2. A list of available plugins appears. Type A+ Courses in the search field at the top, and the plugin of that name shows up in the list. Press Install on it.

../_images/ij_plugin_install.png
  1. IntelliJ notifies you about installing a third-party plugin. Press Accept to okay that.

  2. Press Restart IDE to finish up the installation.

    • If that button fails to show up, close IntelliJ yourself and relaunch it.

    • When restarting, you may be given a brief notice about “indexing” being unfinished. Don’t worry about it.

Creating a project folder

IntelliJ suggests that you create or select a project to store your work. Select New Project.

A New Project window pops up with a list of project types on the left. Let’s make your project an A+ Courses project. Pick that on the left and press Next.

../_images/ij_new_project.png

At the next prompt, under Project Name, write a suitable name for your course project, such as o1 or o1assignments. Under Location, you can mark which folder you’d like IntelliJ to store your files in; the suggested default will do, unless you wish to change it.

Press Create. A window titled Project Structure shows up. We’ll continue setting things up there.

../_images/ij_project_structure.png

Installing the JDK toolkit into IntelliJ

While programming in IntelliJ, you’ll need a toolkit known as the JDK. You can install it as follows.

You should have the Project Structure window open. In that window, select the Project near the top.

You should then see a drop-down menu named SDK. In that menu, is there an option labeled OpenJDK 17?

  • If it happens that yes, there is, pick that option.

  • If not, do as illustrated in the two pictures below: Choose Add SDK → Download JDK in the drop-down menu. For Version, pick 17, and for Vendor pick Amazon Corretto (for example). You’re free to choose where to download the JDK; the default folder should do fine. Finally, press Download, and IntelliJ will fetch the toolkit.

Finally, press OK to close the Project Structure window.

../_images/ij_add_sdk.png
../_images/ij_download_jdk.png

Selecting a course

../_images/ij_plugin_tab.png

In front of you is IntelliJ’s main window that currently holds the project you created, which is empty of content.

Let’s set up your course project for O1 as follows. As part of this process, you’ll automatically receive the requisite version of the Scala language.

  1. Take a look at the top right-hand corner of the view. You’ll find the A+ Courses symbol plugin-logo there (below a bell-shaped symbol), as shown in the illustration on the right.

  2. Click that symbol. IntelliJ will suggest that you link a specific course to your project:

../_images/ij_select_course_button.png
  1. Press the Select an A+ Course button.

  2. A small dialog window pops up for selecting the course you are taking. Select O1 Fall 2023 and press OK.

  3. A language menu appears, pick English or Finnish. IntelliJ also tells you that it’s going to adjust some settings to suit the course. Press OK to approve.

    • Some of O1’s assignments come in two variants: a Finnish one and an English one. That language setting affects which ones you’ll submit. If you know Finnish, we recommend that you use the Finnish edition of this ebook and pick Finnish here. This setting has no effect on IntelliJ itself; it will be in English either way.

  4. After a short wait, IntelliJ suggests a restart to apply the new settings. Press OK to restart.

Setting an A+ passcode

Before you can submit assignments to A+ from IntelliJ, you’ll need to give IntelliJ permission to act in your name in A+. You do that by giving IntelliJ a “passcode”, (properly known as an API Access Token):

  1. Open up your profile page in A+.

  2. There’s a long string of characters under API Access Token. Copy the entire string to the clipboard. (That’s your personal code, similar to a password. Do not share it with other people.)

Now return to IntelliJ and do the following:

  1. On the right-hand side, in the A+ Courses tab, you’ll see a button labeled Set A+ Token. Press it.

../_images/ij_set_token_button.png
  1. Paste the access token at the prompt and press OK.

  2. Course content shows up in the A+ Courses tab. You’ll be accessing it throughout the course.

Programs in This Ebook

This is going to happen frequently in O1: we take a more or less complete program and discuss it in the text, then have you extend or develop it in an assignment.

One reason we do this is that you get to learn from examples. Another is that this is actually a typical scenario for professional programmers, too. Programmers often don’t start from scratch but modify an existing system or use existing program code as a part of a new program.

Here’s one:

The GoodStuff application

Let’s take a look at GoodStuff, an example program designed for the purposes of this course. Goodstuff is an “experience diary” application: it lets the user record their experiences and the ratings they’ve given to those experiences. An experience could be a stay at a hotel, for instance.

As given, GoodStuff is quite basic and lacking in many ways. It does contain the core of a better application, however, and most importantly, it’s suitable for introducing many programming concepts. We’ll be making use of GoodStuff repeatedly in the chapters to come.

Even though we haven’t yet taught you enough about programming to understand the code that defines GoodStuff, you can already explore the program. This will give you an overview of what an application looks like in IntelliJ and how you can manipulate it as a programmer. This is what we’ll do next in this chapter:

  1. Fetch the GoodStuff application into IntelliJ.

  2. Paint a broad-brush picture of the app’s main components.

  3. Run the app within IntelliJ and see how it looks from the user’s perspective.

  4. Take a peek at the program code and fix a tiny error in it.

A Program in IntelliJ

../_images/ij_aplus_toggle.png

The A+ Courses button on the top right toggles whether O1’s lists of contents are visible or hidden. Try it.

In IntelliJ, a programming project consists of modules. A module is just IntelliJ’s way of letting us bundle together files and settings that belong together. O1’s example programs and programming assignments each come within a module. Larger programs may consist of multiple modules.

Fetching an O1 module into IntelliJ

Notice the vertical A+ Courses button plugin-logo near IntelliJ’s top-right corner. It brings up lists of O1’s program modules and assignments. The same button hides the lists when you don’t want to look at them.

../_images/ij_project_toggle.png

The Project button toggles whether the contents of your personal course project are visible or hidden. Try it.

Look at the Modules list and find the GoodStuff module there. Double-click it, and IntelliJ downloads the module to the computer you’re using.

Downloading the GoodStuff module did not accomplish anything very obvious, but let’s take a closer look:

The Project tab in IntelliJ

On the other side of IntelliJ, near the top left-hand corner, is another important button project-logo. It controls the Project tab, which lists the contents of your personal course project: the programs that you’ll work on in O1. Make the Project tab visible now. (We recommend that you keep it visible at most times.)

../_images/ij_modules.png

Two modules in IntelliJ’s Project tab.

Modules and packages

The GoodStuff module is now visible on the left-hand side of IntelliJ’s user interface, in the Project tab.

../_images/ij_files.png

The GoodStuff application’s program code is divided in four files.

The other module already in your course project is called O1Library. You'll need that one throughout the course. Many of our example programs, GoodStuff included, don’t work without the O1Library toolkit. Apart from that, you don’t have to pay O1Library any mind now.

Browse the GoodStuff module’s files in the Project tab. Four files define the GoodStuff app: CategoryDisplayWindow.scala, GoodStuff.scala, Category.scala, and Experience.scala. (IntelliJ shows the names without the .scala suffix.)

These files are divided into packages (pakkaus). You may think of packages as a Scala equivalent of file folders. One use for packages is to group related pieces of a program together, which is particularly helpful with large programs. For instance, we can define a package that contains a program’s user interface to be separate from the package that defines the internal domain model.

Of the GoodStuff program’s four parts, Experience and Category model the program’s “guts”, namely the experiences that are recorded in the diary and the categories that those experiences fall into. These parts are located directly in package o1.goodstuff. The other two implement the program’s user interface and are located in package o1.goodstuff.gui.

Those two packages together define the GoodStuff app. A module may also contain other files. For instance, GoodStuff and many other O1 modules have a doc folder that contains the module’s documentation. We’ll have more to say about documentation later on (in Chapter 3.2).

Let’s run it already, please

Any Scala application will have a file that serves as the app’s launch file. In GoodStuff, the launch file is GoodStuff, which is in package o1.goodstuff.gui. Locate it in the Project tab and right-click it to bring up a menu. In the menu, select Run 'GoodStuff'.

The app’s GUI launches in a separate window and looks like this:

../_images/godstuff.png

This example application will show up multiple times in forthcoming chapters, so take a moment to get familiar with it, beginning with what the app’s user sees. Spend a bit of time using GoodStuff: click Add new hotel and make up some data to enter into the program. Notice the following:

  • This simple application supports only a single category of experiences: accommodation in hotels.

  • The application computes a value-for-money figure for each experience by dividing its rating by its price.

  • The user’s favorite experience grins at you. The experience with the highest rating is considered the favorite.

Finally, close the GoodStuff window. The program run terminates.

A Peek at Program Code

Double-click the names of code files to load up the files’ contents in IntelliJ’s editor. Try it!

Comments

You’ll soon notice that the code doesn’t consist of Scala commands only. It also contains a substantial amount of text in English, which has been colored gray or green by IntelliJ.

It’s common for program code to include such explanatory text, known as comments (kommentti). Comments can help other programmers figure out the purpose of the program’s components and how to use them. Even the programmer who originally wrote the comment may benefit from it when they return to work on a bit of code that isn’t fresh in memory.

Program code isn’t just for computers!

In comments, we’ve come across something more general and important: even though programs are written for computers to execute, we must also take human readers into consideration. When used sensibly, comments can be a cornerstone of good programming style.

Marking comments in Scala

In the Scala language, text between the tags /* and */ is a comment and has no effect on program execution. You can find examples throughout the GoodStuff application.

An alternative is to use the double-slash //, which marks the start of a comment that runs until the end of the line. IntelliJ’s Scala editor, like many other program editors, automatically uses color to highlight comments so that they stand out from the rest of the code.

In O1, we usually won’t require you to include comments in the programs that you write. It can be a good idea to write them nonetheless. In any case, you’ll be reading a lot of example code that contains comments.

Take a look around

Spend a few minutes browsing GoodStuff’s code. Even though most of it is likely to be incomprehensible — even the comments contain unfamiliar programming terms — you’ll get a sense of how a Scala program looks like. Perhaps you’ll also find bits of code that make sense to you or whose meaning you can guess. But if nothing makes any sense yet, that’s okay, too.

In the next chapter, 1.3, we’ll start, little by little, to get familiar with specific programming concepts and the matching commands in Scala. Eventually, you’ll be able to understand GoodStuff’s code, and more complicated programs, not to mention being able to write programs of your own.

Let’s Do Some Editing

Did you notice the typo in the title of the window that hosts the GoodStuff GUI? It says GodStuff!

It doesn’t take master programmer to fix that. Let’s apply the fix and take the opportunity to submit a program for automatic assessment.

The window title is defined as part of the GoodStuff GUI. If you want to locate the line of code yourself, go ahead, but it’s also fine to just see here for the answer:

Where is the title defined?

On line 35 of CategoryDisplayWindow.scala.

Do the following:

  1. Add the letter o where appropriate on that line.

  2. See if it worked: relaunch the program (via the right-click menu on GoodStuff). The window title should be okay now.

  3. Are you working alone or with a pair? If the latter, make sure to form the pair through the menu here in A+.

You’re now all set to submit your solution:

  1. Go back to the A+ Courses tab at IntelliJ’s right-hand edge and find the Assignments list.

  2. In the list, find the GoodStuff assignment under Week 1. Select it. Press the submit button submit above the list.

  3. A little dialog window pops up. Choose to submit alone or with a pair. You’ll also see that IntelliJ is about to submit CategoryDisplayWindow.scala for grading. Press OK.

  4. IntelliJ notifies you that the assigment has been submitted and that you’ll get the feedback later. After a little wait, another notification tells you that the feedback is available here in A+.

  5. You can access the feedback easily from IntelliJ by clicking the link in the notification, which opens the appropriate A+ page in the browser. A+ will have given you some automatic feedback and assignment points.

Saving and restoring files in IntelliJ

IntelliJ saves your files automatically as needed and keeps a history of changes. If you want to make extra-sure, you can press Ctrl+S (Cmd+S on a Mac) to save all unsaved changes in all files, but that is not necessary in practice.

If you ever need to restore an earlier version of a file (and Undo isn’t enough), you can right-click the file or folder and select Local History.

A+ presents the exercise submission form here.

Another Editing Task: The Game of Pong

Preparations

Explore another application, a version of the classic video game Pong. Find the program within the given Pong module and try it out, like you did with GoodStuff. Here are the steps in brief:

  1. Find the Pong module in the A+ Courses tab’s Modules list. Double-click to install it in your O1 project.

  2. Run the program: In the Project tab, find PongApp.scala within the package o1.pong.gui. Right-click and select Run 'runPong'.

  3. Use W or S to move the paddle on the left and the arrow keys to move the one on the right.

Your assignment, part 1 of 2

In the package o1.pong there is a file called package.scala. Among other things, this file defines some numerical values that shape the game. Open it in the editor.

One of the lines near the top defines something called BallRadius. On that line, replace the number 10 with 50.

Relaunch the game. You’ll observe that something changed.

Your assignment, part 2 of 2

In the same package, there’s a file called Ball.scala, which defines the rules that the ball follows as it moves. One of the lines says:

this.velocity = this.velocity.switchY

This command causes the ball to change direction as it bounces off the top or bottom of the playing area. Comment out this line. That is to say, write two slash characters (/) at the beginning of the line, turning it into a comment and causing it to no longer be an executable part of the program.

Relaunch the game.

Does our game now have a bug, an error in behavior? Well, we did intend to make that change, so it’s not a bug, it’s a feature.

Submit your solution.

A+ presents the exercise submission form here.

Fooling around with Pong

If you want, you can experiment further. Here are some ideas:

  • What happens if you change Size and Thickness in package.scala to have different numeric values?

  • Can you locate the bit in package.scala that defines how fast each paddle moves?

  • Can you find any bits of code that define the colors used in the GUI? See if you can change the colors.

  • Looking at PongApp.scala, can you figure out how to change the keys that control the paddles?

  • What if PongApp.scala said push(Right), not push(Up)?

Addendum

If you enjoyed messing about with Pong and seeing what happens, you might also enjoy the following quote, which makes an exciting point about the static-and-dynamic duality of programs:

One of the first items covered in an introductory physics course is the difference between potential and kinetic energy. You can think of potential energy as the energy stored in, say, a battery or a rock placed on top of a hill. Kinetic energy is energy that is in the process of being converted, as when the stored electricity in a battery drives a motor and when a rock rolls down a hill.


Similarly, when a human designs a program, there exists a potential computation that is unleashed when the program executes within a computer. Thus, one can think of the computation as being kinetic and in motion.


Moreover, just as a child with a firecracker can be surprised by the difference between potential and kinetic energy, so computer programmers are often surprised (even pleasantly) by the difference between potential and kinetic computation.


—Gary Flake (in his book The Computational Beauty of Nature)

Hint: Alternative Ways to Launch an App

It was already mentioned that you can launch an app via the right-click menu of its start file (such as GoodStuff or PongApp). Another way to do the same thing is to select that file in the Project tab and press Ctrl+Shift+F10.

If you already have the start file open in the editor, you can alternatively press the little play icon in the left margin (on the line that starts with object).

During O1, you’ll be launching apps a lot. Do it whichever way you prefer.

The above ways of lauching an app require you to first select or open the launch file. Alternatively, you can press Shift+F10 to launch whichever app you most recently launched (without selecting it). This is often convenient.

You may also want to take a look at the little menu in IntelliJ’s top-right corner, next to a play button. The menu lets you select among the most recently launched programs.

Programming as an Activity

Let’s finish the chapter by reflecting on what programming is like.

Programming as problem solving

Typically, a programmer’s work begins with a problem or need that calls for a solution. Here are some examples of problems that can be solved through computing.

  • One wishes to speak to people on the other side of the planet over the internet.

  • One needs a novel accounting application for a company.

  • One wants to know the best route for a car to reach its destination. Or for a spaceship.

  • One seeks a model that describes or predicts people’s behavior in a social network, the spread of diseases, climate change, or historical trends in how common different words are.

  • One wants to determine which additional products to recommend whenever customers make purchases in an online store.

  • One needs a tool that converts scientific measurement data into a format that is convenient for analysis.

  • One wishes to simulate the movement of subatomic particles in order to predict phenomena.

  • One wishes to simulate the movement of emotional avians as they accelerate through a gravitational field toward hoofed mammals.

  • And so on. And so on.

Interesting problems are invented all the time, both by programmers themselves and by others. Even if a problem is familiar, we may seek solutions that are better than those that exist.

Algorithms

Programmers often talk about algorithms (algoritmi). Roughly speaking, an algorithm is a stepwise method for solving a particular problem.

Baking, too, involves algorithms, even if the term isn’t used by bakers: in our example, the master baker’s notion of how to make the cake is an algorithm that she invented. The baker wrote the method down as a recipe. In the same way, a programmer implements algorithms — solutions to problems — as program code.

Parts of a problem may be solved with different algorithms. For instance, a word processor will use one algorithm for proofreading and another to provide a find-and-replace function.

As a programmer, you can invent the algorithms you use for some subproblems. For other subproblems, you’ll apply algorithms that other people previously created. In any case, you’ll need to figure out how to implement and combine the implementations into a complete program.

A mini-assignment: algorithms and programs

Of the following statements, which one is best described as correct? Please note that you receive feedback for both correct and incorrect answers. That feedback is part of the text of this ebook; please read it. It’s not crucial to get it right on the first try.

What programming is like

We’ve established that programming is one form of problem solving. A programmer needs to determine what algorithm solves a problem and how to present that algorithm to the computer as a program. There is practically never just a single possible solution, which is why programmers must compare different options and consider how to create a high-quality program. High quality might mean that the program needs to be fast, user friendly, secure, or easy to extend, for instance.

Programming calls for systematic thinking, creativity, and meticulosity. Many people consider programming to be fun aerobics for the brain, and nearly everyone agrees that programming can be used to create useful tools and products.

Unlike people sometimes think, creating programs often revolves around humans at least as much as it revolves around machines. For instance, programs’ ease of use and extensibility must be assessed from a human perspective. And of course programs are created to meet human needs.

Programs come in different sizes and so do teams that develop programs. Programs are created by individuals and by large, international organizations. In day-to-day programming work, human communication often plays a large role.

Some of the people who program as part of their job are full-time software developers who seek to produce high-quality software for commercial or other purposes. A still larger group are the varied professionals who use programming as a tool for solving problems in a particular field: financial analysts, social scientists, researchers in medicine and genomics, physicists, graphic designers, linguists, climatologists, engineers, etc. Some have harnessed programming as an instrument for art.

Someone with programming skills can create tools that make them more productive as they use applications such as spreadsheets or games and as they engage in other everyday activities. Programming (of some form or another) is becoming a basic skill of the educated citizen, a skill that helps us benefit from the enormous power of computing and to understand the computerized systems that surround us.

Can you think of a program that you wish existed? That you would like to create yourself? What kind of program would make the world a better place?

Summary of Key Points

  • As a computer runs, or executes, a program, it follows a set of instructions created by a programmer. It follows them step by step, to the letter.

  • Programming is a creative activity that seeks solutions to problems that people find meaningful.

  • Programs are written in a programming language. In this course, we use a language called Scala.

  • We use an integrated development environment (IDE) named IntelliJ. An IDE brings together various tools that assist the programmer.

    • In IntelliJ, you can edit code and run programs to examine how your edits impact on program behavior.

    • The parts of a Scala program can be organized in packages. A package may contain multiple program parts defined in multiple files.

    • In IntelliJ, programs may be grouped into modules. A module may contain multiple packages.

    • Many of this ebook’s chapters come with given programs that are more or less complete. They are provided to you as IntelliJ modules.

  • Program code isn’t meant for just computers to process. One indication of this is that code may contain comments that clarify its meaning to human readers.

  • Links to the glossary: programming, program; application, user interface; domain, algorithm; dynamic, static; program code, programming language, Scala; comment; integrated development environment or IDE.

Feedback

Please note that this section must be completed individually. Even if you worked on this chapter with a pair, each of you should submit the form separately.

Credits

Thousands of students have given feedback and so contributed to this ebook’s design. Thank you!

The ebook’s chapters, programming assignments, and weekly bulletins have been written in Finnish and translated into English by Juha Sorva.

The appendices (glossary, Scala reference, FAQ, etc.) are by Juha Sorva unless otherwise specified on the page.

The automatic assessment of the assignments has been developed by: (in alphabetical order) Riku Autio, Nikolas Drosdek, Kaisa Ek, Joonatan Honkamaa, Antti Immonen, Jaakko Kantojärvi, Niklas Kröger, Kalle Laitinen, Teemu Lehtinen, Mikael Lenander, Ilona Ma, Jaakko Nakaza, Strasdosky Otewa, Timi Seppälä, Teemu Sirkiä, Anna Valldeoriola Cardó, and Aleksi Vartiainen.

The illustrations at the top of each chapter, and the similar drawings elsewhere in the ebook, are the work of Christina Lassheikki.

The animations that detail the execution Scala programs have been designed by Juha Sorva and Teemu Sirkiä. Teemu Sirkiä and Riku Autio did the technical implementation, relying on Teemu’s Jsvee and Kelmu toolkits.

The other diagrams and interactive presentations in the ebook are by Juha Sorva.

The O1Library software has been developed by Aleksi Lukkarinen and Juha Sorva. Several of its key components are built upon Aleksi’s SMCL library.

The pedagogy of using O1Library for simple graphical programming (such as Pic) is inspired by the textbooks How to Design Programs by Flatt, Felleisen, Findler, and Krishnamurthi and Picturing Programs by Stephen Bloch.

The course platform A+ was originally created at Aalto’s LeTech research group as a student project. The open-source project is now shepherded by the Computer Science department’s edu-tech team and hosted by the department’s IT services. Markku Riekkinen is the current lead developer; dozens of Aalto students and others have also contributed.

The A+ Courses plugin, which supports A+ and O1 in IntelliJ IDEA, is another open-source project. It has been designed and implemented by various students in collaboration with O1’s teachers.

For O1’s current teaching staff, please see Chapter 1.1.

Additional credits for this page

Niklas Kröger contributed to the section on launching IntelliJ, and Ilona Ma to the section on the Open OnDemand environment.

Niklas Kröger contributed to the section on launching IntelliJ.

a drop of ink
Posting submission...