Writing Clean Functions

Clean functions are methods that are small (they have two or fewer arguments) and avoid duplication. The ideal method has no parameters and does not modify the program's state. Small methods are less prone to exceptions, so you will be writing much more robust code that benefits you in the long run as you will have fewer bugs to fix.

Functional programming is a software coding methodology that treats computations as the mathematical evaluation of computations. This chapter will teach you the benefits of treating computations as the evaluation of mathematical functions in order to void changing an object's state.

Large methods (also known as functions) can be unwieldy to read and prone to errors, so writing small methods has its advantages. Hence, we will look at how large methods can be broken up into smaller methods. In this chapter, we will cover functional programming in C# and how to write small, clean methods.

Constructors and methods with multiple parameters can become a real pain to work with, so we will have to look for ways to work around and pass multiple parameters, as well as how to avoid using more than two parameters. The main reason for reducing the number of parameters we have is that they can become hard to read, be a source of irritation to fellow programmers, and cause visual stress if there are enough of them. They can also be a sign that the method is trying to do too much, or that you need to consider refactoring your code.

In this chapter, we will cover the following topics:

  • Understanding functional programming
  • Keeping methods small
  • Avoiding duplication
  • Avoiding multiple parameters

By the time you have worked through this chapter, you will have the skills to do the following:

  • Describe what functional programming is
  • Provide existing examples of functional programming in the C# programming language
  • Write functional C# code
  • Avoid writing methods with more than two arguments
  • Write immutable data objects and structures
  • Keep your methods small
  • Write code that adheres to the Single Responsibility Principle (SRP)

Let's get started!