Monday, February 12, 2018

Groovy: Advanced Concepts: Data Abstraction

Groovy is an object-oriented language that offers an additional layer of scripting capabilities.  Its data abstraction capabilities are derived from this basic architecture.

Packages and Encapsulation

Groovy allows for organizing classes into packages.  Packages are defined using the package keyword and must be defined at the top of the compilation unit.  Groovy offers additional visibility modifiers that apply to members of a package.  Classes can be marked as protected, which results in them being either available only to other classes in the same package.

Objects and Classes

Java is a class-based language.  This means that Java provides a class-based data abstraction and encapsulation strategy.  In fact, apart from primitives, everything in Java is an object.  There are no standalone data structures or functions.  This means that if a class has a variable that is marked as private, no other class can access that variable.  To access the variable, Java recommends methods to be created in the form of getters and setters, keeping the underlying variables private.
In Java classes can extend an existing class through the sub-classing mechanism.  Classes in Java can only extend a single class.
Groovy offers the same method of data abstraction.  One key addition from Groovy is the automatic creation of getter and setter methods for all variables in a class.  This includes non-Groovy-based classes.
public class JavaClass
{
    // This is a private variable only accessible
    // by instances of this class
    private int privateInt;
    private int anotherPrivateInt = 42;
 
    // The following are getters and setters to provide
    // access to the private variable
    public int getPrivateInt()
    {
        return privateInt;
    }
 
    public void setPrivateInt(int value)
    {
        this.privateInt = value;
    }
}
 
class GroovyClass
{
    private int privateInt
}
 
class GroovyExecutableClass
{
    static void main(String[] args)
    {
        JavaClass jc = new JavaClass()
        jc.setPrivateInt(3)
        println(jc.getPrivateInt())
 
        // Accessing the private variable by the
        // automatic getter/setter
        GroovyClass gc = new GroovyClass()
        gc.privateInt = 4
        println(gc.privateInt)
 
        // Note: Groovy automatically provides the
        // same functionality for existing Java classes
        println(jc.anotherPrivateInt)
    }
}
Groovy’s ability to add automatic getters and setters can be useful, but it can be used to break encapsulation in ways that class writers may not expect.  Any public API that contains private variables are now readable and writable by a Groovy script.  This has caused a fair amount of discussion as to whether this is a true feature, bug or issue.
One addition item of note is how Groovy handles data abstraction in the presence of a trait.  Traits are described in Inclusion Polymorphism.

No comments: