Clean Code – Part 5

Hello, how are you?

My last post was too long ago because my pos graduation is taking all my time. I was doing a project and I had o hard time coding a full system. That is why I am without time to post.
Let us keep talking about clean code? The older posts you will find here: Part 01, Part 02, Part 03, Part 04

  • Copy and Paste (even in non OO codes) -> Avoid doing this copy and paste. When you got a task there is an easy way to finish it, it is very easy to copy a code from a place and past it to where we have to use it. By doing this code replication we are increasing the difficult of the code maintenance, breaking good coding patterns and even worst, propagating some bugs.Imagine if we got a complex method, and we need to use it in another place of our software; instead of doing a change to transforme the code to be more generic and apply it to every situation, some developers choose the easiest way to finish the task that is coping and pasting the method. After pasting the code the developer just have to do small changes to complete the task. Imagine now that we have a bug in this pasted code, so we fix the pasted and the original code. The problem is that the older developer did not tell us that this code was replicated more three times. Can you see the problem of replication?

    It would be easier create just one method to be invoked in all parts of the system.

    When writing your code, if you think something like: “I have done/seen something like this before…” it means that is time to you to stop and think. Be aware of any kind of replication:

    • Non OO codes -> Create just one method and use it in any place of your code.
    • OO codes -> Time to apply super-class, abstract class, etc.
  • Remove unnecessary code -> Have you notice the large amount of commented code on legacy software? By example:
    // user.setCreditCardByDate(credidCard, new Date());
    user.setCreditCard(credidCard);
    list.add(user);
    //for(int a = 0; i < list.size(); i++){
        //daoUser.deleteCredidCardHistory(list.get(i));
        //Logger.debug("im here!!!!");
    //}
    daoUser.deleteCredidCardHistory(list);

    If the commented code has no more use, why will you keep it? Sometimes it is normal keep the older code while you test the new one, but saving it? If you are not so sure about the code you wrote, it is better think twice before saving it.
    If we have a tool to control our software version, what is the purpose of saving a commented code? With this kind of versioning tool we can always check the older code.
    The committed code must be clean, easy to understand and with a straight objective. When your code has a lot of old commented code, the current code might lose its focus because the developer might try to understand the commented code and forget about the current code.
    Take a look on how the above code would be so much easier to read:

    user.setCreditCard(credidCard);
    list.add(user);
    daoUser.deleteCredidCardHistory(list);
  • Knowledge of the development language -> Always seeks to upgrade the knowledge you got in your development language. Sometimes your development language already has the method that you are trying to create. “There is no need to re-create the wheel”. Keep updated about your development language. When some task demands you to do something you never done before, research.
    Someday I found this code on certain software and became a joke on the company:

    for(int i = 0; i < 10; i++){
        //... Do stuff
        // Get inside the if when finds the condition
        if (...){
            i = 13;
        }
        // Do stuff
    }

    You can see that instead using the word break, the developer changed the counter value. That task could be done in an easier way and with more style:

    for(int i = 0; i < 10; i++){
        //... Do stuff
        // Get inside the if when finds the condition
        if (...){
            break;
        }
        // Do stuff
    }

    Maybe you think: “Well, at least was working right?!” I will answer your “Yes”, but I will also say that you will not become a joke at your company if you keep updated about your working tool. Another thing to think about the code above is: “What if we must change the counter value”? “What if we have to change the counter value?” “What if we have to change the counter value from 10 up to 100?” You would have to change at the “for” declaration and in the “if”. It’s not worth it.;

  • TODO -> The IDEs that we can find today help us with this reminder. We can easily write “// TODO”, and see this reminder all over the class/system. It is really easy to put this tag TODO in all system code, and it can remember us of everything that we have to do.

TODO

  • The problem is “as easy is to create it, the TODO will be easy to forget about it”. Once this is usual to all company, tons of TODOs codes might appear at the Task view in a short a time, doing your code dirty.One way out to avoid this kind of problem, once you know that the problem will not be fixed in a short time you will not write the tag TODO in your code (To more information about this approach: Watch out for TODO comments! By Alexandre Gazola).
    Other way out it would be to create your own tags. In your company you could agree in use the task TODO just to codes that will be fixed before the end of the task. We could use like: “// REMAKE” or “// REFACTOR” and by the IDEs we can filter by created TAGs.
  • Lose your ego -> I believe that one of the most difficulties of the human being is to lose the ego. Maybe you got a task to do, trusting in your 30 years of experience you will not talk with anyone about your task and will not gather ideas to do that. Ego it is something that only harm the human being. The best thing to do is to have a quick chat with a few people of your team to gather ideas, put them all together, and you can be sure that you code will have everything to get good design patterns, the right technologies and a good OO modeling.
    Just because someone was recently hired to the team, would mean that he does not have any knowledge. Talking and gathering ideas will take your project to another level.
    Leave your ego away; it will not take you anywhere.

