Tidying up the Interface

Learn how to make our server code clean and easy to use.

We'll cover the following

As we saw, our server works but is complicated to use. Our callers have to make explicit GenServer calls, and they have to know the registered name for our server process. We can do better.

Major functions

Let’s wrap this interface in a set of three functions in our server module:

  • start_link
  • next_number
  • increment_number

The first of these calls the GenServer start_link method. As we’ll see in the next chapter, the name start_link is a convention. The start_link function must return the correct status values to OTP. Because our code simply delegates to the GenServer module, this is taken care of.

Following the definition of start_link, the next two functions are the external API to issue calls and cast requests to the running server process.

We’ll also use the name of the module as our server’s registered local name (hence the name: __MODULE__ when we start it and the __MODULE__ parameter when we use call or cast).

iex> Sequence.Server.start_link 123 
{:ok,#PID<0.57.0>}
iex> Sequence.Server.next_number
123
iex> Sequence.Server.next_number
124
iex> Sequence.Server.increment_number 100 
:ok
iex> Sequence.Server.next_number
225

Run commands given in the above snippet to run the code below:

Get hands-on with 1400+ tech skills courses.