Please note that this article assumes you have read my previous posts on data types, variables, conditionals and loops, classes, etc. and you are able to write a running Hello, World! program. Please do these before trying to create another DOOM or Crysis.
Introduction
A function is a way of packaging code that does something. For example, you might have a function that adds two numbers and returns the sum, or you might have a function that prints your name to the console. With this technique, you can separate commonly-used tasks into different functions, which can be called wherever a programmer needs them… instead of duplicating or re-writing the same code throughout the program (which you won’t like, trust me. Especially if you make a change and have to update it in various places). Think of functions as the “code equivalent of variables”.
In OOP (Object-Oriented Programming) languages such as C# or Java, functions are implemented as static methods; that is, they are declared within a class, unlike C/C++ and some other languages where the functions may exist by themselves. When they are declared within a class or a struct, they are considered part of an object. Every executed instruction is performed in the context of a method. For example, when we call “Console.WriteLine()” (in C#), we are actually calling a function (available to the C# assembly) that simply writes something to the console.
In this post, I will teach you how you can implement functions in C# and Java… to make your programming life even more joyful! (Remember, this is “The Joy of Functions” – there are no mistakes, only happy little accidents.)
Static Methods
As I mentioned earlier, we define functions as static in OOP languages. Literally, this means the methods don’t change the state of a class. This makes sense, since when dealing with functions, we are more interested in executing some arbitrary code, rather than changing the object’s state.
The syntax for defining a static method in a class is same for both C# and Java:
1 2 3 4 |
<access modifier> static <data type> <function name>(<parameters, if any>) { // Implementation of a function } |
Considering this syntax, we can very easily define our function. Let’s define a function for adding two numbers, as follows:
1 2 3 4 |
public static int add(int a, int b) { return a + b; } |
As a professor in university once bluntly told me, “one-letter variables are not reserved for simple functions. They are reserved for lousy programmers.” Although this seems a bit harsh, there are several good reasons not to use one-letter variables – the biggest being, if you don’t have a code editor that can refactor, it would be difficult to change the variable name. (Other reasons included “it’s hard to tell what the variable does”, and “it looks unprofessional”). In this case, however, I’m trying to clearly depict that you can add a and b to get a sum, which is returned at the end of the code block.
From elsewhere in the program, you could call this with simply:
1 |
int bigNumber = add(100, 200) // Returns 300 |
You can see that it’s trivial to define and use a function, but then again, the example function above does a fairly trivial procedure. Let’s define another (more advanced) function that calculates the factorial of a single number n:
1 2 3 4 5 6 7 8 |
public static int factorial(int n) { if (n < 2) { return 1; } return n * factorial (n - 1); } |
This code wouldn’t win any “best code of the year peace prize awards”, but it works and is functional. It’s also easy to maintain, because it’s easy for anyone to read the code and immediately understand what it does, and how it does it (recursively).
Using the Methods Together
We can use our functions in a program as follows:
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class StaticMethod { public static int add(int a, int b) { return a + b; } public static int factorial(int n) { if (n < 2) { return 1; } return n * factorial (n - 1); } public static void Main() { Console.WriteLine (add (4, 4)); // prints 8 Console.WriteLine (factorial (4)); // prints 24 } } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class StaticMethod { public static int add(int a, int b) { return a + b; } public static int factorial(int n) { if (n < 2) { return 1; } return n * factorial (n - 1); } public static void main(String[] args) { System.out.println (add (4, 4)); // prints 8 System.out.println (factorial (4)); // prints 24 } } |
It’s really as simple as that.
Static Classes
Static classes are classes where only a single instance is available to the program. Static classes don’t need to be instantiated. They are useful in cases where you know you won’t be needing to pass instances to other classes. However, static classes can only contain static members, which also cannot be instantiated.
Let’s pretend you have a “GameSettings” class, which stores different settings in a video game. Here’s how you might define it:
1 2 3 4 5 6 7 8 9 |
class GameSettings { public static bool soundOn = true; public static bool musicOn = true; public static void run() { Console.WriteLine(“Running...”); // Java would be System.out.println(“Running...”); } } |
The following is the syntax for using a static method in a class:
1 |
<class name>.<static method name>; |
So, we could use our static class in a program as follows:
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class StaticClass { public static bool isMusicOn() { return GameSettings.musicOn; } public static void Main() { GameSettings.soundOn = false; GameSettings.musicOn = false; GameSettings.run(); Console.WriteLine(isMusicOn()); // prints 'false' } } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class StaticClass { public static bool isMusicOn() { return GameSettings.musicOn; } public static void main(String[] args) { GameSettings.soundOn = false; GameSettings.musicOn = false; GameSettings.run(); System.out.println(isMusicOn()); // prints 'false' } } |
Note that you cannot use non-static members in static methods!
As you can see, static classes can be used as a convenient container for sets of methods that only run on input parameters, and doesn’t modify the state of an object. In the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations like ‘cos’, ‘sin’ etc., without any requirement to store or retrieve data that is unique to a particular instance of the Math class, thus they don’t need instantiation.
Functions are best suited for trivial tasks, especially when the task is duplicated several times in your program; hence, you can simply create a static method in a class and call it whenever you need it. In which cases are you going to use functions?