O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

WRITING NEW CODE

When writing new code, you have the opportunity to make structural decisions up front, and you can define the discipline you would like to use for certain cases. Here are several ideas for guidelines you may find useful. The rest of this section will discuss these choices in some more depth.

  • Keep methods static if possible.
  • Prefer anonymous functions over named ones.
  • Prefer higher order functions over manual algorithm implementation.
  • Prefer immutable data.
  • Watch behavior implementation in classes.

Use Static Methods

Static methods is one of the basic ideas worth considering as a general guideline. It is supported by many object oriented programmers, and from a functional point of view, functions can be made static most of the time. Any pure function can be made static.

In object oriented programming, a commonly discussed question is how to handle method parameters when the values received by the method as parameters are ones that are already available in the class. Consider this rough outline of a class:

public class DataThing {

  private int field1;

  private int field2;

  ...

  private string field13;

 

  public void DoSomethingWithFields1And5() {

    // doing something that involves fields 1 and 5

  }

 

  public int CalculateWithFields() {

    // use all or several of the fields in the class to perform some

    // calculation and return the result

  }

}

The class has a number of private fields and two methods, both of which are meant to use at least some ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required