Applied Programming/Functions

From Wikiversity
Jump to navigation Jump to search

This lesson introduces functions and related code documentation.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Document code segments using comments and documentation strings
    • Use indentation, white space, comments, and documentation strings; generate documentation by using pydoc
  • Construct and analyze code segments that include function definitions
    • Call signatures; default values; return; def; pass

Readings[edit | edit source]

  1. Wikipedia: Modular programming
  2. Wikipedia: Function (computer science)
  3. Wikipedia: Parameter (computer programming)
  4. Wikipedia: Scope (computer science)
  5. Wikipedia: Naming convention (programming)

Multimedia[edit | edit source]

  1. YouTube: Introduction to Structured Programming
  2. YouTube: The Disadvantages of Spaghetti Code
  3. YouTube: The Advantages of Modularization
  4. YouTube: Modularity with Functions
  5. YouTube: Programming Basics - Statements & Functions
  6. YouTube: Programming Tutorial - Function Parameters
  7. YouTube: How to Use Functions in Python
  8. YouTube: Python Programming - Variable Scope
  9. YouTube: Naming Convention with Programming Languages
  10. YouTube: Python Programming: Docstrings

Examples[edit | edit source]

Activities[edit | edit source]

Programming Languages[edit | edit source]

  1. Review Wikipedia: Coding conventions, Research style guides or coding standards for your selected programming language, looking specifically for function documentation. If applicable, discuss coding conventions with your classmates and agree on a standard to follow for this course.

Coding[edit | edit source]

Complete one or more of the following coding activities in your selected programming language. Use self-documenting variable and constant names that follow the naming conventions for your selected programming language. Include comments at the top of the source code that describe the program and are consistent with the program or module documentation conventions for your selected programming language.

  1. Extend the BMI program from the previous lesson. Use separate functions for input, each type of conversion, BMI calculation, and output. Avoid global variables by passing parameters and returning results. Define constants for height and weight conversions and use the self-documenting function, variable, and constant names that follow the naming conventions for your selected programming language. Include comments at the top of the source code and comments for each function that is consistent with the documentation conventions for your selected programming language.