That is all for today.

If you have any question, just post it. I do not know when I will post again because the Pos Graduation is taking a lot of time, but soon I will have more tutorials to post here.

See you later! o_

Clean Code – Part 04

Hello, how are you? To make our code cleaner, let’s keep the study about Clean Code? The others articles you will find here: Part OnePart TwoPart Three.

Today the subject will be Constants and Exceptions.

  • Constants name pattern – The Constant name has its name written with high caps “COLOR”; and will receive “_” when is a composite name “OWN_GOAL”. You don’t have to start a Constant name with “_” because there is no need for it; this was a name pattern created, in another development language, to make distinct the methods of the attributes.
  • Constants name should explain its use – A Constant gets clear thanks to its name which must be objective. Constants name must be understandable wherever it’s placed. Imagine you got a Constant used to log messages, if we just name it as LOG it would not be a clear name as LOGGER. There is a difference in the meaning of the words, LOG is “something” created and LOGGER is the creator. Wherever the LOGGER name is, we always will understand its usability.
  • When Constants are needed – We always should be looking for repetitions in our code. Always that we repeat an action or value there is something wrong happening. Image we have a method that modifies soccer game score:
    public void changeScore(Team team, int goal){
        this.fullScore(team, gol);
    }

    And this method is invoked by other method to register an own goal:

    public void recordOwnGoal(Team team){
        match.changeScore(team, -1);
    }

    Imagine if every time we have to inform an own goal to any method, if we have to write the “-1”, by example: “registerToPlayerAGoal (player, “-1”)”; Why we don’t create a Constant? In this soccer sample, creating a Constant we will be able to eliminate a method. Let’s see our final code:

    //Our declared Constant in the Match class.
    public static final int OWN_GOAL = -1;
    
    public void changeScore(Team team, int goal){
        this.fullScore(team, goal);
    }

    Notice that we don’t have the need of a method to register only the own goal (recordOwnGoal), this method was created only to pass the value of an own goal as negative. When we invoke the method that will change the game score (changeScore) we just have to put the “OWN_GOAL” as parameter instead creating a method just to do that (  changeScore(team, OWN_GOAL);  ). By example, Constants are welcome in templates building: “ADD_SIMPLE_INDENT”, “ADD_DOUBLE_INDENT”, and others. Just notice: “Do you have to pass the same value? It’s time to use Constants”.

  • There is a reason. Why does this exception exist? – When we create a catcher for an exception we must pay attention to the reason of that exception it’s been thrown. We must keep in mind that if a method throws an exception we must handle it. We must be prepared to give the best treatment to the exception. Some ways of doing a good handling it would be: show to the user (exception that were handled), handle unfinished actions (files, databases transactions, log, etc).
    When we ignore an exception, by do not working with the Exception object, we are disrespecting the method contract that may result in problems to the user and to the application.
  • Exception that it’s declared, but it’s impossible to happen? Once I was working in a software by refactoring a method, to adapt it to a new customer request, and when I was testing my code it did not worked but it did not failed either. Even after review my code I didn’t find any error, it was ok.
    What did I do to find what was happening? Debug!
    When I was checking the code in runtime, I found the following code:

    //...
    validateCreditCard(creditCard);
    //...
    }catch(CreditCardInUseException){
        //Impossible to get here
    }

    When the validate credit card was created it was impossible of it been in use, that’s why there was a comment saying that it was impossible to get there. We can see two possible aspects that we could change:

    1. Non cohesion method – notice that sometimes the method to validate the credit card throws an exception and sometimes it doesn’t; there is inside its method a business rule that make its behavior to change, this behavior changing will define how the method signature will be handled (future talk about OO). A good solution to this issue it would be splitting this method instead keeping all this rules in one method; this method it’s too complicated and has too much decisions in it.
      If an exception it’s declared, this exception must be handled and in our case – when the code was created – it was impossible of that exception to be thrown. If there is a method that declares an exception that will never happen, there is something wrong!
    2. If an exception it’s been thrown, there is a reason for this exception to exist. Notice that if the exception were handled, at least, with “System.out.println ();” it would have a message to notify that error. When I say “at least”, it’s because we can handle an exception by a lot of different ways like send an email, record a log, etc. Something was happening, an exception was thrown, but there wasn’t anything to take care of it. Remember: “If a method declares an exception, there is a reason for it and it should be handled”.
  • Straight error message – when you write an error message avoid thinking like: “I will put the message like this, it’s clear that we are talking about this subject”. Are you sure about this? The user does not think as a developer, he does not need to know that a value X come from screen Y and it is needed to Z screen.
    When you do not know the best message for that situation, try looking at the screen and forgetting everything you know about it and think: “If I were someone that didn’t know anything about development, how I would understand this error message?” Make changes to this question and adapt it to what you are developing, change your way of thinking, and keep your focus on the user. Another good thing to do is ask some coworker to give an opinion.
  • Avoid some exception error messages when developing – When you write an exception message, even in a test environment, avoid some messages like: “Can’t you see that it’s by your fault that this error happened!” or “Hey loser, type something here!” Sometimes it is fun to see those types of messages; or it can give us some relieve to see that our code reached there, but doing this is very dangerous. Imagine if this message stays in the code and goes to the client? Even if those messages bring us some kind of happiness, it’s better to avoid it.
  • Log4J – It’s a good tool that can be useful if you want to log your exception. With this library it is possible to log messages in different event levels and more. I will write a tutorial about it very soon, until there here it goes a link that might help you to study it: http://www.developer.com/open/article.php/10930_3097221_3/Logging-with-log4jmdashAn-Efficient-Way-to-Log-Java-Applications.htm.

I hope these tips might help you.
See you guys later.

Clean Code – Part 03

Hello, how are you?
Let’s talk about Clean Code? The first’s articles you will find here: Clean Code – Part 01, Clean Code – Part 02
I have changed the Clean Code subject order and today we will be talking about Comments:

  • Comment telling the “why” – Your comment must tell the “why” of the methods being invoked and not “how” it works. The “how” part must be clear when you read the code. When we write how the code works as comments your code will tend to have a bad design, and it will have no patterns. You might start to trust that your comment will explain how the method works instead the code itself. Remember that your code should be “self-explaining”.
    /**
     * This method publishes the documents using a proxy connection
     * to save the files in the necessary patterns
     * There is a loop (repetition) on going while the methods does not end
     * 
     */
    public void publishDocuments(){
        // some code...
    }

    The methods comment is written what it does and the way it executes the process, but this must but noticed when we read the code, not when we read the comment. If we have methods that were inside an exported package, which purpose would have to the user reading that kind of comment? The user must only know what this method does. Let’s see how a comment can be clearer:

    /**
     * Method that publishes the files, in html, which save them 
     * Applying w3c patterns.
     * 
     */
    public void publishDocuments(){
        // some code...
    }

    The comment must describe methods purpose, and the why of its existence, and do not give information about its implementation.

  • Do not abbreviate – It is not a good idea to shorten the words in the comments, shortened words make your comments difficult to read and to understand.
    //Hold ref to cli PPV
    Account account = daoFactory().getDaoAccount.getAccount();
    //Holds the reference to the clients Pay Per View
    Account account = daoFactory().getDaoAccount.getAccount();

    Writing the comment without abbreviating it you will expend just a little more time but it will make easier for anyone to read it at the first time. Recall: “You create your code so other people might read it; it defines you as a professional”.

  • Do not comment the obvious – There is some kind of codes that does not need any comment and when you do it, you decrease the quality of your code. And it’s so easy to do this…
    /**
     *Methods that calculates the bill total value
     * 
     */
    public void calculateBillTotalValue(Customer customer, Bill notPaidBill){
        // Creates the closed bill date with "today" date
        Date closedBillDate = new Date();
        
        // Sets unPaidBills to zero
        int unPaidBills = 0;
    
        // Check if the bills has the payment delayed
        if (notPaidBill.isPaymentDelayed(closedBillDate)){
            // If the payment is delayed add some interest
            notPaidBill.addInterest(closedBillDate);
        }
        
        // some code...
    }

    The code above didn’t need of that kind of comment, and the method comment just repeats the methods name. When your code is clear, you won’t need to comment every line.

    /**
     * Method that calculates the total bill value that has to be paid, add interest if needed.
     * 
     */
    public void calculateBillTotalValue(Customer customer, Bill notPaidBill){
        Date closedBillDate = new Date();
        int unPaidBills = 0;
    
        if (notPaidBill.isPaymentDelayed(closedBillDate)){
            notPaidBill.addInterest(closedBillDate);
        }
        
        // some code...
    }

    We are able to read the code above in a clear way, without needing those comments. If you have to much unnecessary comments your code gets dirty, huge, hard to read, and worst, can turn the people that read it angry.

  • /* end for */ or /* end while */ – Putting this kind of comment is useful only when you got nested repetitions(loops).
    while ( /*  while controller */){
        while ( /*  while controller */){
            while ( /*  while controller */){
                
            }/* end while */
        }/* end while */
    }/* end while */
    car.turnOffEngine();
  • This kind of comment makes the reading clearer when we got a sequence of nested repetitions (loops), but it turns harmful when we have just one repetition(loops):

    while ( /*  while controller */){
    }/* end while */
    car.turnOffEngine();

    PS.: If you have a lot of nested repetitions(loops) maybe it’s time to split them in separated methods.

  • Comments overplus [1] – When you put too many comments in your code, you get a dirt code, hard to read. The focus of someone that reads it will go to the comment instead the code, which should be the one receiving the focus. When you have a clean code there is almost no needing of putting comments, and even better, it raises tracking chances when are looking for some business bug code, because, your focus will go to the code instead of going to the comment.
  • Comments overplus [2] – If your see a lot of comments in one of your methods maybe it is time to do some refactor. Your code must always be clear, of easy understanding. Don’t use too much words to describe your methods, if you do, there is something wrong.
  • Warn about consequences – Always let the user know if your method has any consequence after been invoked. There are some methods that may affect the software behavior in an unexpected way. As sample: clear temporary files, erase database data and to start a process of remote connection that would overflow the server processing.
  • Required Comments – A clear code it’s able to eliminate most of the comments. Use comments just when it’s really needed, let your code speak for itself.

I hope this post might have aggregate some value to your knowledge. Any doubt? Just comment that I will answer.
See you soon.

Clean Code – Part 02

>Good night everyone, everything ok?

Let’s continue with the subject of keeping our code clean? The first part you can find in here: Clean Code – Part 01

Today we will be talking about scoped variables and attributes.
PS.: Every time I write attributes, I will be referring to both cases, OK? To scoped variables (methods parameters, definitions of variables inside of loops), and to classes attributes. By doing this I will not be repeating attributes/scoped variables all the time. It will make the text smaller and easier to read.

  • Use camelCase at attributes names – this is a basic tip and you will see it around every time. Makes the reading easier and it is adopted by a lot of other development languages. Some samples would be:
        String disapprovedStudent;
        double totalDivide;
        boolean isManager;

    An advantage is that it’s easier to read in camelCase then:

        List player_own_goals;
        List playerOwnGoals;

    A disadvantage would be for long attributes names:

    Map allYellowHousesFromTheBlock;

    That means, use it but don’t abuse.

  • List name on plural – why put a name like: “listPerson” if you just name it as “people” it will give the same idea? There is a huge difference between person and people by the meaning of those words. Keep this concept in mind and you shall see how legible your code will be. Lets see a sample of how a “foreach” would be:
        List houses = new ArrayList();
        // adds the houses from the block at the list 
        for (House house: houses) {
            this.ringBell(house);
            this.runForYouLife();
        }

    Notice that when you read the name “homes” from the list it is clear that we are talking about a group of “home”. When more often this naming “pattern” be applied to your system, clearer will be to those that read it the attribute meaning and how it is used at the method.

  • We shall name the attributes with real names and ye spoke ones, names that provide a “self-explanation”. Think in case you find this kind of attributes naming:
    public class Car{
        //... some code
        boolean caCra;
        //... some code
    }

    What that attribute suppose to mean? What it would be its purpose? How do you say that? Imagine you calling your coworker, and when you try to explain what you are doing, he asks you: “Ok, but which attribute are you talking about?”! How you would you say that?
    Having an attribute with a name straight, objective and “ye spoke” you already can imagine what it means, and when you refer about it with someone, it would be easier to be spoken and the one that is listening you, just by hear it, it might be able to remember of that code. Oh yea, that attribute name how would be if named right?

    public class Car{
        //... some code
        boolean isCarCrashed;
        //... some code
    }
  • If you see the code below, be careful. It might give you a lot of misunderstanding:
        int value1, value2, value3;
        // ou 
        String name1, name2, name3;

    What could possibly mean the one, two or three? Notice that at any moment the attribute let us know where it would be used or in which way it will be used. The code gets harder to understand. In case you got some bad luck getting a nested if/else/while with those kinds of attributes, go get a coffee because you are going to have a very long afternoon… Imagine this situation:

        String str1, str2, str3, str4;
        //... some code
        str4 = str3.substring(4,8) + str1.concat(str2);

    Now, imagine if the code had been written like this:

        String userLogin, userPassword, lastLoginDate, userAccessKey;
        //... some code
        userAccessKey = lastLoginDate.replaceAll("/", "-") + userLogin.concat("-" + userPassword);

    We are able to understand what this code is doing just by the attributes name. By doing this inside of a method with a good naming… Make a perfect combination that will make every developer, which reads your code, happy. I have seen cases that semantically (it was an OO study) which it would not have another possibility instead putting numbers at the end like 1 and 2. If you have in mind the same concept and perception, that the project would not loose its cohesion and its definition if the attributes receive the numbers in the end (1 and 2) go ahead and implement it.

  • Attributes names must make sense to the context that the attributes are being used. Always when you read an attribute name you must understand it in that code, for that specific context:
        //... some code
        int total = 0;
        for (Trade tradedBall : tratedBalls) {
            total += tradedBall.getTotalTratedItens();
        }
        for (Trade tratedHelmet : tratedHelmets) {
            total += tratedHelmet.getTotalTratedItens();
        }
        StockFacade stockFacade = FacadeFactory.getStockFacade();
        stockFacade.updateAmountTratedItens(total);
        //... some code in the same method
        //... 
        //... 15 lines after
        double totalSpent = financialFacade.calculateSpentValue(spentValuesWithEmployees + (valuePerIten * total));
        return totalSpent;

    What is that “total” that came from nowhere at the final sum? Where does its value come from? Which role it has on that method? Now, imagine if instead of “total” its name was “totalTradedItens”. Read that code again changing the “total” name for the suggested name.
    This is the difference of always give a name that has the same value at the context where it is used.

  • Do not specify the attributes type in the front of its name. It is very usual you find “intAge”, “strName”, and “dtBirth”. You might ask: “What’s wrong with it?” Remember that one of the good practices is that the attribute name should “self-explain”? Put the attribute type in front of the name has some advantages:
    • Stimulate some bad attribute naming: it is easier think in put “dtBirth” then “birthDate”. And the idea of “sex-explain” names would start to fail. Others weird names could appear like: dtBir, dtNatDe (naturalDeathDate).
    • Type abbreviations at attributes names: it would not take long to see names like: “strName”, “stName” or “nmName” (if the attribute name was just “name” it would be ok). So far nothing extravagant, but imagine if your software has a javascript and then you start to see: “cbDtSt” or “txtNmFi”. What would be your reaction? Would you know how to explain each one? Believe in me, I’m not overreacting, I’ve seen attributes with that name.
  • Have you ever thought about short attribute names and easy to type? Suppose that in your software you got an attribute named “allAliensFromTheEntireUniverse”. Now think if you have to type that attribute name every time… Would not be easier if was just “aliens”? It is easier and we could understand that it is a list. Don’t you have times that you are doing that exciting code and when you have to type the giant attribute you think: “Come on, should I have to type it again?”? With IDE’s “self-complete” it is easier to type those attributes name, but imagine someone having to choose between 5 names every time instead just typing it if a small attribute name was. Remember, an attribute name should not back away people.
  • Space between your attributes – A code that has a lot of calculations and methods calls with out spaced attributes, it is a headache! Let’s see a sample:
    total=salesPerDay(today)-(COMMITTEE_PERCENTAGE*vendors+totalSoldItens);

    A code it’s cleaner when it has space between its attributes:

    total = salesPerDay(today) - (COMMITTEE_PERCENTAGE * vendors + totalSoldItens);
  •  Avoid sending null attributes: sending null attributes it’s the root of all nullPointers! Just imagine if you are invoking a method that you never use before, but they told you: “Go ahead, put this invoking at your method and send it to the client. You can trust because this method it’s bulletproof!” But what they never told you is that you could not send a null value. When this happen (null pointer) the trust from your client to your software would be shaken.

Well folks, I hope this article might help you.

This subject will be continuated.

Clean Code – Part 01

Have you thought about what people think after they read your software code? I’m not only talking about people that you hang with in these days. Remeber the first company where you worked, will your code be praised? Whould the guy who works with you get a psychotic freak-out if he tries to read and understand the last code you wrote? What do you think, about the quality of the code that you are refactoring today? Which skills levels would you give to the creator of that code?

The question that remain: “After people read our code, would they have us as a reference for development?” (ouch!).

For this to happen, we should do some good practices and costumes while writing our “Daily If”. This subject is huge, so I have to split it.

As a start point, we will use a system that summarizes soccer matches. A little brief about it: “Soccer Show is a system whose objective is to summarize soccer matches. The system must have: date/hour of the scheduled matches, matches place of teams that will be playing (and the players), the result, the sum of the cards applied by the officials”.

1 – Classes

  • It’s a good choice to name the classes as nouns. At our sample system, we could identify: Match, Stadium (match place), Team, Officials and Players. This will help you to think and understand what’s going on. It will give you a better vision of the application context. Imagine if we had declared Stadium as a String at Match class. If later we were asked to add the Stadium capacity, we would create another attribute in Match, the class would start losing its “Cohesion”, who else should know the capacity of the people in the Stadium, but the Match.
  • Classes not in plural. Tell me what will pass through your mind after reading this class name: “Players”. A collective of players is a probably answer. It’s pretty obvious, but, I have seen this happening at some applications. When I asked why, no one told me the reason of that name (they did not know it). Naming your class correctly will bring more clearness to your class purpose.

