SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Writing Good Code
<lecturer> Leo Liang </lecturer>
      <date> 2009-7 </date>
We are …
                      Elegant Code




       Programmer

           Designer
Principles

 Your code should

   –   be simple and clean
   –   be readable and maintainable
   –   be testable
   –   be secure
   –   be extensible
Rule #1




          get the job done
Readable
                                                             白色马驹
                                                             浮出雾中
 Beautiful code is like poem                                转瞬不见
                                                             回到雾里

                                                             秋日午后
    –   Good code style                                      无花果树叶
    –   Meaningful naming                                    轻轻落下
    –   Short method                                         停在
                                                             自己的影子上
    –   Appropriate class size
                                                                --- 阿巴斯

 Unreadable code is unmaintainable

         How To Write Unmaintainable Code?
        http://freeworld.thc.org/root/phun/unmaintain.html
Simple & Clean

 Choose the simplest way that could
  possibly work

 Don’t repeat yourself
    – Reuse

 High cohesion, low coupling
    – Design with contracts
    – Orthogonal ( 正交 )
Robust

 Robustness means two things:

   – getting the job done

   – continuing to get the job done as much as
     possible even when things go bad
Performance vs. Style

 Code style is more important than code performance
     – Consider readability and maintainability

                                                     Clever Code
 Performance is very important

 How the design is affects performance much more
  than how to code
     – Performance is depends on a lot of factors
     – Design correctly
     – Identify the performance bottleneck by test or tool
Don’t live with BAD code



         Refactoring
Principles

 Your code should
   –   get the job done
   –   be simple and clean
   –   be readable and maintainable
   –   be testable
   –   be secure
   –   be extensible
Coding Guidelines
Why need code convention

 Improve the readability
 Create maintainable code
 Eliminate potential bugs
     – Bug pattern
     – Best practices
 ClearCase merge



 No absolutely good or bad
 Need unify convention in a team
Programming Style Guidelines

 Every product line has its own guidelines defined
     – SIG / ISP / MSDP / MIEP / AOP


 General guidelines
     – Java Guidelines from Geotechnical Software Services (
       http://geosoft.no/development/javastyle.html)
     – Excepts: 8 / 20 / 34 / 61 / 63 / 64

                                             Take 20 minutes
                                            to go throw them!
Naming Convention

 Camel case
     – Types: nouns
     – Methods: verbs

     TrafficProfile trafficProfile = createTrafficProfile();


 Constants: all uppercase using underscore to separate
  words
      setStatus( SERVICE_NOT_ACTIVE );
Comment                                 Delete the unused code
                                        instead of comment out
 JavaDoc
     – Classes, public methods
 Comment on
     – where the code isn’t easy to understand
     – where the code differs to conventions
 Unfinished task
     – // TODO: description
 Know issue
     – // FIXME: description
No warning

 Target: No warning
     – Everyone has the responsibility to fix the warnings
     – Should check at code review


 Suppress warning (Be careful!)
     – Java:
       Annotate with @SuppressWarning
     – CheckStyle:
       Suppress audit events between a comment containing
       CHECKSTYLE:OFF and a comment containing
       CHECKSTYLE:ON
     – FindBugs:
       Edit the findbugs_exclude.xml
Sample

 Find code style issues from the sample code




          sample.java
Eclipse Usage

 Eclipse built-in code style formatter
     – Menu: Source – Format
     – Keyboard: Ctrl-Shift-F


 Rename an identifier is very easy in Eclipse
     – Menu: Refactor - Rename
     – Keyboard: Alt-Shift-R
Code Check-in Rule

 Before check-in your code, you must ensure
     – Code compiled successful
     – Basic test passed

 Check-in frequency
     – As soon as possible
     – No longer than 1 day

 Do not leave the file locked when you are not editing it

 Write meaningful comment at check-in


  Ensure the code in ClearCase is always valid
Quick Reference
Quick Reference – Naming Example

AudioSystem audioSystem; // NOT: audio_system
openDvdPlayer();              // NOT: openDVDPlayer();
getServiceCapability();       // NOT: getSc();
MAX_ITERATIONS = 25;
void setTopic(Topic topic) // NOT: void setTopic(Topic value)
                             // NOT: void setTopic(Topic aTopic)
                             // NOT: void setTopic(Topic t)
Collection<Point> points; // NOT: point
line.getLength();         // NOT: line.getLineLength();
Quick Reference – Naming Example

void setFound(boolean isFound);
  // NOT: setIsFound(boolean isFound)
  // NOT: setFound(boolean found)
boolean hasLicense, canEvaluate, shouldAbort;

get/set, add/remove, create/destroy, start/stop, insert/delete,
   increment/decrement, old/new, begin/end, first/last, up/down,
   min/max, next/previous, old/new, open/close, show/hide,
   suspend/resume

xxxFactory, xxxProxy, xxxFacade, xxxCommand
xxxExecption, xxxImpl, DefaultXxx, AbstractXxx
Quick Reference - Comment

 Comment as reminder
    // TODO: ……
    // FIXME: ……
 Suppress warning
    – Java / FindBugs / PMD
         @SuppressWarning
    – checkstyle
         // CHECKSTYLE:OFF
         Some codes …
         // CHECKSTYLE:ON
Quick Reference - Eclipse

 Format code style
     – Source - Format (Ctrl-Shift-F)
 Organize imports
     – Source - Organize imports (Ctrl-Shift-O)
 Rename identify
     – Refactor - Rename (Alt-Shift-R)
 Code clean up
     – Source - Clean up…
 Error correct suggestion
     – Edit - Quick Fix (Ctrl-1)


 More functions in Source and Refactor menu …
Writing Good Code

Weitere ähnliche Inhalte

Ähnlich wie Writing Good Code

Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applicationsChandra Sekhar Saripaka
 
Code Review Looking for a vulnerable code. Vlad Savitsky.
Code Review Looking for a vulnerable code. Vlad Savitsky.Code Review Looking for a vulnerable code. Vlad Savitsky.
Code Review Looking for a vulnerable code. Vlad Savitsky.DrupalCampDN
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Visual studio2012 tipsandtricks
Visual studio2012 tipsandtricksVisual studio2012 tipsandtricks
Visual studio2012 tipsandtricksTung Nguyen Thanh
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NETDror Helper
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityGleicon Moraes
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEAN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEGavin Pickin
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017Ortus Solutions, Corp
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerBen McGraw
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Object Pascal Clean Code Guidelines Proposal (at EKON 22)
Object Pascal Clean Code Guidelines Proposal (at EKON 22)Object Pascal Clean Code Guidelines Proposal (at EKON 22)
Object Pascal Clean Code Guidelines Proposal (at EKON 22)Arnaud Bouchez
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 

Ähnlich wie Writing Good Code (20)

Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
 
Code Review Looking for a vulnerable code. Vlad Savitsky.
Code Review Looking for a vulnerable code. Vlad Savitsky.Code Review Looking for a vulnerable code. Vlad Savitsky.
Code Review Looking for a vulnerable code. Vlad Savitsky.
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
9-Coding.ppt
9-Coding.ppt9-Coding.ppt
9-Coding.ppt
 
Visual studio2012 tipsandtricks
Visual studio2012 tipsandtricksVisual studio2012 tipsandtricks
Visual studio2012 tipsandtricks
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
7-CodingAndUT.ppt
7-CodingAndUT.ppt7-CodingAndUT.ppt
7-CodingAndUT.ppt
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs Scalability
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEAN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle Hammer
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Object Pascal Clean Code Guidelines Proposal (at EKON 22)
Object Pascal Clean Code Guidelines Proposal (at EKON 22)Object Pascal Clean Code Guidelines Proposal (at EKON 22)
Object Pascal Clean Code Guidelines Proposal (at EKON 22)
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Code Quality
Code QualityCode Quality
Code Quality
 

Kürzlich hochgeladen

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Kürzlich hochgeladen (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Writing Good Code

  • 1. Writing Good Code <lecturer> Leo Liang </lecturer> <date> 2009-7 </date>
  • 2. We are … Elegant Code Programmer Designer
  • 3. Principles  Your code should – be simple and clean – be readable and maintainable – be testable – be secure – be extensible
  • 4. Rule #1 get the job done
  • 5. Readable 白色马驹 浮出雾中  Beautiful code is like poem 转瞬不见 回到雾里 秋日午后 – Good code style 无花果树叶 – Meaningful naming 轻轻落下 – Short method 停在 自己的影子上 – Appropriate class size --- 阿巴斯  Unreadable code is unmaintainable How To Write Unmaintainable Code? http://freeworld.thc.org/root/phun/unmaintain.html
  • 6. Simple & Clean  Choose the simplest way that could possibly work  Don’t repeat yourself – Reuse  High cohesion, low coupling – Design with contracts – Orthogonal ( 正交 )
  • 7. Robust  Robustness means two things: – getting the job done – continuing to get the job done as much as possible even when things go bad
  • 8. Performance vs. Style  Code style is more important than code performance – Consider readability and maintainability Clever Code  Performance is very important  How the design is affects performance much more than how to code – Performance is depends on a lot of factors – Design correctly – Identify the performance bottleneck by test or tool
  • 9. Don’t live with BAD code Refactoring
  • 10. Principles  Your code should – get the job done – be simple and clean – be readable and maintainable – be testable – be secure – be extensible
  • 12. Why need code convention  Improve the readability  Create maintainable code  Eliminate potential bugs – Bug pattern – Best practices  ClearCase merge  No absolutely good or bad  Need unify convention in a team
  • 13. Programming Style Guidelines  Every product line has its own guidelines defined – SIG / ISP / MSDP / MIEP / AOP  General guidelines – Java Guidelines from Geotechnical Software Services ( http://geosoft.no/development/javastyle.html) – Excepts: 8 / 20 / 34 / 61 / 63 / 64 Take 20 minutes to go throw them!
  • 14. Naming Convention  Camel case – Types: nouns – Methods: verbs TrafficProfile trafficProfile = createTrafficProfile();  Constants: all uppercase using underscore to separate words setStatus( SERVICE_NOT_ACTIVE );
  • 15. Comment Delete the unused code instead of comment out  JavaDoc – Classes, public methods  Comment on – where the code isn’t easy to understand – where the code differs to conventions  Unfinished task – // TODO: description  Know issue – // FIXME: description
  • 16. No warning  Target: No warning – Everyone has the responsibility to fix the warnings – Should check at code review  Suppress warning (Be careful!) – Java: Annotate with @SuppressWarning – CheckStyle: Suppress audit events between a comment containing CHECKSTYLE:OFF and a comment containing CHECKSTYLE:ON – FindBugs: Edit the findbugs_exclude.xml
  • 17. Sample  Find code style issues from the sample code sample.java
  • 18. Eclipse Usage  Eclipse built-in code style formatter – Menu: Source – Format – Keyboard: Ctrl-Shift-F  Rename an identifier is very easy in Eclipse – Menu: Refactor - Rename – Keyboard: Alt-Shift-R
  • 19. Code Check-in Rule  Before check-in your code, you must ensure – Code compiled successful – Basic test passed  Check-in frequency – As soon as possible – No longer than 1 day  Do not leave the file locked when you are not editing it  Write meaningful comment at check-in Ensure the code in ClearCase is always valid
  • 21. Quick Reference – Naming Example AudioSystem audioSystem; // NOT: audio_system openDvdPlayer(); // NOT: openDVDPlayer(); getServiceCapability(); // NOT: getSc(); MAX_ITERATIONS = 25; void setTopic(Topic topic) // NOT: void setTopic(Topic value) // NOT: void setTopic(Topic aTopic) // NOT: void setTopic(Topic t) Collection<Point> points; // NOT: point line.getLength(); // NOT: line.getLineLength();
  • 22. Quick Reference – Naming Example void setFound(boolean isFound); // NOT: setIsFound(boolean isFound) // NOT: setFound(boolean found) boolean hasLicense, canEvaluate, shouldAbort; get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume xxxFactory, xxxProxy, xxxFacade, xxxCommand xxxExecption, xxxImpl, DefaultXxx, AbstractXxx
  • 23. Quick Reference - Comment  Comment as reminder // TODO: …… // FIXME: ……  Suppress warning – Java / FindBugs / PMD @SuppressWarning – checkstyle // CHECKSTYLE:OFF Some codes … // CHECKSTYLE:ON
  • 24. Quick Reference - Eclipse  Format code style – Source - Format (Ctrl-Shift-F)  Organize imports – Source - Organize imports (Ctrl-Shift-O)  Rename identify – Refactor - Rename (Alt-Shift-R)  Code clean up – Source - Clean up…  Error correct suggestion – Edit - Quick Fix (Ctrl-1)  More functions in Source and Refactor menu …

Hinweis der Redaktion

  1. Designer &amp; programmer 产品 vs. 艺术品
  2. Short method: 反例: handleRequest(), loop, switch, if …
  3. 高内聚,低耦合:模块 /package/class/ 方法,接口
  4. 电信系统的可靠性要求: n 个 9 ( 4 个 9 , 5 个 9 )
  5. i++, ++i
  6. 破窗理论 你写的代码,将会成为别人的例子 时间估算:影响大的重构要与 team 商量;测试
  7. 务虚 / 务实 审美观
  8. Mix case Names representing types must be nouns Names representing methods must be verbs Abbreviations and acronyms should not be uppercase Constants (final variables) must be all uppercase using underscore to separate words
  9. Specific Naming Conventions is / has / can /should set / get … Name as the design patterns