Sitemap

Code Grammar — Chapter 1

2 min readFeb 27, 2024

--

Press enter or click to view image in full size

How to write functions and What NOT to do!

What are functions?

Functions are the first line of organization in any program. In programming, a function is a self-contained block of code that performs a specific task or a set of tasks. Functions are designed to be reusable, which means they can be called multiple times from different parts of a program.

Structure of any function

The structure of a typical function in a programming language involves several components:

Press enter or click to view image in full size
  • function name
  • parameters (if any)
  • and the code block that contains the instructions

Best practices to follow

  1. Size:
  • The first rule of function is they should be small, and the second is they should be smaller in that.

2. Blocks and Indentation:

  • Blocks within if , else, try,catchstatement and within loops should be one line, that line should be a function call probably.

3. Purpose:

  • The function should do ONE thing.
  • The function should either do something or answer something, but not both.

4. Level Abstraction

  • If a function is doing one thing, then statements should all be at the same level of abstraction.
  • Follow Step Down rule, the Step Down to Lower-Level Abstractions. The main function or method should provide a high-level overview of what it does, and as you move through the code, the details and complexity should gradually increase in a step-down fashion.

5. Naming

  • The function name should be a verb.
  • The name should describe what a function does, Long descriptive name is better than a short enigmatic one.

6. Function Argument

  • Zero is the ideal no of arguments, More than two arguments should require justification.
  • It becomes harder to test all combinations of arguments via unit test, in case of more arguments.
  • Output arguments should not be avoided.
  • Passing a boolean argument is not an ideal practice.
  • The name should tell the order and intent of the arguments.

Special Case — Lambda functions

Lambda functions, also known as anonymous functions or lambda expressions, serve a specific purpose in programming. Lambda functions provide a concise way to define small, one-time-use functions without the need for a full function definition.

Get Shantanu kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Best Practices for Writing Lambda Functions:

  • Lambda functions are meant for simple operations. Avoid complex logic within a lambda.
  • For complex logic or critical code, regular functions are generally more testable and maintainable.
  • Avoid nesting lambda functions excessively.
  • Lambda functions work well with higher-order functions like map, filter, and reduce.

--

--