List of coding tips and practices

Discussion in 'Resources' started by EgyptianKing, Nov 22, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    EgyptianKing

    Hi. I've been meaning to, for a long time, write a thread dedicated to better coding practices. I believe many people will learn and benefit from this thread. I will do this by enumerating all the coding tips and practices I can think of. If I am wrong, please correct me, and I highly encourage everyone to post tips if he or she may have them.

    1. Remove objects from collections (HashMap, ArrayList) when not used to avoid memory leaks. Say you store a player object into an ArrayList, you must remove that object from the ArrayList once the player logs out or the server reloads/stops; if not, you will have memory leaks.

    2. Cast a variable after you check if some object is an instance of a class.

    3. Do not make instance variables public, rather make them private and add getter methods to retrieve the information.
    Code:java
    1. private int age = 15;
    2.  
    3. public int getAge(){
    4. return age;
    5. }

    4. Use static variables for constants and utility classes.

    5. Rather than having very large methods, split up some of the logic used in those large method into smaller, more concise methods that each serve a purpose.

    6. Document your code, but not too much. Maybe document what each class does or what each method does, but please do not document each line. I promise you, it will help in the long run.

    7. Make your code easily readable by adding a sufficient amount of white space and indenting correctly.

    8. Use else-if statements rather than multiple if statements because in multiple if statements, each if statement will be ran, but in else-if statements, the program will stop executing once a condition is true. It is more efficient.
    Code:java
    1. //Multiple if statements.
    2. if(2 == 2) //Will check if true. Will run.
    3.  
    4. if(1 == 2) //Will check if true. Will not run.
    5.  
    6. //else-if statements.
    7. if(2 == 2) //Will check if true. Will run.
    8.  
    9. else if(1 == 2) //Will not check if true. Will not run.

    9. If you know the size you want for an array, use an array rather than an ArrayList. It is more efficient.

    10. Try to make less objects, as each one takes memory.

    11. Use .equals() rather than == when comparing objects of the same type.

    12. Always parameterize your Lists, HashMaps, and ArrayLists.
    Code:java
    1. //Raw Type
    2. ArrayList players = new ArrayList();
    3.  
    4. //Parameterized Type
    5. ArrayList<UUID> players = new ArrayList<UUID>();
    6.  

    13. Never throw Exception unless when a method throws Exception.

    14. Always create a package. Use all lowercase when naming your package. (Example: me.program)

    15. Always check if something is not null before doing anything with it to avoid nullpointerexceptions. If you are writing an API, constantly check for moments your code can end up null and fix them.

    16. Use the break statement in a loop when it is appropriate in order to stop the loop from doing any unneeded iterations.

    17. Do not use wildcard imports (Example: java.awt.*).

    18. Do not create objects or perform operations that are not used.


    I hope you guys enjoyed reading this and maybe have learned a thing or two. Again, I encourage everyone to post tips or practices I may have missed in listing. I also am very open to criticism; if I am wrong in any way, I would like you to call it out on me, so that I may improve my coding abilities. Good luck everyone!
     
  2. Offline

    Skionz

    EgyptianKing You can use static when making Utility classes.
     
    Skyost likes this.
  3. Offline

    teej107

  4. Offline

    mrCookieSlime

    Moved to Resources.
     
  5. Offline

    ROTN

    Although they do go against OOP, they have their uses, otherwise it wouldn't even be there :p
     
    Skyost likes this.
  6. Offline

    Skyost

    Many things you say are wrong. Your list depends of the case and is not overall.
     
    werter318 and teej107 like this.
  7. Offline

    EgyptianKing

    Skionz teej107 ROTN
    Is there a point to making a variable or method static? Why not just make an object of the class and access the content with that object? My dad is a .NET dev and he told me he never uses static, so I just go on believing that static is not necessary, ever.

    Skyost
    You're probably right, but can you explain why many of my points are wrong? I can only see my point on if statements to be depending on case.
     
  8. Offline

    Gater12

    Well I use static methods if it makes sense to do so. If the method does not depend on an object instance, does not require an object instance then what is the point of making an object to invoke a method that doesn't do anything with that object?

    I believe you should change it to "Use static when nessascary such as keeping constants and in Utility classes"
     
    ROTN, EgyptianKing and xTrollxDudex like this.
  9. Offline

    xTrollxDudex

    Gater12
    Static can also be used appropriately on design patterns such as singletons and factories, used on performance sensitive code, and single initialization for the entire class.
     
    ROTN, EgyptianKing and Gater12 like this.
  10. Offline

    EgyptianKing

  11. Offline

    Totom3

    That's not true. In fact, this is ArrayList's get() implementation:
    Code:java
    1. public E get(int index) {
    2. rangeCheck(index);
    3.  
    4. return elementData(index);
    5. }

    rangeCheck(index) throws an exception if index is out of bounds, and elementData(index) simply returns the element in the array at the specified index. Compared to array[index], this might result in a 1 or 2 nanoseconds difference; is that what you consider more efficient?

    EDIT: I still don't see why you should be using an array over a List. A List has multiple utility methods in it. If the maximum size of my List is 50000 then should I really reserve 50000 slots of memory? Most of it will be unused and we can hardly do something about it since we can't re-size an array. If we start wrapping the array under methods that take care of these problems, it just comes down to the same as using a List.
     
    DJSkepter likes this.
  12. Offline

    EgyptianKing

    Totom3
    Yeah, well, that's just, like, your opinion man.
    On a more serious note, thanks for pointing that out; I really appreciate it.
     
  13. Offline

    Avygeil

    Totom3 You are right, using an array instead of a ArrayList (not talking about other implementations which may vary) just for efficiency is a micro and premature optimization that is nearly never needed. The only thing that could potentially be slow is duplicating the array to raise the size of the list, but even then, you can initialize your ArrayList with a fixed size, so the "constant size" argument is invalid.

    However, there are 3 reasons that would lead me to use an array over an ArrayList : first, Java is already very verbose, so it makes sense to sometimes return int[2] for a pair of ordered ints instead of List<Integer>, or even Pair<Integer, Integer>... Secondly, implementation : you are often limited to your API. For example, Bukkit's onCommand uses String[]. I'm not going to convert to an ArrayList to parse it. :) And the last reason : (pseudo)-immutability in size of arrays. The last example is perfect : it doesn't make sense to do args.add(). I know Guava adds immutability, but we're not talking about Bukkit dependencies here. ;)

    EgyptianKing other than that, that's some good tips here, but I'd like to discuss/rephrase some :

    10. Is also premature optimization, same as 9. It also depends on cases. For example simple String holders shouldn't be a problem unless you do thousands of operations. Premature/micro optimizations are evil and you should optimize if you find a bottleneck in your code. Better focus on new content.

    11. Not sure what you mean? If you mean not write "boolean b;", that's true for nested code, but fields can be assigned later.

    14. I'd rephrase to "Never catch Exception unless you are sandboxing or if a method throws Exception (essentials :(), and never throw Exception yourself."

    16. Sometimes you want to let NullPointerException happen. It depends on cases. :) Say you're writing an API, you probably want it to throw an NPE if the user passes a null argument, or if something wrong happened that you should fix. Check against null for things that can normally be null in the program flow, like getting the held item by the player.
     
    Europia79 and Totom3 like this.
  14. Offline

    RawCode

  15. Offline

    EgyptianKing

    Avygeil
    Thanks for the tips and corrections; I really appreciate it!

    RawCode
    You're absolutely right, but as long as I helped one individual, I don't care.
     
  16. Offline

    RawCode

    EgyptianKing
    You helped nobody by trashing resource section with invalid article.
    This article as good as single link to oracle documentation.
     
    _Filip likes this.
  17. Offline

    EgyptianKing

    RawCode
    Speak for yourself, not for the community. You have a right to think that my thread is invalid and that it is basically a link to the oracle docs, because that is true. Heck, everything about Java can be found at Oracle's docs, so why should anyone post any info regarding it?

    Just be the bigger man and move on. I don't care if you find my thread pointless.
     
  18. Offline

    Garris0n

    That's like telling somebody to "speak for themselves and not the mathematics community" because they told you that 1 + 1 = 2.
     
    RawCode and Skionz like this.
  19. Offline

    _Filip

    @EgyptianKing
    The resource section is good for things that people would have a hard time figuring out themselves.
    I don't see the point of posting this other than to get pretend internet points.
     
    RawCode likes this.
  20. Offline

    EgyptianKing

    @_Filip
    Initially I wanted to post this so that I may help any new dev in any way possible and to try to get people to post their practices and to correct any false statements of the posted practices. I have, by just posting in this section, learned quite a few things, and I feel as if more people can by being corrected, just like how a couple of people corrected me. Someone on this forum has a signature quote that says something about the best way to learn is to be corrected on the internet, and I think that's pretty accurate. Also I do not know what you mean by pretend internet points, but if you feel strongly about my post not belonging in the resource section, you can report the thread and maybe a moderator can remove it. Thanks
     
  21. Offline

    _Filip

  22. Offline

    teej107

    @EgyptianKing TBH, it's nice that you want to help new devs. Good advice or not, there isn't anything related to Bukkit on here.
     
Thread Status:
Not open for further replies.

Share This Page