Jump to content

Proper Java Programming Tips - Wizards Of The Code


Recommended Posts

Hello, I had a talk with Elfocrash over in Skype some hours ago regarding good programming practices in java. This brought up a book I had read a year ago regarding that subject. It's called Clean Code, - A Handbook of Agile Software Craftsmansmith written by Robert C. Martin and I believe it's one of the most amazing books I've read so far. Since not everyone has the patience and free time to read 300 pages I feel the obligation to sum the key points of it up and post them in the form of tips in here for those that want to do an extra step to better coding.

 

I'll post very small , summarized portions of the book the same order as they are written in there starting from very simple things like naming and ending up to complex things like concurrency. Based on my mood i'll post from one to five/six tips per day each on a different post. None of them will be huge, it will only take about a minute to read them or even less.

 

Tip #1: Use Intention revealing names. Your variables, constances, methods, should reveal decent information about their role in the code.

Difficulty : Very easy

 

------------------------------------------------------------------------------------------------------------

 

Bad example:

 

int i =7; //This is the days in a week

 

Good example:

 

int daysInWeek = 7;

 

There's no need for comenting when you can place this info in the variable while maintaining its size relatively small.

 

------------------------------------------------------------------------------------------------------------

 

Bad example:

 

private DimensionalRift _dr; //The Dimensional Rift

 

Good example;

 

private DimensionalRift dimensionalRift;

 

It's not clear what _dr is when you read it later in the code. And the underscore _ is not even needed, it provides no information.

 

------------------------------------------------------------------------------------------------------------

 

 

Tip #2: The Law of Demeter: A method f of a class C should only call methods that fullfill one of the following conditions:

1)Belong in C

2)Are methods of argument objects of f

3)Are methods of objects created by f

4)Are methods of objects referenced by C

Difficulty : Medium

 

------------------------------------------------------------------------------------------------------------

 

Bad example:

 

public void calculateEarnings()

{

  resultObject = EarningsManager.getInstance().calculate(); //Bad practice EarningsManager does not fullfill any of the conditions.

  String result = resultObject.getResult().getOutcome().getStringValue(); //Trainwrech, resultObject calls nested methods that belong to other objects.

}

 

Good example:

 

public void calculateEarnings(EarningsManager manager)

{

  result = manager.calculate();

  handleResult(result);

 

}

 

public void calculateEarnings()

{

  result = manager.calculate(); //Now manager is a referenced instance inside our class.

  handleResult(result);

 

}

 

In this second example, we pass the manager as argument or reference it inside C class for the method to use it.

http://en.wikipedia.org/wiki/Law_of_Demeter

------------------------------------------------------------------------------------------------------------

Link to comment
Share on other sites

Very nice idea m8.

Maybe should u put all the portions that will u type, in the main post? Coz if ppl comment &/|| spam, it will be "hard" to find every tip.

 

About the first one, the problem comes when the "coding" evolves to "coding to not let leachers 'decrypt' so easy", huh? :P

Link to comment
Share on other sites

Bad example:

 

private DimensionalRift _dr; //The Dimensional Rift

 

Good example;

 

private DimensionalRift dimensionalRift;

 

It's not clear what _dr is when you read it later in the code. And the underscore _ is not even needed, it provides no information.

 

About this one , I prefer on using example _dimensionalRift. Just helps me  to seperate some things in my projects .

 

Would be better to update your main reply than re-reply each time , it will be difficult to read .

Link to comment
Share on other sites

About this one , I prefer on using example _dimensionalRift. Just helps me  to seperate some things in my projects .

 

Would be better to update your main reply than re-reply each time , it will be difficult to read .

 

Just let him do it the way he wants to.

If the topic gets way too spammed, then when the "guide" is finished, a mod can clean it up, combine the posts and then re-open it.

 

Great idea, by the way :]

Link to comment
Share on other sites

True I can update the first post and just bump for reminder.

 

@TheOldOne

 

What's different between _dimensionalRift and dimenisonalRift ? If you need to have two variable with different meaning you can name them different. Cause when someone else reads your code, he can't know what you mean with _. If for example you wanted one rift to be temporary you could write tempDimensionalRift. That makes more sense to others reading your code cause temp is a widelly accepted term for something that is temporary than "_" is.

 

Generally this is called variable encoding. People in the past were using different types of encoding ( postfix, prefix, Hungarian Notation ) because the compilers of the older languages could not do type checking. So they had for example to write m_dimensionalRift, username_String to remind themselves that this is a member of a class etc. But nowadays compilers do type checking so this _ thing is just an artifact of the past.

 

The reason most people are using it, is because they saw it in some code written by oldschool people who are used to write code the old way. We don't live in the 1990's anymore.

Link to comment
Share on other sites

Tip #3: Writting testable code, means avoiding static calls, singletons and the new operator inside method calls.

Difficulty : Medium

 

------------------------------------------------------------------------------------------------------------

 

Bad Example:

 

public boolean myMethod()

{

    // Injecting MyTestObject here for testing needs code editing. Factory is prefered.

    MyObjectInterface object = new MyObject();

 

    //Database can't be replaced with dummy database for testing. Also this code violates the Law of Demeter

    DatabaseManager.getInstance().persist(object);

 

    //Static call can't be replaced with dummy for testing;

    return Geodata.evaluate(object);

}

 

Good example:

 

private MyObjectFactoryInterface factory;

private DatabaseServiceInterface databaseService;

private GeodataInterface geodata;

 

public boolean myMethod()

{

    //The factory implementation can define what type of object is returned. Production or testing object etc.

    MyObjectInterface object = factory.getNewObject();

 

    //Database service can now be either production object or just a dummy in-ram container.

    databaseService.persist(object);

 

    //Geodata can now be an empty object that implements the corresponding interface.

    return geodata.evaluate(object);

}

 

------------------------------------------------------------------------------------------------------------

 

 

Link to comment
Share on other sites

  • 2 weeks later...

"Agile Software Craftsmansmith"

^ this, the one who manages to handle extreme programming or uses the ruck, will find easy to develop with L2J, and the neural networks theory would be easy as fuck.

Thanks for the bibliography, I'm already looking for the book c:

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Posts

    • Welcome to my store :  https://topestore.mysellix.io/fr/ 2015-2022 Aged Discord Account 2015 Discord Account : 50.99 $ 2016 Discord Account : 10$ 2017 Discord Account :3.99 $ 2018 Discord Account : 3.50$ 2019 Discord Account : 2.70 $ 2020 Discord Account :1.50$ 2021 Discord Account :0.99$ 2022 Discord Account :0.70$ Warranty :Lifetime Payment Methods : Crypto/ PayPal Contact Me On Discord Or Telegram Discord : @ultrasstore11 Telegram : https://t.me/ultrastore1 Welcome to my store :  https://topestore.mysellix.io/fr/ 2015-2022 Aged Discord Account 2015 Discord Account : 50.99 $ 2016 Discord Account : 10$ 2017 Discord Account :3.99 $ 2018 Discord Account : 3.50$ 2019 Discord Account : 2.70 $ 2020 Discord Account :1.50$ 2021 Discord Account :0.99$ 2022 Discord Account :0.70$ Warranty :Lifetime Payment Methods : Crypto/ PayPal Contact Me On Discord Or Telegram Discord : @ultrasstore11
    • L2 ArenaWar: Low Rate PvP Server with Free Buffs & Autofarm [PVP]⚔️ [Free]🆓 Classic Interlude with  3x XP rates! Free starter pack(no grade) to kickstart your adventure! Autofarm for convenient grinding! Free buffs to keep you fighting fit! (2 job buffs) No experience loss on death! (Except with Karma) Clear Karma system to keep things fair! ⚖️ Active community of 800-1k players! Join our Discord to learn more! >> Discord <<     Server website: https://l2arenawar.com/en/    
    • This is dedication! 2 years working on a problem. Congratulations!
    • You indeed have to save player position over Enterworld to properly clean it up later (if you don't, even trying to delete packet content would eventually keep it up), that's what we do with debug packet (which is a reusable Map of ExServerPrimitive packets) on aCis.   It doesn't solve the FPS stuttering - more you draw/delete lines, more your client becomes laggy. It's like if client wasn't deleting drawn points/lines properly, but instead simply hide them and redrawn content above.   If you got a solution, I would happy to integrate it.   You should check aCis#Player _debug packet integration, it allows very big amount of lines/points to be drawn, it is also reusable.   https://gitlab.com/Tryskell/acis_public/-/blob/master/aCis_gameserver/java/net/sf/l2j/gameserver/model/actor/Player.java?ref_type=heads https://gitlab.com/Tryskell/acis_public/-/blob/master/aCis_gameserver/java/net/sf/l2j/gameserver/network/clientpackets/EnterWorld.java?ref_type=heads  
    • we sell website templates, make websites to order. Great selection at very good prices. My contacts discord : advert1231 telegram : https://t.me/ggwpins  
  • Topics

×
×
  • Create New...