SlideShare a Scribd company logo
Great Coding Guidelines




A beginner’s guide to write code for next generations
        Aurélien Deleusière – CF Camp 2012
 Based in Paris, France
 Software engineer specializing in web technologies,
  development, architecture and troubleshooting
 ColdFusion since 1998
 Founder of Aurel&Co
 Involved into the French community
 And, yes, I‟m supporting Railo




Who am I?
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Think to the next generations of developers
 Think to yourself when you will have to get back to
  your code later
 Think to your colleagues… it‟s your reputation…




Code for next generations
©Aurélien Deleusière – CF Camp 2012     Monday October 15th 2012
 A working code is not enough…
 …it has to be robust and maintainable




Think to the future
©Aurélien Deleusière – CF Camp 2012       Monday October 15th 2012
JUST A POINT OF VIEW
Before digging into best practices…


©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Both of course!
 But I would prefer a clean code than a fast code
 Use performance mechanisms when possible like
  mainly caching
 Always understand what you‟re doing:
     may this array can be huge one day?




Readability or performances?
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
Mark‟s CFML Myth Busters
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
Mark‟s CFML Myth Busters
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
Mark‟s CFML Myth Busters
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
ART OF CODING
In good hands,
a few lines of CFML looks like poetry.

©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Keep your code as simple as possible
 Use small functions, small files, small number of
  arguments, small names…
 …small is beautiful
 Break down complex and large things to simple and
  little tasks
 Once it works – and is tested - close your eyes and
  be confident

Perfection is attained, not when no more can be
added, but when no more can be removed.
                                      Antoine de Saint Exupéry (1900 – 1944)



Less is more
©Aurélien Deleusière – CF Camp 2012                      Monday October 15th 2012
 Don‟t rush on your keyboard!

Before writing, learn to think.
What one understands, one expresses clearly.
                                      Nicolas Boileau (1636-1711)




Think before doing
©Aurélien Deleusière – CF Camp 2012             Monday October 15th 2012
 Improve your code each time you get back on it
     « Leave code better than you found it »
   Anticipate: This function could do more…
   Consolidate: I‟ve already seen this somewhere…
   Do not duplicate code!
   But in any case: TEST, TEST and TEST!




Improve again and again
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
 Truth is always in source code
 Be curious
 Be confident
     Do not hesitate to refactor, the only reason that should
      stop you is how difficult it is to test




Other principles
©Aurélien Deleusière – CF Camp 2012           Monday October 15th 2012
 Don‟t mix a logic across multiple language
     i.e. javascript, CFML and SQL
 Keep the logic in one place




Languages mix
©Aurélien Deleusière – CF Camp 2012     Monday October 15th 2012
 It‟s not about which guidelines…
     …but have guidelines
 When you go into a code is not yours, enter in
  stealth mode, mimic the style in place:
     Make impossible to identify you when others read your
      code




Stealth coder
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
 Tags fit well with views
 Script with business code

 You can only use tags, it‟s your choice.
 You can only use scripts, it‟s your choice…
     …but never do that. Never.




Tags or script?
©Aurélien Deleusière – CF Camp 2012     Monday October 15th 2012
YOUR CODE HAS TO
TELL A STORY
Make it readable!


©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Do or do not but do always the same way:
       to indent your code
       „ or “
       ending slash for unary tags <cfabort />
       spaces <cfset count = 0 />
       void lines
       …


 One style by language is a good choice



Coding style: be constant
©Aurélien Deleusière – CF Camp 2012               Monday October 15th 2012
 Clear name with meaning
 Boolean should begins with is or has (isBlue)
 About case:
     Only object names should begin with an upper case
     Separate words with an upper case, avoid using the
      old fashion “_”
public void function onApplicationStart() {
  application.physicalRoot = expandPath("/");
  application.env = new model.utils.Env(cgi.server_name);
  application.sanitizer = new model.utils.Sanitizer();
  application.cfTags = new model.utils.CFTags();
  application.debug = false;
  ...
}



Naming conventions
©Aurélien Deleusière – CF Camp 2012                         Monday October 15th 2012
 Don‟t leave garbage into your code
<cfif 1 EQ 2>
...
</cfif>


 Don‟t comment code, remove it

 You identify a portion to improve?
  use Eclipse tasks:
//TODO: This block needs to be refactored



