Jump to content

Recommended Posts

Posted

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

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

Posted

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

Posted

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 .

Posted

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 :]

Posted

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.

Posted

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);

}

 

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

 

 

  • 2 weeks later...
Posted

"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:

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

    • 🎉 ¡Llega EuroLatinL2! 🎉 🌍 Un servidor Interlude x20 con esencia retail y ajustes justos para una experiencia única. 🧠 Desarrollado por profesionales rusos, EuroLatinL2 está basado en el cliente original de Lineage II Interlude. Buscamos revivir lo mejor de la vieja escuela con un balance perfecto entre nostalgia y jugabilidad moderna. 🛡️ ¿Qué hace diferente a EuroLatinL2? ✨ Rates Mid x20 – Equilibrados para un progreso fluido, sin perder el desafío. 🧪 Experiencia 100% retail con leves ajustes para mantener el interés. ⚔️ Raid Bosses épicos ajustados al nivel 80. 💡 Nada de GM Shop, sin buffs OP, sin teleport personalizados. ⛩️ Solo tiendas y contenido original de Lineage II. 🧙 Buffer básico (solo Prophet), duración de 60 minutos. 🔄 Sistema de héroes cada 15 días y Olimpiadas 2h por día. 🛒 Sistema de donaciones solo para servicios estéticos y premium (sin pay-to-win). 🧬 Sistema de skins para armas y armaduras (solo apariencia). 💤 AutoFarm disponible solo con adena/premium, opcional. 🔥 ¿Quieres volver a disfrutar Lineage II como en sus mejores tiempos? 💬 Completa quests, forma grupos reales, derrota jefes con estrategia, y recolecta recetas (¡incluso para Soulshots!). ⏳ ¡La apertura está muy cerca! 🚪 No te quedes fuera de esta aventura. Vive Lineage II como debe ser. 🌐 Sitio oficial: https://eurolatin.eu 📣 ¡Comparte con tu clan y prepárate para la nostalgia! #Lineage2 #Interlude #EuroLatinL2 #L2Classic #PvE #PvP #NostalgiaL2
    • Still looking to adapt packets to allow modern client to connect on my GF Extender.
    • Καλησπέρα,  Αναζητώ Lineage II C3 Rise of Darkness client (καθαρή έκδοση) και το απαραίτητο αρχείο System για Windows 10/11 Προσφέρω αμοιβή για τη βοήθεια  Ευχαριστώ.   Good evening,  I am looking for a Lineage II C3 Rise of Darkness client and the necessary System file for Windows 10/11 compatibility I am willing to pay for assistance  Thank you    Add me Discord: devibtv  or dm here                                                        @AlisaCodeDragon
    • Sorry, I didn't get to read everything you actually wrote, I don't think it has value. Regards.
    • "Why do you have problems with all forum users?" I dont. I respond based on how people act toward me or my clients! You are defending someone who has been trash-talking me and attacking me directly. And somehow you think I’m the one creating the problem? Did you even bother to check what actually happened, or did you just jump on his side?    While there is another guy that knows and calls him out, he is a known scammer. on this very same topic   If you believe I have issues with all forum users, name them, vilmis is not all forum users.   Besides, this looks like you are just another Vilmis alt accounts blindly backing him without facts.   Tinker123aa I have an alergy on scammers you see, ill wait for your list of all forum users tho.
  • Topics

×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock