A Better Java and Beyond – Hello Kotlin

For the uninitiated, Kotlin is a relatively new language that is taking the programming community by storm. In the jungle of thousands of programming languages, Kotlin grabbed attention when Google announced it as the officially supported language for Android development at Google I/O in May 2017. All the new android phones that will be launched in 2017 will support Kotlin including mobiles under 10000.

What is so special about Kotlin? Should you consider Kotlin for your next project? This article gives a bird eye-view.

Kotlin Takes the Crown as the “Better Java”

Given Java’s popularity and #1 position, the “Better Java” title is not just about beating Java but becoming #1 programming language. Because of this, all application programming languages get compared against Java. While Java kept losing some developers to these languages over the years, it still manages to retain the top spot. In spite of the widely discussed nuances of Java, the programmers –by and large– would not switch to other languages, because there were always some shortcomings of the newer languages as compared to Java. (We covered why Java remains popular in our post The Irresistible Charms of Java).

With Kotlin, the wait for the “better Java” seems to be over. While Kotlin is still far from Java’s #1 position, it has climbed rapidly into the top 50 languages in June 2017. Google Developer Groups are covering Kotlin workshops with great interest and there is a lot of uproar over the net, so for sure it will be spreading rapidly.

Kotlin claims the “Better Java” crown, because:

  1. It hits where Java hurts – It does away with senseless getter/setters that are needed in Java. It has a neat way to avoid null pointer exceptions. It uses syntactic sugar and a little bit of functional programming to reduce the number of lines of code and make many programming tasks trivial. Java cannot implement these cool features because it would otherwise break backward compatibility.
  2. It provides interoperability with Java – Instead of re-inventing the wheel, Kotlin works perfectly with Java. It can use Java libraries and frameworks, so on day 1 it already has a rich ecosystem.
  3. It does not let you sacrifice the robustness – Static typing avoids a certain class of possible errors and hence a must for robust, enterprise-grade systems. However, a lot of Java’s verbosity is attributed to it. Kotlin not only retains static typing in its full fervor, but it does so while being concise, and further contributes to more robustness (in terms of var/val distinction and null pointer treatment).
  4. The syntax is clean and readable – It is readable even to those who do not understand the syntax of the language. The designers of Kotlin have deliberately kept away the constructs that could make the code hard to read.
  5. It rolls out a red carpet for the Java developers to switch – Kotlin is just a few concepts away for a Java developer. Apart from a short learning curve, there is an automatic Java to Kotlin converter. Finally, the interoperability promise is that you can convert your Java project to Kotlin one-file-at-a-time instead of doing a complete conversion.

One may notice that the dynamic programming languages such as Python and Ruby lose out on the support of static typing. Scala is a close contender with Java interoperability, powerful functional programming support and more abilities than Kotlin. However, it loses out because the learning curve is pretty high and the syntax can become obscure. Here is a good article comparing Kotlin vs Scala. Although coming from Kotlin camp, the arguments are quite well-balanced.

Kotlin Targets More Beyond Being Just a Better Java

As we saw before, Kotlin establishes itself as a good language aimed at robustness with a clean and concise syntax, and woos the largest chunk of developers (read: the Java developers) with its superior features. But the language designers are not satisfied with just a better Java. With the Java use case as a foundation, they are moving to pastures where other languages have established themselves.

A good example is Javascript which has established itself as the de-facto language on the browser platform and on node.js server-side framework. If you need a type-safe version of Javascript, then you need to use Typescript which essentially creates Javascript code. Similarly, Kotlin programs –which are also type-safe as we saw before– will also generate Javascript code. However, between Typescript and Kotlin, Kotlin is a much better language. Also, developers who flock to Kotlin from Java side will anyways find it easier to code in Kotlin than learn the nuances of Typescript (or even Javascript, which is not as straightforward to understand as one would like it to be).

By generalizing the Java and Javascript use cases, one can see how Kotlin is going. On any given platform, Kotlin would just compile into the de-facto standard of the platform. This minimizes any friction because from day 1, Kotlin has all the necessary features that are needed for developing on the platform. They are already working on Kotlin native which can be used on small devices in IoT and they are also looking at going to the iOS platform as well.

This translates into great advantages for the developers who learn Kotlin. They will be able to practically code to almost any platform as they desire in Kotlin itself.

As a small digression, it is interesting to compare the Kotlin strategy with the strategy that Java had applied and which helped Java spread and become number 1 for so many years. Java also targeted to be on every platform, on every device. Remember their famous slogan “Write Once, Run Anywhere”? One can say the same thing now about where Kotlin is heading. However, there is one significant difference. Java went to every platform with its “Java Virtual Machine (JVM)” technology. The USP was more of the JVM technology than the language features. Today, Kotlin’s strategy is to use the existing technology but with superior language capabilities.

Start a Kotlin Project: “The Python Paradox” Will Work Out for You

Even with all its superiority over Java, it does not happen that all developers migrate to Kotlin overnight. The ecosystem takes some time to catch up, and so the language would take time for it to become mainstream. In terms of technology adoption cycle, we are at a point where the early majority has slowly started coming in. (Google’s push helped here.)

While the masses are still not there, this would be a great time to start a Kotlin project. When Python was at a similar phase of technology adoption, Paul Graham argued that starting a project in Python would attract smart developers, because only those who genuinely love to do coding would have learned Python then. The same argument goes today for Kotlin. Start your next project in Kotlin and you are sure to get only the good programmers on it.

Also, given how Kotlin is rising, it would be a safe bet to project that there would be a sizable number of Kotlin programmers around us in future, to help maintain and enhance the Kotlin projects.

Unlock the power of sealed classes with reactive bus

Unlock the power of sealed classes with reactive bus

A couple of days ago, in the midst of a conversion-to-Kotlin surge, I’ve stumbled upon an old bus implementation. As it always happens in these cases, my fingers moved automatically, and two seconds after my class was already in Kotlin.

I’ve stared at it though, unsatisfied. In that naive conversion, there was something missing. I was wondering, which Kotlin unique feature can I use to go where no Java developer has never been before?

After minutes of tinkering, finally, the illumination: sealed classes!

But let’s start from the beginning!

The Reactive Bus

A bus implementation comes really in handy when you want to decouple the execution from the place when an event happens, keep a bunch of diverse objects updated or implement a command pattern.

With RxJava its implementation is really straightforward.

Things are getting a bit awry if we want to post on this bus a large variety of different events: let’s say, multiple events from your user interface. In this case, a single type wouldn’t fit.

We can use a container class, let’s say ReactiveEvent<T>, wrapped around yet another generic type T and use this wrapper to fill the traffic on our bus. The downside of this approach is that we can potentially create a container of any type, and the more the project will scale, the more of different events we’ll need to handle, the more messy and untidy will be the subscriber code.

Using Sealed classes

I’ll avoid introducing once again the sealed classes: if you ended up reading this article, you might know more than me about this argument. They become really useful in combination with a bus implementation, lettin’ us keep our code sleek and well-ordered.

Let’s say our bus would contain only events generated from user actions, such pressing a Button or start typing on a TextView.

We can think of a super-type UserEvent that is extended by two classes representing two specific user actions:

Every event contains a field that defines an aspect of the performed action, such a the timestamp or the initial typed text. Here we can let our fantasy drives us and enrich them with all the details we’d need later on. 

Side note: the extended classes can also be data classes.

Next step would be communicating to our bus that we want to post and receive only instances of these two classes. This is easily achieved by implementing the bus with the sealed class super-type: ReactiveBus<UserEvent>.

Compile-time advantages

If we show the Kotlin’ compiler we’re a good sealed-class citizen, it will reward us with a lot of aids and warnings when we’re about to do something wrong. All of this even before it comes into our mind to hit run and compile the project.

Let’s imagine that while you’re coding, you find yourself suddenly drunk (it can totally happen, especially on Friday late afternoons) and you want to pass an instance of type String into the bus. You don’t notice that this wouldn’t work (as you’re drunk), but it happens that the compiler does.

It will not only promptly warn us that among all the classes allowed to be posted in the bus, unfortunately, String is not one of those, but it will also generate a compiler error, forcing us to deal with it.

Another advantage comes when we start writing the subscriber logic to handle these events, as we can make use of the never-too-esteemed whenblock to easily filter them. This block is easily the best an Android developer can get in terms of code cleanness.

Note that for every branch the received instance will be smart-casted automagically to the checked type, allowing us to access them without additional code.

Cool huh? But it is even cooler considering that the compiler will suggest us this code even before we start writing it.

Or bothering us (with another error) if we are missing a branch.

Conclusion

Sealed classes is a wonderful Kotlin specific feature, especially when is combined with the checks the compiler is able to perform while we’rewriting. Using them, together with all the other features Kotlin has to offer, will let us not only write a more idiomatic code, but also a safer one.

