# Applied Programming/Functions

This lesson introduces functions and related code documentation.

## Objectives and Skills

Objectives and skills for this lesson include:
* 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

* Wikipedia: Modular programming
* Wikipedia: Function (computer science)
* Wikipedia: Parameter (computer programming)
* Wikipedia: Scope (computer science)
* Wikipedia: Naming convention (programming)

## Multimedia

* YouTube: Introduction to Structured Programming
* YouTube: The Disadvantages of Spaghetti Code
* YouTube: The Advantages of Modularization
* YouTube: Modularity with Functions
* YouTube: Programming Basics - Statements & Functions
* YouTube: Programming Tutorial - Function Parameters
* YouTube: How to Use Functions in Python
* YouTube: Python Programming - Variable Scope
* YouTube: Naming Convention with Programming Languages
* YouTube: Python Programming: Docstrings

## Examples

* C#
* Java
* JavaScript
* PHP
* Python3

## Activities
### Programming Languages

* 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

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.
* 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

* Modular programming is a software design technique that emphasizes separating the functionality of a program into reusable, independent modules.
** This concept is related to structured and object-oriented programming; all have the same end goal of deconstructing a comprehensive program into smaller pieces.
* Structured programming enforces consistent structures (sequential, conditional, and repetition), requiring them to have a single entry and a single exit.
* 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).
* A subroutine, function, or method is a sequence of instructions designed to complete a given task.
* Subroutines aid in the decomposition of complicated, multi-step tasks. They also facilitate the related concepts of re-usability and maintainability.
* A subroutine may receive arguments upon invocation and return values upon termination.
* A subroutine may call other subroutines, or itself recursively.
* 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.
* 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) gets associated with the underlying entity.
* 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.
* A variable's scope can vary from a single expression to an entire program, with many gradations and flavors in-between.
* The 6 levels of scope in order from the most to least inclusive:
** global scope
** module scope
** file scope
** subroutine/function scope
** block scope
** 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.
* 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).
* 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.
* 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.
* Function scope variables are local to a specific function. They go 'out of scope' when the function returns.
** 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.
** 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.
* A variable known only to a block is usually restricted to a construct such as a conditional statement or a loop.
* Some functional languages offer a let-expression mechanism that confines a declaration's scope to a single expression.
** This could be useful if you only need a temporary, intermediate value for a computation.
* There are two strategies employed to resolve names: lexical scoping and dynamic scoping.
** 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.
** 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.
* Parameters are variables that receive data inside a subroutine or function.
* The subroutine or function head defines a parameter list, the standard by which future calls are to be made.
* 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.
** The arguments passed to a subroutine are evaluated and transferred onto the corresponding parameter.
* 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.
* 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.
* 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.
* If one function parameter has a default value, then all following parameters must have default values.
* Following a naming convention is to properly name a variable, function, and other identifiers according to mutual standards.
* Having a consistent naming convention allows other developers to focus on issues of logic rather than syntactical concerns.
* Identifiers should be relatively brief, yet long enough to adequately describe the object being identified.
* 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).
* 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).
* 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.

## Key Terms
### argument

    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.

### call-by-reference

    Arguments are passed to the subroutine by direct reference, typically using the argument's address.

### call-by-value

    Arguments are evaluated and a copy of the value is passed to the subroutine.

### docstrings

    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.

### module

    A collection of programming objects (functions, variables, and other mechanisms) that get packaged together as reusable, adaptable code.

### parameter

    Placeholder variables that receive the supplied arguments so they can be accessed inside the function.

### 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.

### scope

    The block or section of code in which the variable exists and can be referenced. This is known as its visibility.

### subroutine

    A sequence of program instructions that perform a specific task, packaged as a unit.

## See Also

* Computer Programming/Functions
* Cornell University Lecture: Modular Programming
* University of Utah Resource: Functions
* DataCamp: Docstrings in Python
* GitHub: Python Docstring Style Guide