โœจ Best Practices Guide - FluxSharp

Professional coding standards and best practices for FluxSharp development.


Table of Contents

  1. Code Style
  2. Naming Conventions
  3. Error Handling
  4. Performance
  5. Security
  6. Testing
  7. Documentation
  8. Design Patterns
  9. Anti-Patterns

Code Style

Indentation & Formatting

Use 4 spaces for indentation (not tabs):

class Calculator { int result = 0; public int calculate(int a, int b) { int sum = a + b; return sum; } }

Braces

Always use braces, even for single statements:

// โœ“ Good if (x > 10) { print("Large"); } // โœ— Bad if (x > 10) print("Large");

Line Length

Keep lines under 100 characters for readability:

// โœ“ Good string longMessage = calculateMessage(parameter1, parameter2, parameter3); // โœ— Bad string longMessage = calculateMessage(parameter1, parameter2, parameter3, parameter4, parameter5);

Spacing

Use consistent spacing around operators:

// โœ“ Good int result = a + b - c; if (x > 0 && y < 10) { } // โœ— Bad int result=a+b-c; if(x>0&&y<10){}


Naming Conventions

Class Names

Use PascalCase for class names:

class UserManager { } class DataProcessor { } class PaymentCalculator { }

Method Names

Use camelCase for methods:

public void calculateTotal() { } public int getUserAge() { } public bool isValidEmail(string email) { }

Variable Names

Use camelCase for variables, descriptive names:

int userAge = 25; string customerName = "Alice"; bool isActive = true; float totalAmount = 99.99f;

Constants

Use UPPERSNAKECASE for constants:

int MAXATTEMPTS = 3; float PI = 3.14159f; string APPVERSION = "1.0.0";

Boolean Variables

Prefix with

is

,

has

,

should

,

can

:

bool isValid = true; bool hasPermission = false; bool shouldRetry = true; bool canAccess = true;

Collections

Use plural names for collections:

int[] numbers = new int[10]; string[] userNames = new string[5];


Error Handling

Always Handle Exceptions

// โœ“ Good try { int result = parseNumber(input); print("Result: " + result); } catch (Exception e) { print("Error parsing number: " + e); } // โœ— Bad - No error handling int result = parseNumber(input);

Catch Specific Exceptions

// โœ“ Good try { processData(data); } catch (NullPointerException e) { print("Data is null: " + e); } catch (IOException e) { print("IO error: " + e); } // โœ— Bad - Too generic try { processData(data); } catch (Exception e) { // ignore all errors }

Provide Meaningful Messages

// โœ“ Good catch (Exception e) { print("Failed to load configuration file at: " + filePath); print("Error details: " + e); } // โœ— Bad catch (Exception e) { print("Error"); }

Use Finally for Cleanup

// โœ“ Good try { openConnection(); executeQuery(); } catch (Exception e) { print("Query failed: " + e); } finally { closeConnection(); }


Performance

Avoid Unnecessary Object Creation

// โœ“ Good - Reuse objects string result = ""; for (int i = 0; i < 5; i = i + 1) { result = result + i; } // โœ— Bad - Creates new object each time string result = ""; for (int i = 0; i < 1000; i = i + 1) { string temp = new string("Item " + i); result = result + temp; }

Use Appropriate Data Structures

// โœ“ Good - Array for known size int[] items = new int[100]; // โœ— Bad - Growing array inefficiently int[] items = new int[1]; // later: resize manually multiple times

Lazy Evaluation

// โœ“ Good - Compute only if needed if (isValid) { int expensive = calculateExpensiveValue(); process(expensive); } // โœ— Bad - Always compute int expensive = calculateExpensiveValue(); if (isValid) { process(expensive); }

Early Return

// โœ“ Good - Exit early public bool validate(string input) { if (input == null) { return false; } if (input.length() == 0) { return false; } return true; } // โœ— Bad - Nested conditions public bool validate(string input) { if (input != null) { if (input.length() > 0) { return true; } } return false; }


Security

Validate Input

// โœ“ Good public void processUserInput(string input) { if (input == null || input.length() == 0) { throw new Exception("Invalid input"); } // ... process safely } // โœ— Bad public void processUserInput(string input) { // ... assumes input is valid }

Prevent Buffer Overflows

// โœ“ Good - Bounds checking (automatic) int[] data = new int[10]; data[5] = 42; // Safe data[15] = 42; // Error caught! // โœ— Bad - In other languages int data[10]; data[15] = 42; // Buffer overflow!

Use Type Safety

// โœ“ Good - Type-safe public int add(int a, int b) { return a + b; } // โœ— Bad - No type safety public something add(something a, something b) { // type mismatch errors possible }

Sanitize Data

