Clean CAPClean CAP
Home
Inspired by CAPire
Datenschutzerklärung
Impressum
Home
Inspired by CAPire
Datenschutzerklärung
Impressum
  • Clean CAP

Clean CAP

Project-Setup

This section provides a step-by-step guide to setting up a new CAP NodeJS project, including the installation of necessary tools such as Git and Node.js, and initializing your first CAP project.

Git Installation

  1. Download Git: Go to the official Git website and download the latest version for your operating system.
  2. Install Git: Run the downloaded file and follow the installation instructions. Choose the default options unless you have specific preferences.
  3. Verify Installation: Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and type git --version to verify that Git is installed correctly.

Cloning a Project from Microsoft DevOps

  1. Navigate to your DevOps repository: Log in to your Microsoft DevOps account and navigate to the repository you wish to clone.
  2. Copy the clone URL: Find and copy the URL provided for cloning the repository.
  3. Clone the repository: Open a terminal, navigate to the directory where you want the project to be cloned into, and run the command git clone <repository-url>. Replace <repository-url> with the URL you copied.

Node.js Installation

  1. Download Node.js: Visit the official Node.js website and download the LTS (Long Term Support) version for your operating system.
  2. Install Node.js: Run the downloaded file and follow the installation instructions. It's recommended to accept the default installation options, which include npm (Node Package Manager).
  3. Verify Installation: Open a terminal and type node --version and npm --version to ensure Node.js and npm are installed correctly.

Setting Up a CAP NodeJS Project

  1. Install CAP CLI: First, install the CAP (Cloud Application Programming Model) Command Line Interface globally using npm with the command: npm install -g @sap/cds-dk.
  2. Initialize a New Project: Create a new directory for your project and navigate into it via the terminal. Then, initialize a new CAP project by running: cds init --add java, samples.
  3. Hello World Example:
    • Create a new file named hello.cds inside the db/ directory.
    • Add the following content to hello.cds:
      service HelloWorldService {
          entity HelloWorld {
              key ID : Integer;
              message : String;
          }
      }
      
    • Run cds watch in the terminal from your project root directory. This command starts the CAP development server.
    • Access your service at http://localhost:4004/helloworldservice/HelloWorld to see your "Hello World" message.

Coding-Conventions

This section outlines the coding conventions adopted in our CAP NodeJS projects, incorporating Clean Code principles and selected Design Types that align with our development ethos. Our aim is to foster code that is easy to read, maintain, and scalable.

Meaningful Names and Functions

  • Use Intention-Revealing Names: Choose names that reveal intent and make the code easier to understand.

    // Avoid
    const d = new Date().getDay();
    
    // Prefer
    const today = new Date().getDay();
    
  • Small, Focused Functions: Functions should do one thing, do it well, and do it only.

    // Avoid
    function processUserData(user) {
      const userAge = calculateAge(user.birthdate);
      if (userAge > 18) {
        // adult logic
      } else {
        // minor logic
      }
      // More unrelated logic
    }
    
    // Prefer
    function isUserAdult(user) {
      return calculateAge(user.birthdate) > 18;
    }
    

Clean Code Comments and Error Handling

  • Comments: Use comments to explain "why" rather than "what". The code itself should explain "what" by being as clear as possible.

    // Bad: The comment is unnecessary if the code is self-explanatory
    // Check if the user is an adult
    const isAdult = user.age > 18;
    
    // Good: Use comments to explain non-obvious reasons
    // Using 18 as the age of majority, as per regulations in Country X
    const isAdult = user.age > 18;
    
  • Error Handling: Use exceptions rather than returning error codes. Ensure that the function name reflects its purpose and the possibility of throwing an exception.

    // Avoid
    function getUser(id) {
      if (id <= 0) {
        return null; // Unclear implication of returning null
      }
    }
    
    // Prefer
    function getUserOrThrow(id) {
      if (id <= 0) {
        throw new Error('Invalid user ID');
      }
    }
    

Function Arguments and No Side Effects

  • Minimal Function Arguments: Limit the number of function arguments to the absolute minimum, ideally fewer than three.

    // Avoid
    function createUser(firstName, lastName, email, birthdate, address) {
      // Function body
    }
    
    // Prefer: Use an object to encapsulate parameters
    function createUser({ firstName, lastName, email, birthdate, address }) {
      // Function body
    }
    
  • Pure Functions / No Side Effects: Functions should not have side effects. They should not modify any state or data outside their scope.

    // Avoid
    let age = 20;
    
    function incrementAge() {
      age += 1; // Modifies external state
    }
    
    // Prefer
    function getIncrementedAge(age) {
      return age + 1; // No side effects
    }
    

Don't Repeat Yourself

  • DRY Principle: Ensure that you do not duplicate code. Use functions, classes, and modules to encapsulate reusable logic.

    // Avoid
    const userAge = calculateAge(user.birthdate);
    const eligibility = userAge > 18 ? 'adult' : 'minor';
    
    const friendAge = calculateAge(friend.birthdate);
    const friendEligibility = friendAge > 18 ? 'adult' : 'minor';
    
    // Prefer
    function determineEligibility(dateOfBirth) {
      return calculateAge(dateOfBirth) > 18 ? 'adult' : 'minor';
    }
    

