Coding style

If something doesn't fit in any other forum then post it here.
Forum rules
READ NOW: L2j Forums Rules of Conduct
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Coding style

Post by theone »

Over the years I've seen (and I've been the source of... ;) ) alot of flaming on these forums as to why most scripts dont get committed.
However, other than in some sparse comments from L2J devs regarding some contributions I've never seen any kind of "Coding style guide" on this forum (correct me if I'm wrong... maybe I just didnt notice it).
I think it would make your (the L2J devs team) and the community's lives easier if there were clear rules as far as coding style.
It would not only make everything that gets committed easier to read/understand and more standardized, but it would also give some guidelines to people who want to contribute code to L2J as to "what they should at least do in order for their contribution to be even looked at by the team", and they'd know that if they followed those guidelines they'd have much more chances that what they contributed would be committed as the code would be cleaner and therefore much easier to correct if there are mistakes.

I'd like to suggest a few coding style rules if I may:

Javadoc/commenting:
Every class/interface/enum should be commented as to what its purpose is, general use, etc... and the name of the author.
Also, EACH METHOD in that class should be commented clearly to state what it does

Easily understandable class/interface/method names
Class, Interface, Enum and method names should be easily understandable.

Avoid abusing if/else if
Please, for the love of whatever god you believe in, go easy on the if/else if!
It just makes your code confusing for no good reason and makes it harder to debug/fix/maintain later on for just that reason.
There are tons of situations when you can avoid using intricate if/else if statements, make sure there's no other way before you go and do something like this (what follows is what NOT TO DO):

Code: Select all

