Sunday, March 2, 2014

Groovy Tutorial 3: Variables, Objects and Classes: Part 1

As we saw in the last tutorial, variables are memory locations where we store values. We also said that in Groovy, everything is an object. So what exactly are objects?
Object-Oriented Programming (OOP)
There are many programming paradigms, each with its own strengths and weaknesses. OOP is well-suited to large and complex software systems due to its various properties such as information hiding and encapsulation.
In OOP, the building blocks of a software system are classes and objects. Classes are like a blueprint of an entity, whether concrete e.g. person, document, car or building, or abstract, such as the state of a game, an idea or a communication/ http session. Objects are instances of a class, or the realization of the blueprint (class).
Classes
Classes are blueprints or templates of a program’s building block. They group together data and operations relevant to that data. Classes are composed of fields and methods. Fields store the state of a class’ instantiation i.e. an object, while methods represent the behavior of a class.
For example, the class car will have fields to represent color, mileage and registration number while its methods will be getColor(), setMileage(), addMileage() and getRegNum(). As you can guess, each determines the way we can interact with fields.
This provides a way of achieving two of the core principle of object-oriented programming, encapsulation and information-hiding. Encapsulation means grouping together relevant information, ‘in a capsule’. Information-hiding is achieved through being able to access and modify fields via methods using access modifiers. Access modifiers will be discussed in greater detail in the next tutorial. We shall now get to code samples to show examples of using classes and object since there is much more to OOP than I can cover in this tutorial. You should definitely check it out in more detail.
By convention, variable, class and object names use camel-case, with class names starting with a capital letter while variable, object, field and method names start in lowercase.
When saving a groovy script/ file, make sure it is does not clash with any class names in the script.
Persons.groovy
class Person
{
    def name //defines a property
    def income
    def gender
}
def p1=new Person()
p1.name='Cabee'
p1.income=7000000
p1.gender='Male'
println p1.name
Output
Cabee

To see what happens when you give a file a name used in as a class name, change both instances of Person to Persons. The following compilation error will be thrown:
Invalid duplicate class definition…
For java developers, the thing to remember is that Groovy will create the getters and setters in the background, thus p1.name does not reference the field name but rather, calls the auto-created setName() method in the background.
To show some of the syntactic sugar Groovy adds to classes, here is a slightly longer code sample we shall look into more details in the next tutorial:
class Persona
{
    def name //defines a property
    def income
    def gender
}
def p1=new Persona()
p1.name='Cabee'
p1.income=7000000
p1.gender='Male'
println "name: $p1.name"
println "income: $p1.income"
println "gender: $p1.gender"
println()
p1=new Persona([name:'David',income:500000,gender:'Male'])
println "name: $p1.name"
println "income: $p1.income"
println "gender: $p1.gender"

Output
name: Cabee
income: 7000000
gender: Male

name: David
income: 500000
gender: Male
In the next tutorial, we shall look at constructors, access modifiers to control data access and get into classes and objects in more details.
Happy coding with Cabee Groovy Mastery Course!!!

Sunday, February 9, 2014

Groovy Tutorial 2: Variables




For those new to programming, variables are memory locations we reserve for values we will use. They are like a basket into which we can put items. For java developers, the thing to remember is that groovy is both a scripting and a dynamic language. We shall look into greater detail about dynamic typing.
 
Dynamic typing means that unlike in Java and other statically-type languages where a variable has a specific type such as String and only takes values of that type, Groovy allows you to change the type as well as value of the variable simply by assigning it a value or object reference of a different type. This is possible since everything in Groovy is an object, and inherits the java super class Object. 
Being a scripting language, we need neither a class nor a main method to act as our entry point to the program. Groovy will simply run any expressions you have in a file. At this point, I’m assuming you have downloaded and installed groovy as well as the Java Development Kit (JDK), or its equivalent for your platform.
You can download Groovy for free as well as access its documentation and installation steps for various platforms at Codehaus.
Declaring Variables
Variables are declared using the def keyword. For your first example on declaring variables, start up your favourite text editor or the GroovyConsole and type this code:
def x=35 //age
println x
Save the file as age1.groovy. This creates a groovy script names age1.groovy. Go to the command-line and navigate to the folder containing your script and type
 groovy age1.groovy  
   Output
35
If you are using GroovyConsole, you can simply run the script by going to Script > Run or using the shortcut Ctrl+R without saving the script.

Everything is an Object
Java programmers are prone to think that x is an int. However, in Groovy, there are no primitives. The variable x is of type java.lang.Integer, which is a class, making x an object. (Objects and Classes will be discussed shortly).
To ascertain this, add another line to age so it now looks like this:
def x=35 //age
println x
println x.getClass() //print x’s class

Output
35
class java.lang.Integer

Groovy is Dynamic

As stated earlier, you can change the type of a variable simply by assigning a value of a different kind. To illustrate this, modify the script you created earlier as shown:
def x=35 //age
println x
println x.getClass() //print x’s class
x="Cabee's Grovy Mastery Course is Awesome"
println x
println x.getClass()
Output
2
class java.lang.Integer
Cabee's Grovy Mastery Course is Awesome
class java.lang.String
You can force a variable to take only values of a given type by explicitly providing the data type of the variable. 
Replace def with Integer and run the script. It will result in a GroovyCastException after printing class java.lang.Integer (Groovy is interpreted).
For more on variables, types, classes, objects and typing, check out the coming tutorials.
Happy coding with Cabee Grovy Mastery Course!!!

Thursday, January 23, 2014

Groovy Tutorial 1: Why Learn Groovy?

Groovy Tutorial 1: Why Learn Groovy?
For most people who are not java developers, Java is a language, the one used to write Android apps. However, not only is Java a great language for Enterprise apps as well as small computing devices such as card and FFID readers as well as smart cards, it is a whole ecosystem compromising the language, the libraries as well as the JVM.
The Java Virtual Machine is a powerful tool that any programmer can harness, and can technically run on a computer with no OS, which is what allows it to run on SIM cards and other computing platforms that run firmware or with rudimentary OSes.
Several languages can run on the JVM, including Groovy, Scala, JRuby, JPython and many more. They allows for easy integration with Java, harnessing the benefits of Java’s JVM while maintaining the syntax of the respective languages they are derived from.  
For Java Developers however, Groovy is the language to go with. Any Java code is Groovy code, and while most of the other languages running on the JVM can make the same claim, Groovy is designed to maintain Java’s syntax. It offers features that are only coming to Java such as closures and many more, more succinct and beautiful code…
We will get to more reasons for why you should learn Groovy, but here they are in passing:
Succinct
Extends the JDK.
Meta programming!!!!
Flat learning curve.
Fully Dynamic.
It is fun and awesome and cool and, am losing the plot here….
Here are a few code samples to demonstrate Groovy’s succinctness:
HelloWorld.groovy
println 'Hello World'
Output
Hello Word



HelloYou.groovy
def name='My name'
println "Hello $name"
Output
Hello My name

PrintNames.groovy
def printName={it -> print "$it " }
def names=["Groovy","is",'simply','Awesome']
names.each(printName)  //the braces are optional i.e. names.map printName
Output
Groovy is simply Awesome
Happy coding with Cabee Grovy Mastery Course!!!