Code Formatting and Structure

  • Consistent Code Formatting: Use a consistent coding style guided by tools like ESLint or Prettier. This includes consistent indentation, bracket placement, and file structure.

    // Example of using ESLint and Prettier for consistent code formatting
    
  • Logical Structure: Organize the code logically, separating concerns and modules clearly. For CAP projects, this means structuring your project into clear directories for db, srv, and app.

    my-cap-project/
    ├── db/
    │   └── schema.cds
    ├── srv/
    │   └── service.cds
    └── app/
        └── webapp/
    

Design Types Considerations

  • Simplicity Lover: Focus on simplicity in design and implementation. Avoid over-engineering and keep solutions as straightforward as possible.
  • Structure Organizer: Ensure a well-organized codebase, where each piece of code has a clear place and purpose.
  • Quality Fanatic: Adhere to high-quality standards in coding, testing, and overall project management.

By following these conventions, we aim to create CAP NodeJS projects that are not only aligned with Clean Code principles but also reflect our values as a development team. This approach ensures our code is readable, maintainable, and efficient, supporting the long-term success of our projects.

Tools

This section outlines essential tools for Node.js development, including version managers and code formatting tools. These tools help ensure a consistent development environment and coding style across your team.

VSCode Plugins

To streamline your development process and ensure consistency across your team, consider adding the following VSCode extensions to your project setup. These extensions support CAP development, linting, formatting, and more.

  • SAPSE.vscode-cds: Provides language support for the SAP Cloud Application Programming Model (CAP).
  • dbaeumer.vscode-eslint: Integrates ESLint JavaScript into VSCode, helping to find and fix problems in your JavaScript code.
  • esbenp.prettier-vscode: Supports code formatting using Prettier, ensuring consistent code style across your project.
  • mechatroner.rainbow-csv: Highlights CSV and TSV files in different colors, making them easier to read and analyze.
  • qwtel.sqlite-viewer: Allows you to view SQLite databases directly within VSCode, useful for managing local databases.
  • humao.rest-client: Enables you to send HTTP requests and view responses directly within VSCode, simplifying API testing.
  • sdras.night-owl: A VSCode theme optimized for developers who prefer to work at night or in low-light environments.

To recommend these extensions to anyone opening your project in VSCode, create a .vscode/extensions.json file in your project root with the following content:

{
  "recommendations": [
    "SAPSE.vscode-cds",
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "mechatroner.rainbow-csv",
    "qwtel.sqlite-viewer",
    "humao.rest-client",
    "sdras.night-owl"
  ],
  "unwantedRecommendations": []
}

This configuration will prompt users to install these extensions upon opening your project in VSCode, helping to maintain a consistent development environment.

  • Standard Configuration Download:
    • You can start with a standard configuration extensions.json or create your own based on the project needs.

Node Version Manager

fnm (Fast Node Manager) and nvm (Node Version Manager) are tools for managing multiple versions of Node.js. They allow you to switch between different versions depending on the project's needs, ensuring compatibility and ease of testing across various environments.

Installing fnm

  1. For macOS and Linux:

    • Install using curl:
      curl -fsSL https://fnm.vercel.app/install | bash
      
    • Follow the on-screen instructions to update your shell configuration file.
  2. For Windows:

    • Install with Scoop:
      scoop install fnm
      
    • Restart your terminal or command prompt to ensure fnm is recognized.

Installing nvm

  1. For macOS and Linux:

    • Install using curl or wget:
      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
      
      or
      wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
      
    • Follow the installation script's instructions to update your shell configuration.
  2. For Windows:

    • Use nvm-windows for a Windows-compatible version of nvm:
      • Download and install from nvm-windows.

.nvmrc

The .nvmrc file specifies the Node.js version to use for a particular project. This ensures all developers and the deployment environment use the same Node.js version, reducing inconsistencies and potential errors.

  • Creating a .nvmrc file:
    • In your project root, create a file named .nvmrc.
    • Specify the Node.js version (e.g., v20) or version range.
    • Use nvm use or fnm use in the project directory to switch to the specified version automatically.

.prettierrc.json

Prettier is a code formatter that enforces a consistent style by parsing your code and re-printing it with its own rules, taking into account the maximum line length.

  • Creating a .prettierrc.json file:
    • In your project root, create a file named .prettierrc.json.
    • Define your formatting options. For example:
      {
          "trailingComma": "es5",
          "tabWidth": 4,
          "semi": true,
          "singleQuote": true,
          "useTabs": false,
          "quoteProps": "as-needed",
          "proseWrap": "preserve",
          "printWidth": 180,
          "bracketSameLine": false,
          "singleAttributePerLine": true,
          "htmlWhitespaceSensitivity": "css",
          "endOfLine": "lf",
          "bracketSpacing": true,
          "arrowParens": "always"
      }
      
  • Standard Configuration Download:
    • You can start with a standard configuration .prettierrc.json or create your own based on the project needs.