Launching A Static Site With React & AWS CloudFront

After months of dragging my feet and contemplating ideas I finally got around to redesigning my personal website. Visually, it’s not winning any awards. It’s simple and to the point and I wanted to keep the back-end just as simple. I’ve used services like DigitalOcean and Heroku in the past to host websites for clients and just found it a pain to setup load balancing and perform general server maintenance. Those tasks don’t have to be difficult and usually aren’t but I’d rather spend my time actually developing software for clients.

AWS as an alternative offers static website hosting through a combination of S3 and their CloudFront CDN service. I’ve personally found the freedom from concerns about scale and server maintenance alone to be worth the switch. The speed increases from having the site served through a CDN and cost savings don’t hurt either. Read more about Cloudfront here.

In this article we will:

  • Generate a static website using Create React App
  • Configure an AWS IAM user to manage our website on AWS
  • Use an AWS CloudFormation template to generate our AWS CloudFront stack
  • Deploy the website using the AWS CLI

Before beginning you should have:

  • A beginner’s understanding of React, Create React App ,and
  • AWS resources (CloudFormation, CloudFront, IAM, S3). I will not cover these in great detail as the documentation available is quite extensive.

This example is available here on github.


The Website

For the sake of this article, we won’t be doing anything other than creating an app using Create React App and running

yarn run build

If you have an existing website you would like to use, ensure it is static (does not run a server like Express). Once you have your app built you are ready to proceed.

AWS IAM configuration

As an IAM best practice, it’s important we not use our root account to access AWS. Learn more here. If you do not already have an IAM user outside of your root account, create one following the AWS user guide here.

When your IAM user has been created, make a note of the User ARN as we’ll be using it in our CloudFormation template to give this user permission to manage our resources. Your user should atleast have permission to manage S3, CloudFormation, and CloudFront resources.

The CloudFormation template

AWS CloudFormation is great. It provides us a simple way to manage a collection of Amazon resources from a single location. A great benefit is that we can add it to Git and track how our stack has changed over time, making it easier to return to a stable configuration in the event you make a serious error in the future.

In the interest of brevity, I’ve included my CloudFormation template below. You’ll have to make some modifications to get it to work for you. When deployed, it will create 2 S3 buckets, 2 S3 bucket policies, and the CloudFront distribution resource.

AWSTemplateFormatVersion: 2010-09-09
Resources:
  myDistribution:
    Type: 'AWS::CloudFront::Distribution'
    Properties:
      DistributionConfig:
        Origins:
          - DomainName: mys3bucket-example.s3.amazonaws.com
            Id: S3Origin
            S3OriginConfig:
              OriginAccessIdentity: ''
        Enabled: 'true'
        DefaultRootObject: index.html
        Logging:
          IncludeCookies: 'false'
          Bucket: mys3logbucket-example.s3.amazonaws.com
          Prefix: myprefix
        DefaultCacheBehavior:
          AllowedMethods:
            - GET
            - HEAD
          TargetOriginId: S3Origin
          ForwardedValues:
            QueryString: 'false'
            Cookies:
              Forward: none
          ViewerProtocolPolicy: allow-all
        PriceClass: PriceClass_100
        ViewerCertificate:
          CloudFrontDefaultCertificate: 'true'
    DependsOn:
      - MyStaticSiteBucket
      - MyLogBucket
  MyStaticSiteBucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: mys3bucket-example
      WebsiteConfiguration:
        IndexDocument: index.html
  MyLogBucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: mys3logbucket-example
    DependsOn:
      - MyStaticSiteBucket
  MyStaticSiteBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref MyStaticSiteBucket
      PolicyDocument:
        Statement:
          - Sid: ReadAccess
            Action:
              - "s3:GetObject"
            Effect: "Allow"
            Resource: 'arn:aws:s3:::mys3bucket-example/*'
            Principal: "*"
          - Sid: ListWriteDeleteAccess
            Action:
              - "s3:ListBucket"
              - "s3:PutObject"
              - "s3:DeleteObject"
            Effect: "Allow"
            Resource:
              - 'arn:aws:s3:::mys3bucket-example/*'
              - 'arn:aws:s3:::mys3bucket-example'
            Principal:
                AWS: 'arn:aws:iam::example:user/myuser'
  MyLogBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref MyLogBucket
      PolicyDocument:
        Statement:
          - Sid: ListReadWriteDeleteAccess
            Action:
              - "s3:ListBucket"
              - "s3:GetObject"
              - "s3:PutObject"
              - "s3:DeleteObject"
            Effect: "Allow"
            Resource:
              - 'arn:aws:s3:::mys3logbucket-example/*'
              - 'arn:aws:s3:::mys3logbucket-example'
            Principal:
                AWS: 'arn:aws:iam::example:user/myuser'

