The following provides a simple guide to writing Flex scripts, in orrder to make scripts as small and efficient as possible.
Variable declaration
Aim to usedef
rather than the class name, as it leads to more compact code (IDEs will still be able to provide auto-completion):
// bad
Long count = 123L
NewAssetPlaceholder assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
// good
def count = 123L
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
It is also good practise to declare variables as close as possible to where they are used:
// bad
def enabled = isUdoEnabled() && isParentUdo()
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demoasset')
.build()
if (enabled) {
def asset = assetService.createAsset(assetPl)
}
// good
def enabled = isUdoEnabled() && isParentUdo()
if (enabled) {
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
def asset = assetService.createAsset(assetPl)
}
Variable case
Use camel-case for variables:
// bad
def Outputmessage ='my message'
def outputmessage ='my message'
// good
def outputMessage ='my message'
Flex model object instantiation
This model instantiation should be avoided as it is verbose:
// bad
def assetPl = new NewAssetPlaceholder()
assetPl.type = 'media-asset'
assetPl.name = 'demo asset'
// good
def assetPl = NewAssetPlaceholder.builder()
.type('media-asset')
.name('demo asset')
.build()
// also good
def assetPl = new NewAssetPlaceholder([type: 'media-asset', name: 'demo assert"'])
Strings
Single quotes should be used when not performing string interpolation:
// bad
def myValue ="some value"
// good
def myValue ='some value'
It is better to use string interpolation rather than string concatenation, especially with long strings, as it makes it easier to comprehend:
// bad
def myValue = size + " annotations added to assetID " + assetId + " in " + time + "seconds"
// good
def myValue = "$size annotations added to asset ID $assetId in $time seconds"
Semicolons
Semicolons are not necessary in Groovy, and it is recommended not to use them (inline with the [Apache Groovy Style Guide] (http://groovy-lang.org/style-guide.html)).
if
statements
Avoid the use ofif
statements without curly braces, as it is easy to introduce logic errors if you do not:
// bad
if (somevalue)
callMyFunction()
// good
if (somevalue) {
callMyFunction()
}
Streams
Be sure to close any streams that are opened. For example, the following is bad practice because JVM resources are leaked:
// bad
def execute() {
def fis = new FileInputStream('/flex/flex-enterprise/storage/media/Subtitle.vtt')
def data = IOUtils.toString(fis, Charset.defaultCharset())
}
// good
def execute() {
def data
try (def fis = new FileInputStream('/flex/flex-enterprise/storage/media/Subtitle.vtt')) {
data = IOUtils.toString(fis, Charset.defaultCharset())
}
}
Comments
0 comments
Please sign in to leave a comment.