โจ Best Practices Guide - FluxSharp
Professional coding standards and best practices for FluxSharp development.
Table of Contents
- Code Style
- Naming Conventions
- Error Handling
- Performance
- Security
- Testing
- Documentation
- Design Patterns
- 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.