0% found this document useful (0 votes)
587 views

SAPUI5 Guidelines

The document provides coding best practices and naming conventions for developing SAPUI5 applications. It includes 27 sections that cover topics like avoiding global variables, using consistent XML formatting, model view controller patterns, and event handling between controllers using an event bus. Common events and functions are recommended to be shared in a base controller that all other controllers can extend from. CamelCase is suggested for variable, function, and method names while underscores and hyphens are used for private/protected properties and ID names respectively. The document also discusses i18n, commenting code properly, and reducing hard-coded values.

Uploaded by

saravanan ss
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
587 views

SAPUI5 Guidelines

The document provides coding best practices and naming conventions for developing SAPUI5 applications. It includes 27 sections that cover topics like avoiding global variables, using consistent XML formatting, model view controller patterns, and event handling between controllers using an event bus. Common events and functions are recommended to be shared in a base controller that all other controllers can extend from. CamelCase is suggested for variable, function, and method names while underscores and hyphens are used for private/protected properties and ID names respectively. The document also discusses i18n, commenting code properly, and reducing hard-coded values.

Uploaded by

saravanan ss
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Table Of Content

1. Variable And Object Property Names Error! Bookmark not defined.

2. Don’t Use Console.Log(); 3

3. Use Camel Case For Variable And Function Names 4

4. Use Underscore For Private And Protected Object Property Names 4


5. Use Hyphens And Lowercase Letters For Id Names 5

6. i18n Naming Conventions And Utilization 5

7. Use A Base Controller 6

8. Share Common Events of Controllers between Controller with


EventBus 6

9. Use Consistent XML Formatting 8

10. How to Concatenate More than 3 Expressions in a Controller 9

11. Model View Controller 10

12. Avoiding Global Variables 11

13.Using Comments Properly 11

14. Reducing Modules 11

15. Reusing Elements 12

16. Naming Convention 12

17. Don’t Hard Code or Concatenate the Strings that needed to be


translated 13

18. Don’t Use Time-outs Error! Bookmark not defined.

19. Code Formatting 13

20. Creating Classes 14


21. File Names and Encoding 15

22.Routing 16

23. Don’t Override Control class Styling directly 17

24. Don’t Style DOM Element names directly 18

25. Don’t Use generated IDs in CSS Selectors 18

26.Don’t use hard-coded colors,font sizes and images if the app


should be themable 19

27.CSS/Themes Naming Conventions Error! Bookmark not defined.

1. Variable And Object Property Names


Variable/Object Declaration
jQuery Object $Name
Array aName
Date dName

Boolean bName
Float fName
Integer iName
String sName

Object oName
Function fnName

Map mName

Variant Types vName

Regular Expression rName

2. Don’t Use Console.Log();

Because the console object is not available within certain browsers


while the developer tools are not available instead use sap.base.Log.all(); .
There are different Log Levels and they are :

● all
● debug
● error
● fatal
● info
● none
● warning
● trace

3. Use Camel Case For Variable And Function


Names //@saravanan - And Method names also

1. For Variable
sEmployeeGroup = "EmployeeData!";

2. For Function
function sayNow() {
sap.base.Log.info("abc")

};

4. Use Underscore For Private And Protected Object


Property Names

Don’t use or override private and protected functions . Private function are
typically prefixed with “_” where as protected functions are indicated by a
yellow diamond in front of the function name.
1. //private variable in the controller object
_sPrivateVariable = “abc” ;

2. //private function in the controller object


