Groovy Programming Introduction _java

Source: Internet
Author: User
Tags assert closure data structures numeric value readable advantage

When a Java developer joins groovy's development trip, he/she often takes Java thinking and learns about groovy, learning one feature at a time, which allows him to slowly become more creative and write groovy code that is more in line with language habits. The purpose of this article is to guide these developers to learn basic groovy programming styles, learn new operational techniques, new language features such as closures, and so on. This article will not be described in detail, but to give readers a guide to the introduction, and let the reader in the future in-depth study lay a good foundation. If you like this article, you can contribute a part of your strength to enrich it.

No semicolon

C + +/C #/Java Developers often use semicolons everywhere. While groovy supports 99% Java syntax, sometimes you simply paste Java code into a groovy program, but with a whole bunch of semicolons. In groovy, semicolons are optional, you can omit them, and the more common use is to delete them.

Returns the keyword (return) to become optional

In Groovy's world, the end of a method's program block can return a value without writing the ' return ' keyword. Especially for the methods and closures with few statements. The wording is more elegant and concise:

String ToString () {return "a server"}
String ToString () {"A server"}

But some things are not so graceful, for example, you use variables and appear two times in two lines:

def props () {
  def m1 = [A:1, b:2]
  m2 = m1.findall {k, v-> v%2==0}
  m2.c =3
  m2
}

In this example, either a blank line followed by the last expression or an explicit ' return ' keyword makes the code more readable.

My own personal habits, sometimes like to use the return keyword, and sometimes do not like, this is related to personal taste. However, more often than not, for example, in closures, I prefer not to write the return keyword. So even if the return keyword is optional, it will not force you to use it, if you think it will break the readability of the code.


Be cautious, however, when you use the DEF keyword definition instead of a method defined in place of a specific type, sometimes you'll be surprised to find that the last expression returns as a result. So more often it is more recommended to use a specific type (such as void or type) as the return type. In our example above, if we forget to put the M2 on the last line and act as the return value, then the last expression will be m2.c = 3, which will result in the value 3 being returned as the return value rather than the result we expect.

Like the If/else statement, the Try/cath statement can also return a value because the "last expression" inside them is returned.

def foo (n) {
  if (n ==1) {
    "Roshan"
  }else{
    "Dawrani"
  }
 
Assertfoo (1) = = "Roshan"
Assertfoo (2) = = "Dawrani"

Def and type

When we talk about Def and types, I often find that some developers use both ' def ' and ' type '. But ' def ' is superfluous here. So, you have to make a choice, you don't need ' def ', or you use a type.

So don't write the following code:

def String name = "Guillaume"

can be written

String name = "Guillaume"

When we use def inside groovy, the real type is object (so you can assign any object to a variable defined with Def, and you can return it as any object type when a method uses Def as the return value).

When a method does not declare a variable type, you can use Def, but this is not necessary, so you can omit it, so you can replace the following statement:

void DoSomething (Def param1, Def param2) {}

Recommended:

void DoSomething (param1, param2) {}

However, as we mentioned at the end of the article, we recommend specifying the type for the parameter of the method. This can help improve the readability of your code, help your IDE tools make your code complete, or take advantage of groovy's static type checking or static compilation capabilities.

Another def extra place is to define a constructor and avoid using:

Class MyClass {
  def MyClass () {}
}

You should remove the ' Def ' before the constructor:

Classmyclass {
  MyClass () {}
}}

The default public

By default, groovy would assume that classes and methods are defined as ' public '. So you don't need to explicitly declare public. When you need to declare it as non-public, you need to specify the modifier explicitly.

So avoid the following wording:

public class Server {public
  String toString () {return "a Server"}
}

It is recommended to use the following concise wording

Class Server {
  String toString () {"A Server"}
}

You may be concerned about the accessibility issues within the package scope. In fact, groovy allows you to omit public because this package scope does not support public by default, but in fact there is another groovy annotation syntax to achieve accessibility:

Class Server {
  @Package scopecluster cluster
}

Omit parentheses

Groovy allows you to omit parentheses in top-level expressions, such as println statements:

Println "Hello" method
A, b

Contrast:

println ("Hello") method
(A, B)

When the last parameter of the method is a closure, such as using Groovy's ' each ' iteration mechanism, you can put the closure outside the parentheses, or even omit the parentheses:

List.each ({println it})
List.each () {println it}
List.each {println It}

Usually we recommend using the third style above, which is more natural because it is superfluous to have no parentheses!

But groovy does not allow you to remove parentheses in certain situations. As I said before, the top-level expression can be omitted, but the nested method or the right side of the assignment expression, you cannot omit:

def foo (n) {n}


println foo1//error notation
def m = foo1


class, Level citizens

In groovy, the. class suffix is unwanted, a bit like the Java instanceof.

For example:

Connection.dopost (Base_uri + "/modify.hqu", params, Resourcesresponse.class)

Below we use gstring and use the first class of citizens:

Connection.dopost ("${base_uri}/modify.hqu", params, resourcesresponse)

Getters and Setters

In the groovy world, getters and setters are what we often call "attributes," and Groovy provides a shortcut to annotation syntax to give us access to or assign a value to a property. To discard Java-style getters/setters, you can use annotation syntax:

Resourcegroup.getresourceprototype () getName () = = Server_type_name
ResourceGroup.resourcePrototype.name = = Server_type_name
 
resourceprototype.setname ("something")
resourceprototype.name = "Something"

When you write beans in groovy, we usually call it Pogos (normal Groovy object), you don't have to create the attributes, and the Getters/setters method, but leave it to the groovy compiler to do it.

So, no longer need to write this:

Class Person {
  private string name
  string GetName () {returnname}
  void SetName (String name) {this.name = Nam e}
}

But:

Class Person {
  String name
}

As you can see, a simple "property" without any access modifiers will allow the groovy compiler to automatically generate a private property and getter and setter method for you.

When you use such a Pogos object in Java, the getter and setter methods actually exist, and of course they are the same as normal writing.

Although the compiler can create getter/setter methods, but when you need to add some special logic to the method or the default Getter/setter method, you can define it yourself, and the compiler will automatically choose your logic instead of the default logic.

Initializing beans with named arguments and the default constructor

There is such a bean:

Class Server {
  String name
  Cluster Cluster
}

To avoid trouble like the following:

def server =newserver ()
server.name = "Obelix"
server.cluster = Acluster

You can use named parameters and the default constructor (the constructor is called first, and then the setter method is called):

def server =newserver (name: "Obelix", Cluster:acluster)

Using the WITH () syntax in the same bean to handle repetitive operations

In the default constructor, named parameters are a very interesting thing to do when creating new instances. But when you need to update an instance, do you need to repeatedly beat the ' server ' prefix before the variable? The answer is no because, thanks to the WITH () statement, groovy will automatically fill you in:

Server.name = Application.Name
server.status = status
server.sessioncount =3 server.start
()
Server.stop ()

Contrast:

Server.with {
  name = Application.Name
  status = Status
  sessioncount =3
  start ()
  Stop ()
}

equals and = =

In the Java world, = = is the equivalent of the IS () method in groovy, and groovy's = = is the smart equal () Method!

When you need to compare object references, you should use groovy's = =, because he will help you avoid nullpointerexception, and you don't need to care whether the left or right side of the operator is null.

It should not be written like this:

Status!=null&& status.equals (controlconstants.status_completed)

But:

Status = = Controlconstants.status_completed


gstrings ()

We often use string and variable connections in Java, and use a lot of double quotes, plus signs, and \ n characters to create a new line. Using an interpolation string (called gstrings in Groovy) simplifies our code:

throw new Exception ("Unable to convert resource:" + Resource)

Contrast:

throw new Exception ("Unable to convert resource: ${resource}")
Inside the curly braces, you can put any expression, not just a variable. For simple variables, or variable attributes, you can even throw out curly braces:

throw new Exception ("Unable to convert resource: $resource")
You can even delay the calculation of an expression by means of a closure annotation (${-> resource}). When the gstring variable is cast to a string variable, it automatically evaluates the closure value and calls the ToString () method as the return value. For example:

int i =3
 
def s1 = "I ' Value is: ${i}"
def s2 = "I's value is: ${-> i}"
 
i++
 
asserts1 = = "I ' Value is:3"/ /pre-calculated, assign value
asserts2 = = "I ' Value is:4"//latency calculation at creation time, using the latest variable value

In Java, string concatenation is a very cumbersome one:

throw new Pluginexception ("Failed to execute command list-applications:" +
  "the group with name" +
  PARAMETERMAP.G Roupname[0] +
  "is not compatible group of type" +
  server_type_name)

You can use the \ Continuous character (this is not equivalent to multiple lines of text)

 
throw new Pluginexception ("Failed to execute command list-applications: \" The
group with name ${parametermap.groupna Me[0]} \ is not
compatible group of type ${server_type_name} ")

Or you can use three double quotes to implement multiple lines of text:

throw new Pluginexception ("" "Failed to execute command list-applications: The
  group with name ${ Parametermap.groupname[0]} is not
  compatible group of type ${server_type_name)} "" "

Alternatively, you can use the. stripindent () function to delete extra spaces left in multiple lines of text.


Also note the difference between the single and double quotes in groovy: Single quotes are typically used to create Java strings, without any interpolation variables, and double quotes can create Java strings and can be used to create gstrings with interpolated variables.

For multiline strings, you can use three quotes: for example, use three double quotes in the gstrings variable, and three single quotes in a simple string variable.

If you need to write regular expressions, you must use the slash character markers:

Assert "Foooo/baaaaar" ==~/fo+\/ba+r/

The advantage of the slash mark is that you don't have to write two backslashes to escape and make the regular expression simpler.

Last but not unimportant, use single quotes to define the amount of character constants, and double quotes to define the strings that need to use the interpolation function.


native data structure syntax

Groovy provides native syntax for data structures, such as lists, maps, regular expressions, or a range of values. Make good use of them in your groovy program.

Here are some examples of the use of those native data structures:

def list = [1,4,6,9]
 
///By default, keys are characters, so there's no need to enclose them in quotes
//You can use with () contains keys, such as using [(state variables): state names], using variables or objects as key
def map = [CA: ' California ', MI: ' Michigan ']
 
def range =10..20
def pattern = ~/fo*/
 
//equivalent to add ()
list <<5
 
//Call contains ()
assert4in List
   assert5in list
assert15in range
 
/subscript
assertlist[1] ==4
 
//Add key value pair
map << [WA: ' Washington ']
//subscript
assertmap[' CA '] = = ' California '
/property
Assertmap. WA = = ' Washington '
 
///Use regular expression to match string
assert ' foo ' =~ pattern

Grovvy Development Tools

Let's go on to say the data structure, when you need an iterative set, groovy provides a very rich way to decorate Java's core data structures, such as each{}, find{}, findall{}, every{}, collect{}, inject{}. These methods add some fun to the programming language and help us to design complex algorithms more easily. With adorners, a number of new methods have been applied to various types of Java, thanks to the dynamic nature of the language. You can find more use in strings, files, streams, collections, or other methods:

http://groovy.codehaus.org/groovy-jdk/

The power of the switch

Groovy's switch is more powerful than the C language family because they typically only receive basic data types and. Groovy's switch can accept a rich data type:

def x =1.23
def result = '
switch (x) {case
  ' foo ': result = ' found foo '
  //lets fall through case
  ' bar ': Result + = "Bar"
  case[4,5,6, ' in List ']: Result
    = "List" broke case
  12..30: Result
    = "range"
    Break Case
  Integer: Result
    = ' integer ' break Case number: result
    = ' number '
    break
  Default:result = "Default"
}
assert result = = "Number"

Typically, you can use the Iscase () method to determine whether a numeric value is case-insensitive.

Alias Imports Import aliasing

Java, when you want to use a class with the same name from two different packages, such as

Java.util.List and Java.awt.List, you can import one of these classes, and the other you have to rename them effectively.

There are times when we often use a class with a very long name in the code, making the whole code bloated.

To improve these conditions, Groovy provides an alias-import feature:

Importjava.util.List as Julist
importjava.awt.List as Alist


When importjava.awt.WindowConstants as WC//import, use as to set an alias
Of course, you can also statically import a method:

Import static pkg. Someclass.foo
foo ()


Groovy's Truth system

All objects in groovy can be coerced to a Boolean value: null, void, or null values are treated as false, others are treated as true.

So don't write this code again: if (name!= null && name.length > 0) {} instead: if (name) {}

The same applies for collections and other data types.

Therefore, you can use this simple method in judgment conditions such as the while (), the IF (), the triple-order operator, the Elvis operator (speak below), and so on.
More powerful is that you can add a Asboolean () method to your class to customize the truth of your class.

Safe Action Object graph (nested objects) Safe graph navigation

Groovy supports the use of. operator to safely manipulate an object graph.
In Java, if you are interested in a node in an object graph and want to check whether it is null, you often write complex if-embedded code, as follows:

if (order!=null) {//1
  if (Order.getcustomer ()!=null) {//2
    if (Order.getcustomer (). GetAddress ()!=null) {//3< C3/>system.out.println (Order.getcustomer (). getaddress ());}}}

And using Groovy's security operator? The above code can be simplified to:

println order? Customer?. Address

It's so subtle.

Operation connected to each? The elements in front of the operator are checked for NULL, and if NULL, the NullPointerException is thrown and a null value is returned

Assert assert

To check parameters, return values, and so on, you can use an Assert statement.

In contrast to the Java assert, Groovy's assert does not need to be activated separately.

def check (String name) {
  //name Non-null and Non-empty according to Groovy Truth
  assertname
  /safe Naviga tion + Groovy Truth to check
  assertname? Size () >3
}

You will notice that Groovy's power Assert statement provides better output, including a graphical view of different values for each subexpression assertion.

Elvis (Elvis)?: operator assigns a default value to a variable

?: is a very convenient operator to assign a default value to a variable, he is a three-mesh operator (xx?). A:B) is abbreviated.
We often write the following three mesh operation code:

def result = Name!=null? Name: "Unknown"///if Name is null to give ' Unknown ' default value, otherwise the value of the original name

Thanks to Groovy's truth system, NULL checks can be simply directly judged by ' name ' and null will be turned to false.
In a bit more, since you have to return ' name ', it's cumbersome to repeat the name two times in the three-mesh operator, and you can remove the duplicate variable that is entered between the question mark and the colon, and it becomes the Elvis operator, as follows:

def result = name?: "Unknown"  //"Unknown" if Judge name is false, or the value of name <span></span>


Catch any exceptions

If you don't really care about the exception thrown in a try block, groovy can simply catch all of these exceptions and ignore their exception types. So later, like this code to catch exceptions:

try{
  //...
} catch (Throwable t) {
  //Something bad happens
}

Can be written to catch any exception (' Any ' or ' all ', or whatever else you think is "arbitrary"):

try{
  //...
} catch (Any) {
  //Something bad happens
}


Optional Type Recommendations

Finally, I'll discuss when and how to use the ' optional type ' feature.
Groovy lets you decide whether to display a strong type or use the DEF keyword to declare what you want, so how do you decide?

I have a fairly simple rule of thumb:

When you write code that will be used as a public API to others, you should always use a strongly typed statement.

This makes the interface conventions clearer, avoiding the passing of possible error type parameters, and facilitating the provision of more readable documents, which, when editing a private method that you can only use, enforces the IDE's code completion or makes it easier for the IDE to infer the object's type. Then you'll be more comfortable deciding whether to use a specific type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.