Blogs about SAP Websites
Stay up to date on essential SAP websites with the latest offerings and news about SAP for Me, SAP Help Portal, SAP Support Portal, and other properties.
cancel
Showing results for 
Search instead for 
Did you mean: 
Marwah_Shwaiki
Product and Topic Expert
Product and Topic Expert
2,147

Recently I came across the "Clean SAP UI5" book, which focuses on adopting clean code principles that focus on maintaining code that is easy to read, understand, and maintain. This is where the concept of "Clean Code" comes into play.

In this blog, I would like to highlight the principles of clean code in SAP UI5 along with illustrative examples, and at the end, I will share some thoughts based on practical experience in projects😉.

 

Marwah_Shwaiki_0-1718981352501.png

 

So what is Clean Code?

Clean Code is a set of practices that aim to produce code that is easy to read, simple to understand, and effortless to maintain. Robert C. Martin  introduced these principles in his book "Clean Code: A Handbook of Agile Software Craftsmanship." These principles are universal and can be applied to any programming language or framework, including SAP UI5.

Why Clean Code in UI5?

SAP UI5 is a robust framework for building responsive, enterprise-level applications. Given its complexity and the collaborative nature of enterprise projects, following clean code principles becomes even more critical. Clean code in UI5 development can lead to:

  • Better Collaboration: Easy-to-read code facilitates better collaboration among team members.
  • Faster Onboarding: New developers can quickly understand and contribute to the codebase.
  • Reduced Bugs: Clear and well-structured code reduces the likelihood of errors.
  • Enhanced Maintainability: Easier to refactor and extend applications as requirements evolve.

Key Principles of Clean Code in UI5

  1. Meaningful Names

    • Be Descriptive: Use meaningful and descriptive names for variables, functions, and classes. Avoid abbreviations that are not universally understood.
    • Consistent Naming Conventions: Follow consistent naming conventions throughout your codebase. For instance, use camelCase for variables and functions, and PascalCase for classes.

 

// Bad Example
var p; // what does p stand for?

// Good Example
var productPrice;

 

  • Single Responsibility Principle

    • Function Focus: Each function should have a single responsibility or perform a specific task. This makes the code easier to understand and maintain.
  • Avoid Magic Numbers and Strings

    • Use Constants: Replace magic numbers and strings with named constants to provide context and make the code self-explanatory.

 

// Bad Example
if (user.age > 18) { /* logic for adults */ }

// Good Example
const LEGAL_ADULT_AGE = 18;
if (user.age > LEGAL_ADULT_AGE) { /* logic for adults */ }
​

 

  • Comment Judiciously

    • Useful Comments: Write comments that explain why the code exists, not what it does. Well-written code should be self-explanatory, reducing the need for excessive comments.

 

// Bad Example
// This function adds two numbers
function add(a, b) {
    return a + b;
}

// Good Example
// Adjusts the user balance after a transaction
function adjustUserBalance(user, amount) {
    user.balance += amount;
}
​

 

  • DRY Principle (Don't Repeat Yourself)

    • Reusability: Avoid duplicating code by creating reusable functions and components. This not only reduces redundancy but also centralizes logic for easier maintenance.

 

// Bad Example
function getUserFirstName(user) { return user.firstName; }
function getUserLastName(user) { return user.lastName; }

// Good Example
function getUserProperty(user, property) { return user[property]; }
​

 

  • Proper Error Handling

    • Graceful Degradation: Ensure that your code handles errors gracefully. Use try-catch blocks and provide meaningful error messages to help with debugging.

 

// Bad Example
var data = JSON.parse(input);

// Good Example
try {
    var data = JSON.parse(input);
} catch (error) {
    console.error("Invalid JSON input: ", error.message);
}
​

 

Clean Code in Action: A UI5 Example

Let's look at a simple SAP UI5 example to illustrate some of these principles. Assume we are building a function to retrieve and display product details. 

 

// Bad Example
function getProductDetails(id) {
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.loadData("/api/products/" + id, {}, false);
    if (oModel.getData().price > 100) {
        alert("Price is over 100");
    }
    var oView = sap.ui.getCore().byId("myView");
    oView.setModel(oModel);
}

// Good Example
const API_ENDPOINT = "/api/products/";
const HIGH_PRICE_THRESHOLD = 100;

function getProductDetails(productId) {
    const oModel = new sap.ui.model.json.JSONModel();
    const productUrl = `${API_ENDPOINT}${productId}`;

    oModel.loadData(productUrl, {}, false);
    displayHighPriceAlert(oModel.getData().price);
    setViewModel("myView", oModel);
}

function displayHighPriceAlert(price) {
    if (price > HIGH_PRICE_THRESHOLD) {
        alert("Price is over " + HIGH_PRICE_THRESHOLD);
    }
}

function setViewModel(viewId, model) {
    const oView = sap.ui.getCore().byId(viewId);
    oView.setModel(model);
}

 

Reality Check Based on My Experience 🤔

While the principles of clean code are ideal for creating maintainable and robust code, the reality of software development can often make it challenging to adhere strictly to these guidelines. Here are some common obstacles developers might face:

  1. Time Pressure: Tight deadlines and the need for quick delivery can force developers to prioritize speed over code quality. In such cases, writing clean code might take a back seat to deliver functional code quickly.
  2. Changing Requirements: Frequent changes in project requirements can lead to rushed updates and patches, resulting in code that is less clean and harder to maintain. This can cause technical debt that accumulate over time.
  3. Lack of Experience: Junior developers or those new to a specific framework like SAP UI5 might struggle to apply best practices and clean code principles consistently. Limited knowledge and experience can make it difficult to write clean, maintainable code.

From my perspective, it's essential to find a balance between ideal practices and practical constraints. and do so Here are a few tips:

  • Incremental Improvement: Aim to improve the codebase incrementally. Start with the most critical areas and gradually apply clean code principles.
  • Code Reviews: Conduct regular code reviews to share knowledge and identify areas for improvement. This helps maintain a high standard of code quality and provides learning opportunities.
  • Peer Programming: Take the chance to learn from other perspectives by getting involved in peer programming with other developers 
  • Automated Tools: Use automated tools for code analysis and linting to enforce coding standards and catch common issues early some IDE's like VScode are offering this possibility by adding the relevant extensions.
  • Documentation: Maintain good documentation to support code understanding and maintenance, especially when clean code practices cannot be fully adhered to due to external pressures.

Final Word

Applying clean code principles to SAP UI5 development is essential for building maintainable, scalable, and robust applications. However, it's important to recognize that real world constraints can make it challenging to follow these principles perfectly. By understanding these constraints and striving for continuous improvement, developers can still achieve a high standard of code quality that benefits both the team and the end product.

Happy coding!  🤗

3 Comments
Labels in this area
Top kudoed authors