if(whatever >= 2){  if(whateverelse.equals("hello"))  {     // do something  }  else if(whateverelse.equals("me"))  {     // do something  }  else  {     // do something  }}else if(whatever < 1){  // do something}else{  // do something}
Think before you code!
Organize your thoughts on paper before you start coding. Make sure you didnt forget anything so that you dont have to go back and modify things afterwards, this ends up creating a mess in your code and others have a hard time making sense of it.

Code for others!
There's a great deal of chance that others will end up reading, expanding, modifying your code. Remember this when coding and commenting your code. Try to make their life easier!

Think about maintainability and expandability
This is CRUCIAL and it's one thing that forgotten 99% of the time in contributions.
We make something "that works fine" but we forget that it will later need to be maintained, expanded and/or improved in the futuer. Think about this when you're coding, program in a way that it will be easy for yourself or someone else to get in there and modify the code without breaking everything.

Avoid at all costs code that breaks!
Desing your code so that all hell doesnt break loose whenever something goes wrong or when it gets modified.
Think about making your scripts modular(if it's a larger script) with standardized in/out methods. This way if you need to update/maintain/modify a module, you only need to modify that part and you dont need to go and modify tons of other stuff in your script.

Dont be a jackass
So you're contributing something. Honestly and from the bottom of my heart thank you for putting your heart into this and keep up the good work.
However, dont be a jackass about it! Others before you have contributed as much and even much more than you have. Remain humble, others have things to learn from you, but you also have things to learn from others.

Keep trying
Your contribution didnt get committed for which ever reason? Ask why and what you should change to make it committable and keep working on it until it's good enough! Because "your script works fine on your server" doesnt mean that it will get committed. There are alot of things to take in consideration, and the "retail-like" thing is just one of them (and not even the most important in alot of cases). Security, efficiency, low ressource usage, maintainability, etc... are just as important if not more!

Variables
The names of variables should always be clear and easy to understand.
They should be all at the top of the class so they can be found easily later.

Variable names
Be consistent and always use the same style when coming up with variable names. They should be similar all through your script and follow general coding conventions.
from: http://docs.oracle.com/javase/tutorial/ ... ables.html
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_".
Think about ressource usage!
Always code thinking about the best way to accomplish what you set out to do while using as little ressources as possible. Think about memory leaks and such as well.
There is a garbage collector, that's true, but remember to release your variables when they're not needed anymore. It's easy to end up with variables "lost" that the garbage collector cannot get to if you dont remember to release them.
Example:

Code: Select all

public class TestClass{  int value;  public TestClass(int value){      this.value = value;  }}

Code: Select all

public class TestClass2{  private TestClass test;  public TestClass2(TestClass test){     this.test = test;  }    public void cleanup(){     test = null;  }}

Code: Select all

public class TestClass3{  private TestClass2 test;  public TestClass3(TestClass2 test){     this.test = test;  }   public void cleanup(){     test.cleanup()     test = null;  }}
If I had not released(set to null) the "test" variable in TestClass2 before I removed the reference in TestClass3 (set its "test" variable to null), the garbage collector would not have collected the instances of TestClass and TestClass2 because they were still linked together, but they would have ended up being unreachable code since I had no more a reference to them... Things like this can end up causing memory leaks and be a real burden on a server, especially with high player counts.

Dont do spaghetti code! Take an hour or two to read a bit about design patterns!
This is the most important part!!!
Please visit both links!
http://en.wikipedia.org/wiki/Spaghetti_code
http://www.javacamp.org/designPattern/
Last edited by theone on Sun Jan 08, 2012 6:53 pm, edited 3 times in total.
Image
User avatar
jurchiks
Posts: 6769
Joined: Sat Sep 19, 2009 4:16 pm
Location: Eastern Europe

Re: suggestion: coding style

Post by jurchiks »

Well, l2j already has the Eclipse code style/formatter/compiler settings so if You use Eclipse, most of these are there (the javadoc settings are not very demanding though). Someone could make the same thing for NetBeans; I'm sure there is someone who uses it.
But the thing is, what if I have my own coding style?
That is absolutely no reason to decline a contribution. Anyone can always just open the class I wrote and format it in their own way, but some people just find it too damn difficult to do, even though in Eclipse all it takes is to tap Ctrl+Shift+F and the magic has happened; I have even set it up to format every time I save a file.

And about the Keep trying part - what if the code is already very good and yet it is still ignored? I know for sure such cases exist.

P.S. if you don't want to argue about this here, PM to keep the thread clean. I can predict this could boil out of control if someone gets too passionate.
If you have problems, FIRST TRY SOLVING THEM YOURSELF, and if you get errors, TRY TO ANALYZE THEM, and ONLY if you can't help it, THEN ask here.
Otherwise you will never learn anything if all you do is copy-paste!
Discussion breeds innovation.
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

jurchiks wrote:Well, l2j already has the Eclipse code style/formatter/compiler settings so if You use Eclipse, most of these are there (the javadoc settings are not very demanding though). Someone could make the same thing for NetBeans; I'm sure there is someone who uses it.
it's really lacking... and really has not much to do with coding design (take a look at this it will be very informative for you: http://www.javacamp.org/designPattern/)
jurchiks wrote:But the thing is, what if I have my own coding style?
Everyone has it's own coding style, but when working on a large-scale group project things should be a bit standardized so they are easier to maintain and modify later on. Standardizing the basic coding style of a large project doesnt mean that you need to completely change the way you code, but it does mean there should be conventions as to how coding should be done. In the long run you gain alot by using coding conventions for maintainability. Just take a look at the current L2J code, if it was all done with coding conventions and using proper design patterns upgrades/maintenance would be much much easier than it is now.
jurchiks wrote:That is absolutely no reason to decline a contribution. Anyone can always just open the class I wrote and format it in their own way, but some people just find it too damn difficult to do,
imho it should be. Learning how to organize your code properly should be the first thing for contributors (and god knows I was the champion of spaghetti code in the past...)
jurchiks wrote:even though in Eclipse all it takes is to tap Ctrl+Shift+F and the magic has happened; I have even set it up to format every time I save a file.
If you think that's code formatting... think again :D
jurchiks wrote:And about the Keep trying part - what if the code is already very good and yet it is still ignored? I know for sure such cases exist.
Doesnt matter, it will have been a good learning experience for you even if it doesnt get committed. But if it's well written it's much easier to ask why it doesnt get committed because the devs will be able to make heads or tails of your code without having to test the hell out of it.
jurchiks wrote:P.S. if you don't want to argue about this here, PM to keep the thread clean. I can predict this could boil out of control if someone gets too passionate.
I'm not passionate about this anymore, just trying to help out :)
That's just my 2 cents anyway, I'm sure others have different opinions.
On a last note, as a good example for mangled spaghetti code, I recommend you take a look at L2PcInstance.java... :mrgreen:

I'm not trying to flame at you or anybody else here btw, so please no one start flaming on this thread. We're just having a discussion and arguing about our respective opinions. It should remain a healthy discussion.
Image
User avatar
jurchiks
Posts: 6769
Joined: Sat Sep 19, 2009 4:16 pm
Location: Eastern Europe

Re: suggestion: coding style

Post by jurchiks »

theone wrote:
jurchiks wrote:even though in Eclipse all it takes is to tap Ctrl+Shift+F and the magic has happened; I have even set it up to format every time I save a file.
If you think that's code formatting... think again :D
I think you're mixing code formatting and design patterns together in one bowl. Not the same thing.
theone wrote:
jurchiks wrote:And about the Keep trying part - what if the code is already very good and yet it is still ignored? I know for sure such cases exist.
Doesnt matter, it will have been a good learning experience for you even if it doesnt get committed. But if it's well written it's much easier to ask why it doesnt get committed because the devs will be able to make heads or tails of your code without having to test the hell out of it.
It might be a learning experience for me if it was something big, but if it is something trivial and yet it is ignored...

About L2PcInstance - yeah, that's hell for a serious programmer, and yet it keeps growing.
If you have problems, FIRST TRY SOLVING THEM YOURSELF, and if you get errors, TRY TO ANALYZE THEM, and ONLY if you can't help it, THEN ask here.
Otherwise you will never learn anything if all you do is copy-paste!
Discussion breeds innovation.
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

jurchiks wrote:
theone wrote:
jurchiks wrote:even though in Eclipse all it takes is to tap Ctrl+Shift+F and the magic has happened; I have even set it up to format every time I save a file.
If you think that's code formatting... think again :D
I think you're mixing code formatting and design patterns together in one bowl. Not the same thing.
[/quote]

Well... yes and no... but I did have the term wrong (coding style). I meant coding conventions.
Desing patterns are in the same line of thought but provide tools to write more efficient and cleaner code.
Coding conventions basically refers to standardizing common programming techniques (i.e: variable names and placement in the class, the way javadoc should be written, etc...etc..) to facilitate team work and code maintainability.

I must admit that I was the champion of spaghetti code in the past.
Then I got to work on a project with Fordfrog and he convinced me (ok... he forced me :D ) to follow some strict coding conventions, which lead me in turn to start reading about design patterns and then I eventually saw the light!
Changing the way I code completely was a hard task and it took some time, but I would not go back.
I code in a much cleaner and more efficient way now. I get 100X less bugs in my code because of this. Any developer can get into code I made and understand/modify it easily without having to wonder what's what and how it works.

This was actually meant to be a very positive post, I hope it will be seen this way :)
Last edited by theone on Wed Dec 28, 2011 8:02 pm, edited 1 time in total.
Image
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

jurchiks wrote:It might be a learning experience for me if it was something big, but if it is something trivial and yet it is ignored...
I've been there... I can relate :|
jurchiks wrote:About L2PcInstance - yeah, that's hell for a serious programmer, and yet it keeps growing.
take a look:
viewtopic.php?f=69&t=24363&p=142181#p142181
I might need help doing this if you have some spare time ;)
Image
Evilus
Posts: 387
Joined: Mon Jun 09, 2008 6:08 pm

Re: suggestion: coding style

Post by Evilus »

theone. I see you made few topics trying to help l2j community. Stop it! Lol....no but seriously I am just trying to say the community has not changed since you have been gone, in fact it has prolly gone for the worse. Don't think that someone will read this other than maybe tops 5 people, not to mention this topic will die in less than a week and become 1 of the forgotten ones at page 73 :D, unless some nice soul(Zoey) stickies it ^^.

Same goes for that other topic you made even though 2 devs actually said it is nice , I highly doubt it will get committed, unless again some nice soul(Zoey) commits it ^^.

Thanks for at least trying but I wouldn't hold my breath your attempts will do any good at all.

Also now on topic ^^, your points are very valid here. In the project I work which remains to be unnamed here since most know anyway...We have forced to write javadocs for some time now. Our code is very well documented and this makes the next time that wants to find something or possible fix something he doesn't have to read through thousands of line of code to find what he is looking for instead he/she just reads the javadocs and then reads maybe 100 lines of code. You save at least 10 minutes even if there is 1 line like return xxxx; You saw yourself or some other person a lot time next time they read it. Because I doubt everyone remembers everything they wrote at some point.

The code for others is very very important, even if it may be very clear for you doesn't mean it is for someone else. Ah spaghetti code is so nice...there is so much of it and so easy to make it. You are bound to make so many bugs when coding like that.
User avatar
jurchiks
Posts: 6769
Joined: Sat Sep 19, 2009 4:16 pm
Location: Eastern Europe

Re: suggestion: coding style

Post by jurchiks »

theone wrote:
jurchiks wrote:About L2PcInstance - yeah, that's hell for a serious programmer, and yet it keeps growing.
take a look:
viewtopic.php?f=69&t=24363&p=142181#p142181
I might need help doing this if you have some spare time ;)
Already did a couple of hours ago. Looks simple and effective, but to actually get good friction from the main bunch of developers I'm afraid you'll have to provide a real-world example of a script that uses those event listeners.
ATM despite holidays I am preparing for 2 olympiads so I don't really have that much free time.
If you have problems, FIRST TRY SOLVING THEM YOURSELF, and if you get errors, TRY TO ANALYZE THEM, and ONLY if you can't help it, THEN ask here.
Otherwise you will never learn anything if all you do is copy-paste!
Discussion breeds innovation.
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

Hehe, nice to hear from you Evilus!
It's been a while :)
Image
User avatar
MELERIX
L2j Veteran
L2j Veteran
Posts: 6667
Joined: Sat Sep 23, 2006 11:31 pm
Location: Chile
Contact:

Re: suggestion: coding style

Post by MELERIX »

I think there is some people confused about the difference between: Format Code vs Cleanup Code vs Code Style xD

a IDE (for example Eclipse) can help you to "Format & Cleanup" the code (fixing indentations, extra white spaces, etc) also could help you to follow "Code Conventions" (where put {}, or where (), or fixing enumators, etc).

but, Eclipse can't help you to fix "Code Style", because it depend 100% of the Dev-Side, and what he learned and from where he learned it (teachers, books, internet, university, etc) :P

PD: I remember there is a option in Eclipse to enable warnings for "Avoid abusing if/else if" or something related.
User avatar
jurchiks
Posts: 6769
Joined: Sat Sep 19, 2009 4:16 pm
Location: Eastern Europe

Re: suggestion: coding style

Post by jurchiks »

MELERIX wrote:PD: I remember there is a option in Eclipse to enable warnings for "Avoid abusing if/else if" or something related.
Nope, there is only an option to separate else ifs on a new line or keep them in one line, like that:

Code: Select all

if (cond1) {...} else {  if (cond2) { //...  } else { //...  }} 
Eclipse can turn that into this:

Code: Select all

if (cond1) {...} else if (cond2) {//...} else {//...} 
which is the same thing written shorter.
If you have problems, FIRST TRY SOLVING THEM YOURSELF, and if you get errors, TRY TO ANALYZE THEM, and ONLY if you can't help it, THEN ask here.
Otherwise you will never learn anything if all you do is copy-paste!
Discussion breeds innovation.
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

MELERIX wrote:but, Eclipse can't help you to fix "Code Style", because it depend 100% of the Dev-Side, and what he learned and from where he learned it (teachers, books, internet, university, etc) :P
+1
You got exactly what I meant
Image
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

Just a little example about if statement abuse for those of you who might think it's a correct way to code :P
I did this really fast off the top of my head, didnt really check the logic or if I made mistakes but it will give you a good idea about what difference thinking about what we code and how we code it makes on the final product.
Take a special look at the two methods:
private static int getPointsGainedWrongWay()
private static int getPointsGainedCleanWay()

They give the same result...
Also, look at the clutter I remove from the main method (init) by assigning the names in a separate method and only calling this method in init()

I did not take time to comment all the methods, I usually do but this is just an example

Code: Select all

public class TestClass{    private static Random rnd = new Random();        private static String name1,name2,name3,name4,name5;        private static String[] nameVals = {        "John",        "Valerie",        "Eric",        "Mark",        "Louisa",        "Steven"    };        /**     * points are added based on the number of     * names which are the same (i.e.: 3 names are the same = 3 points)     * The preceding statement needs to be true in order to continue.     * i.e.:     * name1 = name2... check name3     * but if name3 != name1... stop and start again from name2     */    public static void init()    {                int pointsGained = 0;                for(int i=0; i<1000; i++)        {            assignNames();             //pointsGained = getPointsGainedWrongWay();            pointsGained = getPointsGainedCleanWay();        }       }        /**     * Lots of if mumbo-jumbo... enough to give you a good headache :D     * @return     */    private static int getPointsGainedWrongWay()    {        int result = 0;                if(name1.equals(name2)){            result ++;            if(name1.equals(name3)){                result ++;                if(name1.equals(name4)){                    result ++;                    if(name1.equals(name5)){                        result ++;                    }                }            }        }        if(name2.equals(name3)){            result ++;            if(name2.equals(name4)){                result ++;                if(name2.equals(name5)){                    result ++;                }            }                   }        if(name3.equals(name4)){            result ++;            if(name3.equals(name5)){                result ++;            }        }                   if(name4.equals(name5)){            result ++;        }                return result;    }        /**     * There are tons of other ways to do this, I just wanted     * to illustrate one simple to understand way to do this     * without getting into comparators and such     * @return     */    private static int getPointsGainedCleanWay()    {        int result = 0;                String[] names = {name1,name2,name3,name4,name5};                /*         * we dont need to check on if(name5.equals(...)) that's         * why it says i<(names.lenght-1)         */        for(int i=0; i<(names.length-1); i++)        {            for(int j=i+1; j<names.length; j++)            {                if(names[i].equals(names[j]))                {                    result ++;                }                else{                    break;                }            }        }                return result;    }        private static void assignNames()    {        name1 = getRandomName();        name2 = getRandomName();        name3 = getRandomName();        name4 = getRandomName();        name5 = getRandomName();    }        private static String getRandomName()    {        int index = rnd.nextInt(nameVals.length);        return nameVals[index];    }}
Image
User avatar
Zoey76
L2j Inner Circle
L2j Inner Circle
Posts: 7005
Joined: Tue Aug 11, 2009 3:36 am

Re: suggestion: coding style

Post by Zoey76 »

I had been trying to enforce some of the Java Code Conventions, but the problem is that even myself don't use 100% JCC and there is no real documentation except 10 vague "pages" in some oracle siteand I don't even want to begin with JavaDocs which lack official conventions, anyway I (in Eclipse) tried to enforce "correctness" on JavaDoc.

Anyway suggestion in first post are mostly fine (I use underscore for variables :D but also use getters and setters :twisted: )

The contributors part of the community is small, when I started I got some minor commits accepted at html typos, but code contributions committed? no way, I had to contribute over a year to get something committed, and it wasn't my code that was wrong, anyway I keept trying and helping out others and never complaint about a code not committed, of course didn't make me happy at the moment, but is part of a learning curve, I see things different than former L2J Devs, if someone has potential I try to lend a hand to help him get full development and in the end help everyone else.

This topic could get sticked, but you need to keep first post for code suggestion only and clean and the other posts for opinion/talk about this topic. :wink:

Finally I don't think we (current dev team) have ever rejected a contribution only based in code format/style, most of the time we request the contributor (or anyone) to improve it (from our point of view) a bit and try to meet previous code standard and then we commit, also we expect community to test, I already said this before:
If you share a contribution you can't expect a dev to check the code, cleanup/fix, test in-game, check balance performance changes, etc all alone, we don't have the time to do such tasks (we are developing, testing and fixing our own contributions, anyway sometimes we do all that in order to get something committed) so instead of blaming us (the devs, which is getting really annoying :| ) look at the rest of the community and let them know that they have to do their part too. :roll:

Anyway I'm getting kindda off-topic. :lol:
Powered by Eclipse 4.30 🌌 | Eclipse Temurin 21 ☕ | MariaDB 11.3.2 🗃️ | L2J Server 2.6.3.0 - High Five 🚀

🔗 Join our Discord! 🎮💬
User avatar
theone
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

Re: suggestion: coding style

Post by theone »

just edited/updated the first post
Image
Post Reply