Keep your code clean
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
 Do not overload your code with useless comment
<!--- init count to 0 --->
<cfset count = 0 />


 A comment is stronger when it is useful and frugal
application.proxy = {
         server = "",
         port = 80, // *MUST* be a number
         user = "",
         password = "”
};



Comments
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
 Avoid McDonald‟s programming
// =======================================================
// controllo esistenza fornitore su anagrafica
q_fornitore = cfc_fornitori.GetAnagFornitore(idSocieta =
my_idsocieta, idAnag = codFornitore, const = glb.const, dbprop = glb.dbprop);
// =======================================================

// inserimento link fornitore
linkfornitore = structNew();
linkfornitore.idSocieta = my_idsocieta;

//=======================================================
if (q_fornitore.recordcount eq 0) {
    // inseriemnto tan030anagfornitori
    fornitore = structNew();
     .....
// =======================================================




Comments
©Aurélien Deleusière – CF Camp 2012                            Monday October 15th 2012
 Use every scope explicitly. Always
     Arguments, caller, query name, etc.

public Token function init(token) {
        variables.token = arguments.token;
        return this;
}




Variables scopping
©Aurélien Deleusière – CF Camp 2012          Monday October 15th 2012
 Declare a variable where it‟s used… avoid the old fashion of all
  the declaration on top (legacy from var scoping up to CF8)
public string function generate() {
            var i = 0;
            var token = "";
            for (; i <= 32 ; i++)
                         token &= chr(randRange(65, 90));

           return hash(token, "MD5");
}

public string function generate2() {
            var token = "";
            for (var i = 0 ; i <= 32 ; i++) {
                         token &= chr(randRange(65, 90));
            }

           return hash(token, "MD5");
}



Variables declaration
©Aurélien Deleusière – CF Camp 2012                         Monday October 15th 2012
 Don‟t use Magic Numbers. Never.

<cfswitch expression="#quoteRow.groupID#">
          <cfcase value="12">
                   <cfset quoteRow['isAnnual'][1] = "yes" />
          </cfcase>
          <cfcase value="13">
                   <cfset quoteRow['isAnnual'][1] = "yes" />
          </cfcase>
          <cfcase value="24">
                   <cfset quoteRow['isAnnual'][1] = "yes" />
          </cfcase>
          <cfcase value="25">
                   <cfset quoteRow['isAnnual'][1] = "no" />
          </cfcase>
</cfswitch>



Variables usage
©Aurélien Deleusière – CF Camp 2012                      Monday October 15th 2012
 Don‟t use the pound sign where it is not needed
<cfset newColor = #oldColor# />
<cfset newColor = "#oldColor#" />

 But do instead:
<cfset newColor = oldColor />




Variables usage
©Aurélien Deleusière – CF Camp 2012    Monday October 15th 2012
if (isBlue == false) {
...
}


Prefer:
if (!isBlue) {
...
}




Logic
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
if (!isBlue) {
          doThis();
} else {
          doThat();
}


Prefer avoiding “if not else”:
if (isBlue) {
         doThat();
} else {
         doThis();
}

Logic
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
if (isBlue) {
          return true;
} else {
          return false;
}


Prefer:
return isBlue;




Logic
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Parenthesis:
if (isBlue || isRed && isSquare) {...}
if (isBlue || (isRed && isSquare)) {...}

return variables.token == arguments.token;
return (variables.token == arguments.token);


 Order of variables
if ("blue" == color) { //don‟t, use EQ?
...
}



Logic
©Aurélien Deleusière – CF Camp 2012            Monday October 15th 2012
if (token.equals("1234"))
         writeOutput("ok");
else
         writeOutput("ko");


Prefer:
if (token.equals("1234")) {
         writeOutput("ok");
} else {
         writeOutput("ko");
}



Always use brackets
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Exceptions allow you to focus on the useful code
<cffunction name="login" access="public" returnType="boolean" output="false">
 <cfargument name="username" type="string" required="yes" />
 <cfargument name="hash" type="string" required="yes" />

 <cfscript>
 try {
   var user = request.object.new("User").init(arguments.username);
   var hashServer = hash(session.token & user.getPassword(), "MD5");

   if (hashServer == arguments.hash) { //connection success
              session.user = user;
              user.lastLogon(username);
              return true;
   }

   var debug = "username=#user.getUsername()#<br>password=#user.getPassword()#<br>";
 } catch (objectNotExistsException e) {
   var debug = "user not exists exception (#arguments.username#/#arguments.hash#)";
 } catch (connectionFailedException e) {
    var debug = e.message & "<br>" & e.detail;
 }
 </cfscript>

  <cfthrow type="loginFailedException” message="...” detail="#debug#" />
</cffunction>




Exceptions
©Aurélien Deleusière – CF Camp 2012                                             Monday October 15th 2012
 Don‟t make entities dependent on each others

<cfset colors = "blue,red,green,yellow" />
<cfloop from="1" to="10" index="i">
        <cfinclude template="sometemplate.cfm">
</cfloop>

<!--- sometemplate.cfm --->
<cfset i = 0>
<cfloop list="#colors#" index="lst">
         <cfset i++ />
         ...
</cfloop>


Decoupling
©Aurélien Deleusière – CF Camp 2012          Monday October 15th 2012
Principle: no dynamic value into the condition of a loop

for (i = 1 ; i <= arrayLen(items) ; i++) {
           ...
}




About readability
©Aurélien Deleusière – CF Camp 2012                   Monday October 15th 2012
len = arrayLen(items);
for (i = 1 ; i <= len ; i++) {
           ...
}


Improvement: 0% to 5%




About readability
©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
for (item in items) { // Railo and CF since 9.0.1
          ...
}


Improvement: 10% to 15%




About readability
©Aurélien Deleusière – CF Camp 2012                 Monday October 15th 2012
A REAL WORLD
EXAMPLE
We learn more from our mistakes


©Aurélien Deleusière – CF Camp 2012   Monday October 15th 2012
 Control birth date:
     60 days minimum
     Must be right with the age entered (previous screen)

Requirements
©Aurélien Deleusière – CF Camp 2012         Monday October 15th 2012
function isBirthDateValid(value,element) {
         var tmp = value.split("/");
         if (tmp.length != 3) {
                   return false;

           } else {
                       var month = tmp[1]-1;
                       var year = tmp[2];
                       var day = tmp[0];
                       if (isValidDate(month,day,year) != true) {
                                  return false;

                       } else {
                                  return true;
                       }
           }
}



Original code
©Aurélien Deleusière – CF Camp 2012                         Monday October 15th 2012
function isBirthDateValid(value,element) {
         var tmp = value.split("/");

           if (tmp.length == 3) {
                     var month = tmp[1]-1;
                     var year = tmp[2];
                     var day = tmp[0];
                     if (isValidDate(month,day,year) != true) {
                                return false;

                       } else {
                                  return true;
                       }
           }

           return false;
}



Rewriting step 1
©Aurélien Deleusière – CF Camp 2012                       Monday October 15th 2012
function isBirthDateValid(value,element) {
        var tmp = value.split("/");

           if (tmp.length == 3) {
                     var month = tmp[1]-1;
                     var year = tmp[0];
                     var day = tmp[2];

                       return isValidDate(month,day,year);
           }

           return false;
}



Rewriting step 2
©Aurélien Deleusière – CF Camp 2012                    Monday October 15th 2012
function isBirthDateValid(value, element) {
        var tmp = value.split("/");

           if (tmp.length == 3) {
                     var day = tmp[0];
                     var month = tmp[1] - 1; //month start at 0
                     var year = tmp[2];

                       return isValidDate(month, day, year);
           }

           return false;
}



Rewriting step 3
©Aurélien Deleusière – CF Camp 2012                     Monday October 15th 2012
function isBirthDateValid(value, element) {
  try {
    var birthDate = $.datepicker.parseDate('dd/mm/yy', value);

      if (birthDate.getAgeInDays() >= 60) {

        // we retrieve the current id from ”birthDate_X”
               // to check the age against "age_X"
                var id = element.id.split('_').pop();
                if (birthDate.getAge() == $('#age_' + id).val()) {
                   return true;
                }
      }
    } catch (e) {}

    return false;
}




Final code
©Aurélien Deleusière – CF Camp 2012                                  Monday October 15th 2012
Date.prototype.getAge = function() {
  var today = new Date();
  var age = today.getFullYear() - this.getFullYear();
  var monthes = today.getMonth() - this.getMonth();
  var days = today.getDate() - this.getDate();

     if (month < 0 || (monthes == 0 && days < 0)) {
        return age - 1;
     } else {
        return age;
     }
};

Date.prototype.getAgeInDays = function() {
   var today = new Date();
   return Math.floor((today - this) / 86400000); //ms to days (24*60*60*1000)
};




Final code
©Aurélien Deleusière – CF Camp 2012                                Monday October 15th 2012
Thank you! Vielen Dank! Merci !
@adeleusiere • aurelien.deleusiere.fr • cfml-france.com

More Related Content

Similar to CFCamp 2012 - Great Coding Guidelines - V1.0

Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
Building high productivity applications
Building high productivity applicationsBuilding high productivity applications
Building high productivity applications
Hutomo Sugianto
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Ugo Matrangolo
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
manugoel2003
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips
Troy Miles
 
Critical software developement
Critical software developementCritical software developement
Critical software developement
nedseb
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
Sabik T S
 
Building Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience ManagerBuilding Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience Manager
Justin Edelson
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
Andrey Karpov
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Clean code bites
Clean code bitesClean code bites
Clean code bites
Roy Nitert
 
Building Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience ManagerBuilding Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience Manager
connectwebex
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
Ólafur Andri Ragnarsson
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
Edorian
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
IEEE MIU SB
 
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
mfrancis
 
SOLID
SOLIDSOLID
Capgemini oracle live-sql
Capgemini oracle live-sqlCapgemini oracle live-sql
Capgemini oracle live-sql
Johan Louwers
 

Similar to CFCamp 2012 - Great Coding Guidelines - V1.0 (20)

Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
Building high productivity applications
Building high productivity applicationsBuilding high productivity applications
Building high productivity applications
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Sightly_techInsight
Sightly_techInsightSightly_techInsight
Sightly_techInsight
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips
 
Critical software developement
Critical software developementCritical software developement
Critical software developement
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
 
Building Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience ManagerBuilding Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience Manager
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Clean code bites
Clean code bitesClean code bites
Clean code bites
 
Building Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience ManagerBuilding Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience Manager
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
 
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
Dockerizing apps for the Deployment Platform of the Month with OSGi - David B...
 
SOLID
SOLIDSOLID
SOLID
 
Capgemini oracle live-sql
Capgemini oracle live-sqlCapgemini oracle live-sql
Capgemini oracle live-sql
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

CFCamp 2012 - Great Coding Guidelines - V1.0

  • 1. Great Coding Guidelines A beginner’s guide to write code for next generations Aurélien Deleusière – CF Camp 2012
  • 2.  Based in Paris, France  Software engineer specializing in web technologies, development, architecture and troubleshooting  ColdFusion since 1998  Founder of Aurel&Co  Involved into the French community  And, yes, I‟m supporting Railo Who am I? ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 3.  Think to the next generations of developers  Think to yourself when you will have to get back to your code later  Think to your colleagues… it‟s your reputation… Code for next generations ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 4.  A working code is not enough…  …it has to be robust and maintainable Think to the future ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 5. JUST A POINT OF VIEW Before digging into best practices… ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 6.  Both of course!  But I would prefer a clean code than a fast code  Use performance mechanisms when possible like mainly caching  Always understand what you‟re doing:  may this array can be huge one day? Readability or performances? ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 7. Mark‟s CFML Myth Busters ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 8. Mark‟s CFML Myth Busters ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 9. Mark‟s CFML Myth Busters ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 10. ART OF CODING In good hands, a few lines of CFML looks like poetry. ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 11.  Keep your code as simple as possible  Use small functions, small files, small number of arguments, small names…  …small is beautiful  Break down complex and large things to simple and little tasks  Once it works – and is tested - close your eyes and be confident Perfection is attained, not when no more can be added, but when no more can be removed. Antoine de Saint Exupéry (1900 – 1944) Less is more ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 12.  Don‟t rush on your keyboard! Before writing, learn to think. What one understands, one expresses clearly. Nicolas Boileau (1636-1711) Think before doing ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 13.  Improve your code each time you get back on it  « Leave code better than you found it »  Anticipate: This function could do more…  Consolidate: I‟ve already seen this somewhere…  Do not duplicate code!  But in any case: TEST, TEST and TEST! Improve again and again ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 14.  Truth is always in source code  Be curious  Be confident  Do not hesitate to refactor, the only reason that should stop you is how difficult it is to test Other principles ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 15.  Don‟t mix a logic across multiple language  i.e. javascript, CFML and SQL  Keep the logic in one place Languages mix ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 16.  It‟s not about which guidelines…  …but have guidelines  When you go into a code is not yours, enter in stealth mode, mimic the style in place:  Make impossible to identify you when others read your code Stealth coder ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 17.  Tags fit well with views  Script with business code  You can only use tags, it‟s your choice.  You can only use scripts, it‟s your choice…  …but never do that. Never. Tags or script? ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 18. YOUR CODE HAS TO TELL A STORY Make it readable! ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 19.  Do or do not but do always the same way:  to indent your code  „ or “  ending slash for unary tags <cfabort />  spaces <cfset count = 0 />  void lines  …  One style by language is a good choice Coding style: be constant ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 20.  Clear name with meaning  Boolean should begins with is or has (isBlue)  About case:  Only object names should begin with an upper case  Separate words with an upper case, avoid using the old fashion “_” public void function onApplicationStart() { application.physicalRoot = expandPath("/"); application.env = new model.utils.Env(cgi.server_name); application.sanitizer = new model.utils.Sanitizer(); application.cfTags = new model.utils.CFTags(); application.debug = false; ... } Naming conventions ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 21.  Don‟t leave garbage into your code <cfif 1 EQ 2> ... </cfif>  Don‟t comment code, remove it  You identify a portion to improve? use Eclipse tasks: //TODO: This block needs to be refactored Keep your code clean ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 22.  Do not overload your code with useless comment <!--- init count to 0 ---> <cfset count = 0 />  A comment is stronger when it is useful and frugal application.proxy = { server = "", port = 80, // *MUST* be a number user = "", password = "” }; Comments ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 23.  Avoid McDonald‟s programming // ======================================================= // controllo esistenza fornitore su anagrafica q_fornitore = cfc_fornitori.GetAnagFornitore(idSocieta = my_idsocieta, idAnag = codFornitore, const = glb.const, dbprop = glb.dbprop); // ======================================================= // inserimento link fornitore linkfornitore = structNew(); linkfornitore.idSocieta = my_idsocieta; //======================================================= if (q_fornitore.recordcount eq 0) { // inseriemnto tan030anagfornitori fornitore = structNew(); ..... // ======================================================= Comments ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 24.  Use every scope explicitly. Always  Arguments, caller, query name, etc. public Token function init(token) { variables.token = arguments.token; return this; } Variables scopping ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 25.  Declare a variable where it‟s used… avoid the old fashion of all the declaration on top (legacy from var scoping up to CF8) public string function generate() { var i = 0; var token = ""; for (; i <= 32 ; i++) token &= chr(randRange(65, 90)); return hash(token, "MD5"); } public string function generate2() { var token = ""; for (var i = 0 ; i <= 32 ; i++) { token &= chr(randRange(65, 90)); } return hash(token, "MD5"); } Variables declaration ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 26.  Don‟t use Magic Numbers. Never. <cfswitch expression="#quoteRow.groupID#"> <cfcase value="12"> <cfset quoteRow['isAnnual'][1] = "yes" /> </cfcase> <cfcase value="13"> <cfset quoteRow['isAnnual'][1] = "yes" /> </cfcase> <cfcase value="24"> <cfset quoteRow['isAnnual'][1] = "yes" /> </cfcase> <cfcase value="25"> <cfset quoteRow['isAnnual'][1] = "no" /> </cfcase> </cfswitch> Variables usage ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 27.  Don‟t use the pound sign where it is not needed <cfset newColor = #oldColor# /> <cfset newColor = "#oldColor#" />  But do instead: <cfset newColor = oldColor /> Variables usage ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 28. if (isBlue == false) { ... } Prefer: if (!isBlue) { ... } Logic ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 29. if (!isBlue) { doThis(); } else { doThat(); } Prefer avoiding “if not else”: if (isBlue) { doThat(); } else { doThis(); } Logic ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 30. if (isBlue) { return true; } else { return false; } Prefer: return isBlue; Logic ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 31.  Parenthesis: if (isBlue || isRed && isSquare) {...} if (isBlue || (isRed && isSquare)) {...} return variables.token == arguments.token; return (variables.token == arguments.token);  Order of variables if ("blue" == color) { //don‟t, use EQ? ... } Logic ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 32. if (token.equals("1234")) writeOutput("ok"); else writeOutput("ko"); Prefer: if (token.equals("1234")) { writeOutput("ok"); } else { writeOutput("ko"); } Always use brackets ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 33.  Exceptions allow you to focus on the useful code <cffunction name="login" access="public" returnType="boolean" output="false"> <cfargument name="username" type="string" required="yes" /> <cfargument name="hash" type="string" required="yes" /> <cfscript> try { var user = request.object.new("User").init(arguments.username); var hashServer = hash(session.token & user.getPassword(), "MD5"); if (hashServer == arguments.hash) { //connection success session.user = user; user.lastLogon(username); return true; } var debug = "username=#user.getUsername()#<br>password=#user.getPassword()#<br>"; } catch (objectNotExistsException e) { var debug = "user not exists exception (#arguments.username#/#arguments.hash#)"; } catch (connectionFailedException e) { var debug = e.message & "<br>" & e.detail; } </cfscript> <cfthrow type="loginFailedException” message="...” detail="#debug#" /> </cffunction> Exceptions ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 34.  Don‟t make entities dependent on each others <cfset colors = "blue,red,green,yellow" /> <cfloop from="1" to="10" index="i"> <cfinclude template="sometemplate.cfm"> </cfloop> <!--- sometemplate.cfm ---> <cfset i = 0> <cfloop list="#colors#" index="lst"> <cfset i++ /> ... </cfloop> Decoupling ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 35. Principle: no dynamic value into the condition of a loop for (i = 1 ; i <= arrayLen(items) ; i++) { ... } About readability ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 36. len = arrayLen(items); for (i = 1 ; i <= len ; i++) { ... } Improvement: 0% to 5% About readability ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 37. for (item in items) { // Railo and CF since 9.0.1 ... } Improvement: 10% to 15% About readability ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 38. A REAL WORLD EXAMPLE We learn more from our mistakes ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 39.  Control birth date:  60 days minimum  Must be right with the age entered (previous screen) Requirements ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 40. function isBirthDateValid(value,element) { var tmp = value.split("/"); if (tmp.length != 3) { return false; } else { var month = tmp[1]-1; var year = tmp[2]; var day = tmp[0]; if (isValidDate(month,day,year) != true) { return false; } else { return true; } } } Original code ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 41. function isBirthDateValid(value,element) { var tmp = value.split("/"); if (tmp.length == 3) { var month = tmp[1]-1; var year = tmp[2]; var day = tmp[0]; if (isValidDate(month,day,year) != true) { return false; } else { return true; } } return false; } Rewriting step 1 ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 42. function isBirthDateValid(value,element) { var tmp = value.split("/"); if (tmp.length == 3) { var month = tmp[1]-1; var year = tmp[0]; var day = tmp[2]; return isValidDate(month,day,year); } return false; } Rewriting step 2 ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 43. function isBirthDateValid(value, element) { var tmp = value.split("/"); if (tmp.length == 3) { var day = tmp[0]; var month = tmp[1] - 1; //month start at 0 var year = tmp[2]; return isValidDate(month, day, year); } return false; } Rewriting step 3 ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 44. function isBirthDateValid(value, element) { try { var birthDate = $.datepicker.parseDate('dd/mm/yy', value); if (birthDate.getAgeInDays() >= 60) { // we retrieve the current id from ”birthDate_X” // to check the age against "age_X" var id = element.id.split('_').pop(); if (birthDate.getAge() == $('#age_' + id).val()) { return true; } } } catch (e) {} return false; } Final code ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 45. Date.prototype.getAge = function() { var today = new Date(); var age = today.getFullYear() - this.getFullYear(); var monthes = today.getMonth() - this.getMonth(); var days = today.getDate() - this.getDate(); if (month < 0 || (monthes == 0 && days < 0)) { return age - 1; } else { return age; } }; Date.prototype.getAgeInDays = function() { var today = new Date(); return Math.floor((today - this) / 86400000); //ms to days (24*60*60*1000) }; Final code ©Aurélien Deleusière – CF Camp 2012 Monday October 15th 2012
  • 46.
  • 47. Thank you! Vielen Dank! Merci ! @adeleusiere • aurelien.deleusiere.fr • cfml-france.com