Press "Enter" to skip to content

Ballerina: A programming language for the cloud

Ballerina, which is developed and supported by WSO2, bills itself as “an open source, statically typed, cloud-native programming language.” What is a cloud-native programming language? In Ballerina’s case, it is one that supports common Internet data structures and networks, and includes interfaces to a large number of Internet databases and services. Ballerina was designed to simplify the development of distributed microservices by making it easy to integrate APIs, and to do it in a way that is familiar to C, C++, C#, and Java programmers.

Essentially, Ballerina is a C-like compiled language that has features for JSON, XML, and tabular data with built-in SQL-like language queries, concurrency with language-managed threads and sequence diagrams, live sequence diagrams synchronized with source code , flexible types for use both within programs and in service interfaces, explicit error handling and concurrency safety, and networking primitives built into the language.

There are two implementations of Ballerina. The currently available version, jBallerina, has a toolchain implemented in Java, compiles to Java bytecode, runs in a Java virtual machine, and interoperates with Java programs. A newer, unreleased (and incomplete) version, nBallerina, cross-compiles native binaries using LLVM and provides an external C function interface. jBallerina can currently generate native GraalVM images experimentally from its CLI, and can also generate artifacts in the cloud for Docker and Kubernetes. Ballerina has interface modules for PostgreSQL, MySQL, Microsoft SQL Server, Redis, DynamoDB, Azure Cosmos DB, MongoDB, Snowflake, Oracle Database, and JDBC databases.

For development, Ballerina offers a Visual Studio Code plugin for editing and debugging fonts and graphics; an IntelliJ IDEA plugin; a command line utility with several useful features; a web-based sandbox; and a REPL (read-evaluate-print loop) shell. Ballerina can work with OpenAPI, GraphQL and gRPC schemas. It has a module sharing platform called Ballerina Central and a great library of examples. The command line utility provides a build system and package manager, along with code generators and the interactive REPL shell.

Finally, Ballerina offers integration with Choreo by WSO2 for observability, CI/CD, and devops, for a small fee. Ballerina itself is open source and free.

ballerina language

Ballerina Language combines familiar elements of C-like languages ​​with unique features. For an example using familiar elements, here’s a “Hello World” program with variables:

import ballerina/io;
string greeting = "Hello";
public function main() {
    string name = "Ballerina";
    io:println(greeting, " ", name);

Both int and float Types are 64-bit signed in Ballerina. Strings and identifiers are Unicode, so they can be adapted to many languages. Strings are immutable. The language supports methods and functions, for example:

// You can have Unicode identifiers.
function พิมพ์ชื่อ(string ชื่อ) {
    // Use \u{H} to specify character using Unicode code point in hex.
string s = "abc".substring(1, 2);
int n = s.length();

in ballerina, nil is the name of what is normally called null. A question mark after the type makes it nullable, just like in C#. A pair of empty parentheses means nil.

int? v = ();

arrangements in Ballerina use square brackets:

int[] v = [1, 2, 3];

Dancer maps they are associative key-value structures, similar to Python dictionaries:

map<int> m = {
    "x": 1,
    "y": 2

Dancer records are similar to C structures:

record { int x; int y; } r = {
    x: 1,
    y: 2

You can define types and named records in Ballerina, similar to C typedefs:

type MapArray map<string>[];
MapArray arr = [
    {"x": "foo"},
    {"y": "bar"}
type Coord record {
    int x;
    int y;

you can create a Union of multiple types using the | character:

type flexType string|int;
flexType a = 1;
flexType b = "Hello";

Ballerina does not support exceptions, but it does support errors. He check keyword is shorthand for returning if the type is error:

function intFromBytes(byte[] bytes) returns int|error {
    string|error ret = string:fromBytes(bytes);
    if ret is error {
        return ret;
    } else {
        return int:fromString(ret);

This is the same function using check rather if ret is error { return ret:

function intFromBytes(byte[] bytes) returns int|error {
    string str = check string:fromBytes(bytes);
    return int:fromString(str);

You can handle abnormal errors and make them fatal with the panic keyword. You can ignore return values ​​and errors using Python-like underscore _ character.

ballerina has a any types, classes and objects. Object creation uses the new keyword, such as java. ballerina enum types are shortcuts for unions of string constants, unlike C. The match statement is like switch case instruction in C, only more flexible. Ballerina allows type inference to a var keyword. Functions in Ballerina are first-class types, so Ballerina can be used as a functional programming language. Ballerina supports asynchronous programming with the start, future, waitand cancel keywords; these run on strandswhich are logical threads.

Also Read:  Should you leave Facebook, Twitter, and Instagram for the fediverse?

Ballerina provides distinctive network services, XML tables and types, concurrency and transactions, and various advanced features. All of this is worth exploring carefully; there is too much for me to summarize here. The program in the image below should give you an idea of ​​some of them.

ballerina 01 IDG

This example on the Ballerina home page shows the code and sequence diagram of a program that pulls GitHub issues from a repository and adds each issue as a new row to a Google spreadsheet. The code and the diagram are linked; a change to one will update the other. The access tokens must be filled in to the question marks before the program can be run, and the ballerinax/googleapis.sheets package must be pulled from Ballerina Central, either using the “Pull Unresolved Modules” code action in VS Code or using the bal pull Command from the CLI.

Ballerina Standard Libraries and Extensions

There are over a thousand packages in the Ballerina Central repository. They include the Ballerina standard library (ballerina/*), extensions written by Ballerina (ballerinax/*), and some demos and third-party extensions.

The standard library is documented here. Extensions written by Ballerina tend to be connectors to third-party products such as databases, watch systems, event streams, and common web APIs such as GitHub, Slack, and Salesforce.

Anyone can create an organization and post (submit) a package to Ballerina Central. Please note that all packages in this repository are public. You can of course push your code to GitHub or another source code repository and control access to that.

ballerina installation

You can install Ballerina by downloading the appropriate package for your Windows, Linux, or macOS system and then running the installer. There are additional installation options, including building from source code. Then run bal version from the command line to verify a successful installation.

Also, you need to install the Ballerina plugin for your preferred editor. The documentation recommends Visual Studio Code, and that’s what I used, but you can also use IntelliJ IDEA if you want, though it’s not clear how well the IntelliJ plugin is currently supported. I only found out about it by browsing Ballerina’s source code repositories on GitHub.

You can verify that the Ballerina extension has been installed correctly in VS Code by running View->Command Palette->Ballerina. You should see about 20 commands.

The bal command line

The bal command line is a Ballerina source code management tool that helps you manage Ballerina packages and modules, test, compile and run programs. It also allows you to easily install, upgrade, and switch between Ballerina distributions. See the screenshot below, which shows part of the output of bal helpor consult the documentation.

ballerina bal help lg IDG

bal help displays the various subcommands available from the Ballerina command line. Commands include compilation, packaging, scaffolding and code generation, and documentation generation.

Examples of dancers

Ballerina has, well, a batch You can find them on the Ballerina by Example learn page, and also in VS Code by running the Ballerina: Show Examples domain. Reviewing the examples is an alternate way to learn Ballerina programming; it’s a nice complement to tutorials and documentation, and it supports unstructured discovery and deliberate searches.

A word of caution about the examples: not all of them are self-explanatory, as if they were written by an intern who knew the product without thinking about the students or getting any reviews from naive users. On the other hand, many are self-explanatory and/or include links to relevant documentation and source code.

For example, while browsing the examples, I discovered that Ballerina has a testing framework, Testarina, which is defined in the module ballerina/test. He test module defines the necessary annotations to build a test suite, like @test:Config {}and the assertions you can expect if you’re familiar with JUnit, Rails unit tests, or any similar testing framework, for example, the assertion test:assertEquals(). He test The module also defines ways to specify setup and teardown functions, specify mock functions, and set test dependencies.

examples of dancers IDG

Examples of ballerinas, seen from VS Code Ballerina: Show Examples domain. Similar functionality is available online.

Overall, Ballerina is a useful and feature-rich programming language for its intended purpose, which is cloud-oriented programming, and it’s free open source. It doesn’t produce the fastest runtime modules I’ve ever used, but that issue is being addressed, both with GraalVM’s experimental native images and with the planned nBallerina project, which will compile to native code.

At this point, it might be worth adopting Ballerina for internal projects that integrate Internet services and don’t need to run fast or be beautiful. Certainly the price is right.

Cost: Ballerina Platform and Ballerina Language: Free open source under the Apache License 2.0. Choreo Hosting: $150 per component per month after five free components, plus infrastructure costs.

Platform: Windows, Linux, macOS; Visual Studio Code and JetBrains IDEA.

Copyright © 2023 IDG Communications, Inc.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *