top of page

Proper Code Formatting Saved Many a Simulation Modeller

Writer: Selaelo KgoaleSelaelo Kgoale

Updated: Mar 19

This is a special blog post by our intern, Selaelo Kgoale. Selaelo is still a junior in the simulation modeling world, and he is presenting some of the lessons he has learned on his new journey in a series of blog posts. Subscribe to the blog if you want to follow along and learn some new tips and tricks.


This post was made possible by the support of our Patrons. To become a member, click here.

 

In this blog post, I will be addressing the importance of code formatting in model development. As a novice to the world of simulation modelling, I did not know why this was crucial to understand and apply as a best practice until my mentor Jaco-ben Vosloo explained it. So, I thought it would be ideal to write a blog post and inform my fellow novices who may not be fortunate enough to have some mentorship.


When developing simulation models in AnyLogic, it’s easy to prioritise logic, algorithms, and functionality while neglecting a crucial aspect: code formatting. Whether you are writing Java functions to manipulate agents or defining custom classes for simulation logic, a properly structured code streamlines the development process. A well-organized code base can lead to an easy-to-understand and simple-to-maintain model, while poorly formatted code can result in a debugging nightmare.


This was an eye-opener on something I had been overlooking for some time, and I hope it will be the same for you.


The Benefits of Code Formatting in Simulation Models


Code formatting is crucial for several reasons beyond mere aesthetics; it significantly enhances your Java code's readability, maintainability, and efficiency when working with AnyLogic models.

  1.  Readability: A clean and well-structured code base greatly improves comprehension at a glance. This clarity is particularly advantageous when handling complex process models, state-based behaviors, or multi-method simulations that involve various Java functions.

  2.  Maintainability: Thoughtfully organized code enables you and your colleagues to implement changes more effortlessly. Well-formatted code can save considerable time that might otherwise be spent unraveling intricate functions.

  3. Efficiency: Consistent code formatting facilitates the debugging process, making it easier to identify and rectify syntax errors and logical mistakes.


By prioritising sound code formatting practices, you will not only enhance the quality of your simulation models but also cultivate a more collaborative and efficient work environment.


In this post, we will explore the importance of code formatting for effective model development. We will demonstrate the differences between poorly formatted and well-formatted code and share best practices to help you keep your AnyLogic models clean, readable, and scalable. We will also demonstrate an AnyLogic feature that can format poorly written code.


Example Model: Comparing Well-Formatted vs. Poorly-Formatted Code


To demonstrate the benefits of formatting by creating a simple model where a Java class with a method/function that processes input waiting time and aggregates them to high and low priority. We’ll implement the same logic in two different ways—one with poor formatting and one with best practices.


  1. Poorly formatted


    This code has the following issues:

    1. No proper indentation

    2. Inconsistent casing in method name

    3. No spacing for readability


  2. Well formatted


    Key improvements:

    1. Consistent indentation for better readability

    2. Camel case for method names (Java best practice)

    3. Proper spacing for improved clarity


Now that we've got an idea of what good and bad code formatting looks like let's dive into the best practices in detail, breaking down how we approach code formatting.


Best Practices for Writing and Formatting Code in AnyLogic (and in Java)


1. Use Consistent Indentation and Spacing

  • 4 spaces per indentation level (avoid tabs).*

  • Use blank lines to separate logical sections.

  • Place curly braces {} on the same line as the statement (K&R style)


Bad format:

if(x > 0){ System.out.println("Positive");}

Good format:

if (x > 0) {
    System.out.println("Positive");
}

*Note by Jaco-Ben: This can be a very contentious point.. I prefer tabs and avoid using spaces as it is easier to miss a space or two and have code that does not look right,t but you can't put your finger on it. Although the official Google Style guide indicates that "tab characters should not be used" here. I would still not use spaces... watch this video about Tabs vs. Spaces from the TV series Silicon Valley for some of the arguments for and against it. ;-)


  1. Follow Java Naming Conventions

    Classes(including Agents): PascalCase (e.g., CustomerAgent).

    Methods/functions: camelCase (e.g., calculateArrivalRate).

    Constants: UPPER_SNAKE_CASE (e.g., MAX_WAIT_TIME)


  2. Line Length & Wrapping


  • Limit Line Length to 80-120 Characters

  • Break long lines at logical points (e.g., after operators, before method arguments).

    This accommodates the print capabilities of terminals used by most programmers and improves readability.


    **Couldn't put a bad formatting example because the code snippet tool wraps the text**


    Good formatting:

double averageWaitTime = 
(totalWaitTime / numberOfCustomers) * conversionFactor;

  1. Code Structure & Organization


When creating classes, there is a preferred order the class members. The Class Member Ordering is as follows:

  1. Constants & static variables

  2. Instance variables

  3. Constructors

  4. Methods (public first, then private)


Good format:


public class Customer {
    private static final int MAX_ORDERS = 10;
    private String name;
    public Customer(String name) {
        this.name = name;
    }
    public void placeOrder() { 
...
 }
    private void validateOrder() { 
...
 }
}

Although not a formatting issue per se, even the Method & Variable Access Modifiers have a preferred method of being set up.

  1. Use the most restrictive access modifier possible (private > protected > public).

  2. Avoid public instance variables; use getters/setters instead.


Bad Format (Exposing Variables Directly):

public String customerName;

Good Format (Encapsulation):

private String customerName;
public String getCustomerName() {
    return customerName;
}

  1. Avoid Hardcoded Values ("Magic Numbers")


    Bad Format:

delay(5);

Good Format:

final int PROCESS_DELAY = 5;
delay(PROCESS_DELAY);

By using constants, the code becomes easier to modify and understand.


  1. Write Self-Documenting Code


  1. Use clear variable & function names instead of excessive comments.

  2. Only comment on complex logic or business rules.


Bad Format( with Redundant Comment):

// This function checks if a customer is VIP
boolean isVIP(Customer c) { return c.loyaltyPoints > 1000; }

Good Format:

boolean isCustomerVIP(Customer customer) { 
    VIP_THRESHOLD = 1000
    return customer.loyaltyPoints > VIP_THRESHOLD;
}

We can ensure a more streamlined process with these practices applied to our model development process.


P.S. The VIP_THRESHOLD variable should best exist in the class member section and not in the function itself. We placed it here to illustrate the example.


Formatting already written code.

AnyLogic has the functionality to format already-written Java code. To do so, we simply right-click on the Java and select the format code option.

The functionality essentially applies all Java conventions to the class.


The format function from AnyLogic is available everywhere you write code and also when you right-click on a function object.



Benefits of well-formatted code


If the previous examples did not make the benefits of well-formatted and properly written code that follows best practices clear, here is a short, non-exhaustive list of them.


  • Improves Readability – Makes it easier for you and others to understand the logic.

  • Enhances Debugging – Structured code helps quickly identify errors and bugs.

  • Eases Collaboration – Team members can read, edit, and maintain the code more efficiently.

  • Reduces Technical Debt – Well-formatted code is more straightforward to update and extend over time.

  • Prevents Logical Errors – Proper indentation and spacing prevent misinterpretation of code structure.

  • Speeds Up Code Reviews – Reviewers can quickly scan and validate changes without confusion.

  • Ensures Consistency – Following a standard format makes the codebase uniform and professional.

  • Optimizes Performance – Clean code often leads to better-structured, efficient algorithms.

  • Facilitates Automation – Consistent formatting allows for better use of code linters and automated testing tools.

  • Boosts Maintainability – A structured codebase makes future modifications and refactoring much easier.



Conclusion

Formatting code is an imperative best practice for model development. It should always be considered during the development process. The same convention applies to the function objects and action properties of objects used in our models.


You can download the example model below or from AnyLogic Cloud here or download from the link below:




Keep modeling

Selaelo Kgoale


 

Selaelo Kgoale is a simulation enthusiast and new intern at The AnyLogic Modeler. To contact him, use LinkedIn.


What next?

If you liked this post, you could read more posts by following the links above. Why not subscribe to our blog or follow us on any of the social media accounts for future updates? The links are in the Menu bar at the top, or the footer at the bottom. You can also join the mobile app here!


If you really want to make a difference in supporting us please consider joining our Patreon community here 


If you want to contact us for some advice, maybe a potential partnership or project or just to say "Hi!", feel free to get in touch here, and we will get back to you soon!





Comments


  • LinkedIn
  • Facebook
  • YouTube
  • Twitter
  • Instagram

©2021 by The AnyLogic Modeler

bottom of page