mys3bucket-example – This is the name of the S3 bucket that will contain our website code and function as the store CloudFront. It needs to be a unique name across all existing buckets currently on S3. More can be learned here.

mys3logbucket-example – The name of the S3 bucket that will hold logs generated from our CloudFront stack. Follows the same naming conventions as our other S3 bucket.

example:user/myuser – The IAM user resource name from the Amazon IAM console. Links our user the bucket access policies

AWS CLI

With the template ready, we now need to configure our development environment to connect to AWS. Follow the instructions here to install AWS CLI if you haven’t already and run

aws configure

to link your AWS account. Use your access key and secret key values from the .csv file you downloaded earlier. You can leave the defaults for the region name and output format fields.

Now we’re ready to create our stack! Run the next command from the project’s root directory.

aws cloudformation deploy --stack-name my-cloud-stack --template-file myTemplate.yaml

You should now see CloudFormation building our stack in the AWS console. The deploy command is nice because it will automatically create the stack for us if it doesn’t already exist, and if it does it will perform an update. A more convenient approach to calling the create and update stack commands explicitly. Learn more about deploy here.

When it has completed, run

// "build" is the desired directory to upload
aws s3 sync build s3://mys3bucket-example  --delete

substituting “mys3bucket-example” with your S3 bucket name to upload our build directory to our website store. The --delete option will remove files that are not in the directory we’re uploading.

Note: build specifies the directory to upload to S3. If your production directory is different ie. dist, the command will need to be updated accordingly.

With the completion of the upload you can now navigate to your CloudFront domain name shown in the screenshot or the S3 url and view your page online!

Next Steps

Use a custom domain with your CloudFront hosted website – Limit access to your website so it is only accessible through CloudFront (disable access through the S3 address). Attach a domain name through the Route 53 service and modifying the stack CNAMES.

Error Handling – One of the caveats of serving a React app through a static site is because there is only one entry point (index.html), if visitors try to navigate to another page like /about or /contact they’ll be greeted with an ugly 404 page. One way to address this is to set an Error Document in the S3 bucket properties page, but this only addresses one error status. Another way is to direct all responses to index.html and handle the errors client side, this isn’t the greatest approach however. It doesn’t make the greatest sense to handle a 502 error client side. Defining custom error responses through CloudFront in the AWS console is probably the best solution.

Basic features of Perl programming language

Basic features of Perl programming language

Perl is a high-level programming language which is basically used to do website design. It is used for different purposes but mostly for the network programming, system administration, bioinformatics, and so on. The program Perl was developed to ease the work of the programmer. The programmer uses different programs and languages to web design networking, software related work and so on. Other beginning programs requires a lot of spaces which create pressure on the hard disc. But with the Perl programming, the programmers can write their program easily and quickly. Understanding the Perl programming language is also quite easy for the programmers.

You at first need to install Perl interpreter on your device to use the Perl programming language. If you are using Windows operating system, then there might have a chance of pre installing of this program. However, if the program is not installed, you can install the program from the official website of the Perl. For Unix and Macintosh operating system, you have to download the interpreter in the same way from the perl.com.

Perl has many features like extensibility and reusability of the program which other programs can hardly offer. Few features of the Perl programming language is discussed below.

Cleaner code

The language of the program is not that difficult and understandable by even a novice programmer. The codes written with this program is readable. Unlike the other programs, it doesn’t use the cryptic variables on its program. That is why it is one of the most popular programming languages among its users.

Extensibility and Reusability

The content of this program is easily shareable. The user or programmer can compile this language with the other language and can create programs together. The program is extensible too with the other programs. It is an interpreter program so other programs can be used together with this programming language.

Object oriented program

Perl programming is an object oriented program. Perl programming uses different types of virtual methods to make the program simple. It avoids the complications of using unnecessary syntax and other packages in the program.

Compatibility

Perl is a highly compatible programming language. It can be embedded with the C or C++ programming application. Perl works a dynamic library which can programs from the different sources with high compatibility. Moreover, it can access to different interfaces like DBM, GDBM, NDBM, etc.

So, these are the basic features of the Perl programming language.