_fnPrivateFunction: function() {
sap.base.Log.info(“abc”);

5. Use Hyphens And Lowercase Letters For Id


Names

<Button id="sap-m-button-id"
press="onButtonPress">
</Button>

6. i18n Naming Conventions And Utilization

#TIT: Application name // # is a Comment Line in i18n


appTitle=Abc

#DES: Application description


appDescription=Abc
i18n can help reduce the number of formatter or utility functions of
your application.Using,i18n can easily build formatted string via parameter
passing.It also keeps the controller clean and the xml file declarative.

7. Use A Base Controller


Create an application as base controller. The base controller extends
all other controllers . In the base controller go methods which are common
in the controllers.
For example,the base controller could contain a method called
getModel.In the method goes this.getView().getModel().Now all controller
can use the shortcut this.getModel() instead of this.getView().getModel().
Move reusable functions to higher scope.The recommended base
controller as follows:
● getRouter
● getResourceBundle
● getModel
● setModel
● onNavback

8. Share Common Events of Controllers between


Controller with EventBus
The sap.ui.core.EventBus in SAP UI5 allows sharing events
application-wide. It is possible to attach or detach events to an
EventBus.One can retrive the global EventBus anywhere in an application .
Therefore one can retrive to an EventBus applied events anywhere in
an application.The primary use case for an EventBus is to enable
communication between controllers.
In EventBus ,it is sufficient to initialize the button press event just in
one controller or in a base controller which extends the view’s controllers.
After the press event is initialized ,it is to attach to the EventBus.Then the
EventBus is to receive in the view’s controllers.
For Example , the 1st xml view’s controller which holds the button
between the controllers of view1 and view2 through the EventBus shared
method called _onButtonPress the controller attaches the method to the
EventBus and consumes it as well

● Controller of View1

return Controller.extend("com.EventBus.EventBus.controller.View1", {
onInit: function () {
var oEventBus = sap.ui.getCore().getEventBus();
oEventBus.subscribe("_onButtonPress",
this._onButtonPress, this);
},
onButtonPress: function () {
var oData = {
message: "View's 1 button was clicked."
};
var oEventBus = sap.ui.getCore().getEventBus();
oEventBus.publish("_onButtonPress", oData);
},
_onButtonPress: function (oChannel, oEvent, oData) {
var sMessage = oData.message;
sap.m.MessageToast.show(sMessage);

}
});

● Controller of View2

sap.ui.controller("com.EventBus.EventBus.controller.View2", {
onButtonPress: function() {
var oData = {
message: "View's 2 button was clicked."
};
var oEventBus = sap.ui.getCore().getEventBus();
oEventBus.publish("_onButtonPress", oData);
}

});

9. Use Consistent XML Formatting


● If an xml element has more than two attributes then do a line
break before the first attribute
<ActionButton
title=”{i18n>employee}”
icon=”sap-icon://add”
press=”onPressButton”/>

● If an Xml has only one attribute then don’t give line break
<ActionButton title=”{i18n>employee}”/>

● If an xml element does not contain any aggregations, then don’t


use a closing tag but a forward slash(/) in order to close the
XML element and no space before the forward slash.
Refer above example

10. How to Concatenate More than 3 Expressions in


a Controller

var oModel=this.getView().getModel(“i18n”);
var oResourceBundle= oModel.getResourceBundle();
var sText=oResourceBundle.getText(“abc”);
11. Model View Controller

● Exhausting Models - Models allow you to write maintainable


code.It allows us to auto update control properties and bindings
all at once. It also decouples the data to the presentation layer.

var oModel=this.getView().getModel();
oModel.setProperty(“/message”,”hello”);
oModel.setProperty(“/alignment”,”End”);
oModel.setProperty(“/busy”,true);
oModel.setProperty(“/message”,”hello”);
//auto update all controls with binding

● Reducing Anonymous Functions - Prefer callbacks as separate


function for readability and extensibility.
fnMyServiceCall: function() {
var oModel=this.getView().getModel(“view”);
oModel.read(“/Orders”,{
success: this.fnSuccessCallback;
error:this.fnErrorCallback;
})
},
fnSuccessCallback: function(oResult,oResponse){
//
},
fnErrorCallback: function(oError){
//
},

12. Avoiding Global Variables

Exposing too many variables to the global scope can result in


unintentional runtime errors.Since members are accessible to the whole
view or module,undeclared variables with the same name can also effect
the value of the globally scoped variable if not handled properly. In order to
reduce the chances of having unwanted access to the variables scope
them to where they belong to.

13.Using Comments Properly

Comments are helpful , not only for us but to any succeeding


developer that will support our application. On the other hand,do not overdo
the documentation . Comment only what is needed.

14. Reducing Modules

There are several ways to load modules.Each method is intended to


reduce response time and performance by using only what is needed by
the application.
● Bootstraps - Modules loaded in manifest.json are the ones used
throughout the application .
● Constructor and Init - Dependencies loaded in the sap.ui.define of the
controller file are used for controller-wide dependencies.
● On-demand - These are inline sap.ui.require for example, Dialogs .
Used them for rarely used elements and libraries in view.

15. Reusing Elements

In relation to having reusable controllers,fragments. Fragments


hilghly increase the reusability and help us to insert controllers even at
runtime.If our application has re-occuring control parts. We can just
declare fragment then reuse them anywhere needed.fragments are also
cached once they are initiated,which will speed up our application response
moving forward.

16. Naming Convention

● Controller name starts with an uppercase letter and use


CamelCase for concatenated words.
● Property,event,aggregation,association,method and parameter
names start with a lowercase letter and also use CamelCase
17. Don’t Hard Code or Concatenate the Strings that
needed to be translated

Hard coding Ui strings will exclude them for translation .In addition ,
concatenating translatable strings in applications might lead to errors in
i18n : the texts in question might have a different translation order in other
languages and will then be syntactically wrong.

18. Don’t Use Time-outs

Executing logic with timeouts is often a work around for faulty


behavior and does not fix the root cause. The timing that work for us may
not work under different circumstances or when the code is changed.Use
callbacks or events instead.

19. Code Formatting

The following list contains the formatting rules:

● Add a semicolon after each statement , even if optional


● No spaces before and after round braces (function
calls,function parameters etc.) and is on the same line
● Use space after conditional statements and exception
handling around curly braces,around operators and after
commas
● Use “===” and “!==” instead of “==” and “!=”
● Indentation must follow
● Do not use oEvent.preventDefault() or
oEvent.stopPropagation() without a good reason and
clear documentation why it is really required
● Make sure not to break data binding

For example,
function outer(c, d) {

var e = c * d;
if (e === 0) {
e++;
}
for (var i = 0; i < e; i++) {
// do nothing
}

function inner(a, b) {
return (e * a) + b;
}

return inner(0, 1);

20. Creating Classes


For the creation of class the rules are :
● Initialize and describe instance fields in constructor function
this._bReady = false;

● Define instance methods as members of the prototype of the


constructor function
MyClass.prototype.doSomething = function() { }

● Define static members(fields and functions) as members of the


constructor function object itself :
MyClass.doSomething = function() { }

● Start the name of private members with an underscore


this._bFinalized

● Combine constructors+methods+static in single JS source file


named and located after the qualified name of the class; this is
precondition for class loading
● Static classes do not have a constructor but an object literal;
there is no pattern for inheritance of such classes. If inheritance
is needed, use a normal class and create a singleton in the
class.
● Do not use SuperClass.extend() for subclasses. If no base
class exists, the prototype is automatically initialized by
JavaScript as empty object literal and must not be assigned
manually. Consider inheriting from sap.ui.base.Object
● Subclasses call the constructor of their base class
SuperClass.apply(this, arguments);

21. File Names and Encoding


When developing content for SAPUI5 ,the following rules are :
● Folder names must not contain spaces
● To avoid issues with SAPUI5 module loading and with URL
handling in general , resource names should not contain
spaces.
● Single folder names must not be longer than 40 Characters
● Two resource names must not only differ in case
● Avoid non-ASCII characters in resource names.

22.Routing and Navigation

If we try to work with navigation using component based routing then


further if an application requires more navigation with split apps like a
double master or double detail,use the event bus mechanism.The
navigation handling of the event bus should be specific to that split app
controller and named uniquely to avoid multiple listeners of the same
navigation bus.

1. Naming Targets
Targets and routes should match view file to easily track the flow of
the navigation. Also provide the following minimal settings for targets :
● viewLevel - sets hierarchy to the application views
● viewName
● viewType
● transition - the default transition behavior for the current target
● bypass - fail safe target for unmatched routes
2. Creating Patterns
Route name should be descriptive by itself .Prefer plural form of
routes if applicable.

3. Naming URL Parameters

Routing parameter should be url safe.Routing parameters


should be singular form

CSS Styling Issues

23. Don’t Override Control class Styling directly

If the naming of style classes is changed in future versions,styling


rules will no longer be applied to targeted elements. In addition , overriding
control class styles directly might lead to style clashes when applications
are run in shared runtime environment.
For example, Add a custom CSS class to the control in those
situation were we want additional styling :
oButton.addStyleClass(“abcAppError”);

Then provide the style for this class will be :


.abcAppError {
Font-weight: bold;
}

24. Don’t Style DOM Element names directly

Styling DOM elements directly will lead to unpredictable results, as


SAPUI5 does not guarantee the stability of the inner control DOM tree over
time. In addition,this might lead to styling clashes when applications run in
shared runtime environments or when custom HTML is added. It is better to
limit styling changes to specifically used CSS classes.
For example :
.myStyleClass {
width : 120px;
}

25. Don’t Use generated IDs in CSS Selectors

SAPUi5 applications can create dynamic IDs for elements.Don’t use


these IDs as selectors in custom CSS as they can change over time.It is
better to add and use CSS classes instead.
For example : Adding a style class
.myEmphasizedButton {
font-weight: bold;
}

26.Don’t use hard-coded colors,font sizes and


images if the app should be themable

Themability of applications relies on less calculations within the


SAPUI5 theme CSS.It means that these colors are not modified by theming
which leads to design issues or accessibility issues

27.CSS/Themes Naming Conventions


● All CSS classes must begin with the sapUI prefix .
● For each control there must be one unique control specific
prefix for CSS classes.
For example, sapUIBtn for a Button control or sapMITb for an
IconTabBar in sap.m library.This class must be written to the HTML root
element of the control.
● All CSS classes within the HTML of this control must append a
suffix to this class name
For example, spaUiBtnInner or sapMITBHeader

You might also like