2 – Methods

  • Methods name should indicate a verb. After we read the method name, we already can have an idea of what this method will do. By Sample:
    match.goal(value);

    What does this piece of code? What does it returns? Then you take some time getting in the class, opening the method to read the code… Imagine if the code was like this:

    match.getGoalsByPlayer(player);

    After reading the method name (with the verb), you already have an idea of its return object, even more, a possible method behavior.

  • It’s a good idea that each method contains only one behavior. Imagine if you invoke a method to get the total of present audience at the match:
    List presentAudience = match.getTotalPresentAudience();

    After you invoke the method you get this message:

    Exception in thread "main" main.DaoPublicException
      at main.DaoPublic.updateTotalProfitMatch(DaoPublic.java:6)
      at main.PresentAudience.getPresentAudience(PresentAudience.java:7)
      at main.match.getPresentAudience(match.java:7)
      at main.Principal.main(Principal.java:13)

    But, why a method that updates the matches profit is doing at this simple GET method? Your method must be “Cohesive”. Even, if there is no option, as last choice, change the methods name so the developer that will use the method will be aware of what might happen. (I know, its ugly, but…)

    match.getPresentAudienceAndUpdateProfit();
  • Indent: This is like “The First Developer Rule”. The problem is that each developer has its own preference, and sometimes it does not fit at the company indent pattern. One thing is for sure, I do not know which indent pattern you will adopt, but, please, take one. Right below we get two codes where it’s easy to see which one is easier to read:
            public int calculateScoredGoals()
        {int total = visitorTeam.getScoredTeam() +
    houseTeam.getScoredTeam();
                return total
            ;}
      public int calculateScoredGoals() {
        int total = visitorTeam.getScoredTeam() + houseTeam.getScoredTeam();
        return total;
      }

    It does not matter what kind of indent you will adopt, just chose one that makes the code reading easier not only for you, but for your entire company.

  • We should not keep returned attributes from methods if it will not be accessed later. Let’s imagine an update method which returns a list with the objects that were updated:
      public void updateMatchDate() {
        //... Some code
        List expelledPlayers = DaoFactory.getDaoMatch().updatePlayers(expelledPlayers);
        //... More code, but none of them accessing expelledPlayers
      }

    What’s the motive of creating the list? What for? Just invoke the method and it’s done. The list will be updated and you will not have an allocated object without reference.

This was the first post about this subject, much more are coming! Leave your opinions bellow so we might chat about it. I love to learn with other people experiences.