Lesson Summary[edit | edit source]

  • Modular programming is a software design technique that emphasizes separating the functionality of a program into reusable, independent modules.[2]
    • This concept is related to structured and object-oriented programming; all have the same end goal of deconstructing a comprehensive program into smaller pieces.[2]
  • Structured programming enforces consistent structures (sequential, conditional, and repetition), requiring them to have a single entry and a single exit.[3]
  • Object-oriented programming entails the use of classes, a template for object instantiation. An object is a user-created data type that carries its own attributes (fields) and behaviors (methods).[4]
  • A subroutine, function, or method is a sequence of instructions designed to complete a given task.[5]
  • Subroutines aid in the decomposition of complicated, multi-step tasks. They also facilitate the related concepts of re-usability and maintainability.[5]
  • A subroutine may receive arguments upon invocation and return values upon termination.[5]
  • A subroutine may call other subroutines, or itself recursively.[5]
  • A subroutine has a side-effect when it modifies external data beyond its scope. For example, a subroutine may alter its supplied argument, changing its value in the calling environment.[5]
  • A variable's scope is the portion of the source code in which the binding of an identifier (user-defined name of a program element[6]) gets associated with the underlying entity.[7]
  • The scope of a name binding is the region where a given identifier can be recognized or declared; it could apply to variables, functions, and user-created structures.[7]
  • A variable's scope can vary from a single expression to an entire program, with many gradations and flavors in-between.[7]
  • The 6 levels of scope in order from the most to least inclusive: [7]
    1. global scope
    2. module scope
    3. file scope
    4. subroutine/function scope
    5. block scope
    6. expression scope
  • A declaration is global in scope if the name has effect throughout an entire program. The use of non-constant variables with global recognition is considered a harmful practice, due to the increased likelihood of colliding identifiers and unintentional masking.[7]
  • When the scope is limited to a module, the identifier can only reference within the visibility of that module (which could potentially span multiple files of source code).[7]
  • This idea of module scope can also be extended to class hierarchies where certain attributes or behaviors may be specified as private, only to be accessed from within the class itself.[7]
  • When variables are declared outside a subroutine, they usually are declared at the file-level; their scope ranges from the point of declaration until the end of the file.[7]
  • Function scope variables are local to a specific function. They go 'out of scope' when the function returns.[7]
    • In most cases, the lifetime of these variables spans the duration of the function call; the entity gets created when the variable is declared, only to be permanently destroyed when the function returns.[7]
    • However, some languages also have static local variables, where the lifetime of the variable is the entire lifetime of the program. The variable is only known in the context of its resident function.[7]
  • A variable known only to a block is usually restricted to a construct such as a conditional statement or a loop.[7]
  • Some functional languages offer a let-expression mechanism that confines a declaration's scope to a single expression.[7]
    • This could be useful if you only need a temporary, intermediate value for a computation.[7]
  • There are two strategies employed to resolve names: lexical scoping and dynamic scoping.[7]
    • With lexical scoping, the entity referenced is known prior to run-time, determined by the lexical structure and content of the program's source code.[7]
    • With dynamic scoping, the entity referenced is deduced at run-time, depending on the variable's relative position in the call stack. This method is far less popular among implemented programming languages.[7]
  • Parameters are variables that receive data inside a subroutine or function.[8]
  • The subroutine or function head defines a parameter list, the standard by which future calls are to be made.[8]
  • Subroutines may use a ‘call by value’ strategy where the arguments passed set-up local variables inside the function. These variables don't have access to data in the calling environment, so critical processes remain safe from accidental error.[8]
    • The arguments passed to a subroutine are evaluated and transferred onto the corresponding parameter.[8]
  • Subroutines may also use a ‘call by reference’ strategy where the original argument itself gets referenced—not just a copy of its value; by referring to the actual memory location of the variable, it can be directly affected, producing an observable side-effect.[8]
  • There is a slight distinction to be made between an "argument" and a "parameter." The argument is the value or reference supplied when calling the function; the parameter is the variable inside the function that receives the argument. For variables that are ‘passed by reference,’ both aliases would refer to the same object.[8]
  • Function parameters can have default parameter values written in parameter = expression form. When calling a function with default parameters, the corresponding argument can be omitted in a call, and the default value will be used instead.[9]
  • If one function parameter has a default value, then all following parameters must have default values.[10]
  • Following a naming convention is to properly name a variable, function, and other identifiers according to mutual standards.[11]
  • Having a consistent naming convention allows other developers to focus on issues of logic rather than syntactical concerns.[11]
  • Identifiers should be relatively brief, yet long enough to adequately describe the object being identified.[11]
  • A popular naming convention in some programming languages is to use lower camel case, where the first word is lower-cased and subsequent words are capitalized (e.g., getHeight(), printChart(), and so on).[11]
  • Constants are typically named with all upper-case letters and if applicable, underscores separating the words (e.g., WEIGHT_CONVERSION, HEIGHT_CONVERSION, and so on).[11]
  • Different programming languages have different naming conventions; following your language's convention is not essential to writing code, but strongly advised. When peers review your code, they will be well-adjusted to your style of nomenclature.[11]

Key Terms[edit | edit source]

Data that gets passed to a function upon invocation. Depending on the evaluation strategy, the argument supplied may consist of variables/constants, literal values, other function calls, or an expression involving operators and the aforementioned objects.[8]
Arguments are passed to the subroutine by direct reference, typically using the argument's address.[5]
Arguments are evaluated and a copy of the value is passed to the subroutine.[5]
A string literal which appears as the first expression in a class, function or module. While ignored when the suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object. [12]
A collection of programming objects (functions, variables, and other mechanisms) that get packaged together as reusable, adaptable code.[2]
Placeholder variables that receive the supplied arguments so they can be accessed inside the function.[8]
return value
A function may optionally return a value or another object to its calling environment upon termination. This return value may be captured or simply ignored.[13]
The block or section of code in which the variable exists and can be referenced. This is known as its visibility.[7]
A sequence of program instructions that perform a specific task, packaged as a unit.[5]

See Also[edit | edit source]

References[edit | edit source]