// โœ“ Good public void displayUserData(string name) { // Sanitize/escape special characters string safe = escapeHtml(name); print("User: " + safe); } // โœ— Bad public void displayUserData(string name) { print("User: " + name); // Possible injection }


Testing

Write Testable Code

// โœ“ Good - Easy to test public int add(int a, int b) { return a + b; } // โœ— Bad - Hard to test public void add() { int a = getUserInput(); int b = getUserInput(); print(a + b); }

Use Meaningful Test Cases

// โœ“ Good void testAdd() { int result = add(2, 3); assert(result == 5); result = add(-1, 1); assert(result == 0); result = add(0, 0); assert(result == 0); }

Test Edge Cases

// โœ“ Good - Include edge cases add(0, 0); // Zero add(-5, 5); // Negatives add(MAXINT, 1); // Overflow


Documentation

Write Clear Comments

// โœ“ Good // Calculate the factorial of n // Returns the product of all positive integers โ‰ค n public int factorial(int n) { if (n <= 1) { return 1; } return n factorial(n - 1); } // โœ— Bad public int factorial(int n) { // this is factorial if (n <= 1) { return 1; } return n factorial(n - 1); }

Document Assumptions

// โœ“ Good // Assumes items is sorted in ascending order // Returns the index of target or -1 if not found public int binarySearch(int[] items, int target) { // ... } // โœ— Bad public int binarySearch(int[] items, int target) { // ... }

Use Doc Comments

// โœ“ Good /*

  • Calculates the sum of two numbers

  • @param a First number

  • @param b Second number

  • @return The sum of a and b

/ public int add(int a, int b) { return a + b; }


Design Patterns

Single Responsibility Principle

// โœ“ Good - Each class has one job class UserValidator { public bool validate(User user) { // Validation logic only } } class UserRepository { public void save(User user) { // Persistence logic only } } // โœ— Bad - Multiple responsibilities class User { // User logic // Validation // Persistence // Serialization }

Don't Repeat Yourself (DRY)

// โœ“ Good - Extract common logic public bool isValidEmail(string email) { return email.contains("@") && email.contains("."); } public bool isValidDomain(string domain) { return domain.contains("@") && domain.contains("."); } // โœ— Bad - Repeated code public bool isValidEmail(string email) { return email.contains("@") && email.contains("."); } public bool isValidDomain(string domain) { return domain.contains("@") && domain.contains("."); }

Composition Over Inheritance

// โœ“ Good class Engine { public void start() { } } class Car { Engine engine = new Engine(); public void start() { engine.start(); } } // โœ— Bad (when inappropriate) class Car extends Engine { // Not all car properties are engine properties }


Anti-Patterns

God Objects

// โœ— Bad - Does too much class Application { // 50+ methods // 100+ properties // Handles everything } // โœ“ Good - Break into smaller classes class UserManager { } class DataProcessor { } class ConfigManager { }

Magic Numbers

// โœ— Bad if (age > 18) { } if (salary > 50000) { } // โœ“ Good int MINAGE = 18; int MINSALARY = 50000; if (age > MINAGE) { } if (salary > MIN_SALARY) { }

Deep Nesting

// โœ— Bad - Too nested if (user != null) { if (user.isActive) { if (user.hasPermission) { if (user.isVerified) { // Do something } } } } // โœ“ Good - Early return if (user == null) return; if (!user.isActive) return; if (!user.hasPermission) return; if (!user.isVerified) return; // Do something

Silent Failures

// โœ— Bad - Error ignored try { processData(); } catch (Exception e) { // Silently ignore } // โœ“ Good - Handle or log try { processData(); } catch (Exception e) { print("Error processing data: " + e); // Handle appropriately }


Quick Checklist

Before committing code, verify:

  • [ ] Code follows naming conventions

  • [ ] Indentation is consistent (4 spaces)

  • [ ] Lines are under 100 characters

  • [ ] Comments explain the "why", not the "what"

  • [ ] All exceptions are handled

  • [ ] Input is validated

  • [ ] No unnecessary object creation

  • [ ] Code is DRY (not repeated)

  • [ ] Single Responsibility Principle followed

  • [ ] Tests cover main cases and edge cases

  • [ ] No magic numbers (use constants)

  • [ ] No deeply nested conditions

  • [ ] Security practices followed

  • [ ] Performance considered


Resources

For more information:

  • Security:

    docs/02-language/ADVANCED_SECURITY.md

  • Performance:

    docs/05-reference/IMPLEMENTATION_SUMMARY.md

  • Error Handling:

    docs/02-language/EXCEPTION_HANDLING.md

  • Learning Guide:

    docs/LEARNING_GUIDE.md


Last Updated: April 9, 2026 Status: Comprehensive โœ… These best practices help create maintainable, secure, and efficient FluxSharp code.