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 =123Ldef 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('demo asset').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
String Outputmessage ='my message'
String outputmessage ='my message'// good
String 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 performingstring interpolation:
// bad
def myValue ="some value"// good
def myValue ='some value'
You should also avoid string concatenation:
// bad
def myValue ="some value "+ offset
// good
def myValue ="some value $offset"
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
defexecute(){def fis =new FileInputStream('/flex/flex-enterprise/storage/media/Subtitle.vtt')def data = IOUtils.toString(fis, Charset.defaultCharset())}// good
defexecute(){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.