What are Functions? (advanced)
Jon Mattingly avatar
Written by Jon Mattingly
Updated over a week ago

NOTE: Learners are introduced to the concept of functions in the world of Moongarden. Learners get more in-depth experience with functions and how they are used in object-oriented programming languages within the new Bug World app.

Definition: A function is a block of code designed to perform a particular task.

Example: In OOP, functions are specific actions that can be performed by objects. For example, there are hundreds of makes and models of different cars, however all cars can still accelerate and turn. These actions are the functions defined by the Car class. The accelerate function causes the car to move faster, and the turn function makes the car change directions.

While cars share many of the same functions, like turn and accelerate, they may be performed differently by each object depending on the object's properties. For example, while the accelerate function might be shared between cars, an object with brand new tires will be able to accelerate quicker and easier than the exact same car with old tires. Changing the tire_type property affects the outcome of the accelerate function.

Like everything in object-oriented programming, functions are performed independently from all other parts of the program. Each function is responsible for a single specific action, and does not care about the outcome of the action. You can tell your car to accelerate and your car will execute the action regardless of the outcome, even if that means driving your car into a wall!
โ€‹
โ€‹Application: In the Bug World app, learners can call upon functions to defeat Slimes! Each function represents a single, specific action, noted underneath each function name in pseudocode.ย 

In the Bug World app, learners will have a chance to adjust functions in order to best defeat the Slimes. Below you can see the function to merge two fuzzes to upgrade their power to either higher damager or speed. Learners will have to decide if adding the merge function will be the best way to defeat Slimes!

Why We Use Functions: Functions are actions. We need functions to code dynamic programs because without them, objects won't actually do anything. Functions allow programmers to define the code for an action once, and reuse it many times without re-writing it again. With functions, we can repeat actions without repeating the code.

Did this answer your question?