Defining a Greeter Application in Slice
The first step of writing our application is to define the contract between our client and server using Slice. For this example, the contract is very simple: we want a single operation which accepts a name, and returns a greeting. Let’s see what this looks in Slice.
Slice Files
All Slice definitions must be contained within slice files, i.e. files ending with a .ice
extension.
For this example, we’ll create a Slice file named Greeter.ice
to write our definitions in.
Once we’ve finished writing it, this file can be run through a Slice compiler (like
slice2cpp
) to generate code used in the following pages.
Writing the Greeter.ice
Slice File
Before anything else, we ought to add a #pragma once
to the top of our Slice file. This is a preprocessor directive which prevents our Slice files from being included multiple times. In this example, where we have only a single Slice file, it’s not really necessary, but adding it costs us nothing, and is a good practice that can prevent some headaches in projects with multiple files.
This is also the part of the file where we would #include
any other Slice files that this file needs. However, since our example is small and self-contained, we don’t need to include any other files.
Slice supports the same preprocessor directives as C++, however most projects should only ever need #include
and #pragma once
.
With this out of the way, we start by adding a module to our Slice file. These containers let us organize our Slice definitions into named groups, and Slice requires that all definitions be placed within a module; i.e. Slice does not support top-level definitions. So now our Slice file will look like:
#pragma once
module VisitorCenter
{
// ... definitions go here
}
Now that we have a module, there’s only one more thing we need before we can define our operation: an interface. Interfaces are at the core of Ice, as they specify the interface between a client and server. So, how your operations are split among interfaces can have large implications for the structure of your application. With only one operation, there’s no such considerations though:
interface Greeter
{
// ... operations go here
}
Finally, we can write our operation. It should take a name (a single string
parameter), and return a greeting (a return type of string
). Something like:
string greet(string name);
Most importantly, you’ll notice there is no implementation for our operation. Slice is only for defining the contract between client and server. How operations get called or implemented is left up to the language code, as you’ll see in the following pages.
Putting everything together (and adding some doc-comments), here is the final state of our Slice file:
#pragma once
module VisitorCenter
{
/// Represents a simple greeter.
interface Greeter
{
/// Creates a personalized greeting.
/// @param name The name of the person to greet.
/// @return The greeting.
string greet(string name);
}
}