A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
Presentación para la charla sobre el libro de Robert C. Martin, Clean Code.
Esta presentación la impartí en CyLicon Valley, aquí tenéis el video con el audio de la charla => https://www.youtube.com/watch?v=1Fss1jBfc3g
A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
Presentación para la charla sobre el libro de Robert C. Martin, Clean Code.
Esta presentación la impartí en CyLicon Valley, aquí tenéis el video con el audio de la charla => https://www.youtube.com/watch?v=1Fss1jBfc3g
Vladimir Romanov - How to write code that is easy to read and change? What should you do when you see a piece of code written years ago which is hard to understand? In my experience, this boils down to 4 principles that I would like to share along with some examples in Apex
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code. You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way.
You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained. This presentation is based on C# and Visual Studio 2012. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-18 Desert Code Camp - Chandler, AZ
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
Slides of the talk held at JEEConf, Kiev and jPrime, Sofia. A personal view on the classic topics from the Uncle Bob's Clean Code bible, with some personal additions and tips&tricks. This topic actually represents the core of the training sessions that I provide as an independent trainer (www.victorrentea.ro)
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
Talk built based on several of my trainings: http://www.victorrentea.ro/#training
Covers: Clean/Onion/Hexagonal Architecture, Domain Entities, Value Objects, Repository, Extract When it Grows Principle, Dependency Inversion Principle, Clean Code and Design Patterns.
These are the backing slides of the talks given at JPoint 2017 and Devoxx PL 2017: https://www.youtube.com/embed/4-4ahz7zDiQ
"Even bad code can function. But if code isn't clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn't have to be that way." In this knolx session, a few important topics for having clean code are covered. Basically the following topics - Meaningful name, Functions, Comments and Classes.
Over the last year there has been a lot of buzz about Clean Architecture in the Android community, but what is Clean Architecture? How does it work? And should I be using it? Recently at Badoo we decided to rewrite our messenger component.
Over the years this core piece of functionality in our app has become large and unwieldy. We wanted to take a fresh approach to try and prevent this from happening again. We choose to use Clean Architecture to achieve our goal. This talk intends to share our journey from theory to implementation in an application with over 100 million downloads. By the end, you should not only understand what Clean Architecture is, but how to implement it, and whether you should.
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
Clan code is extremely essential to build scalable application which can be maintained quite easily and improved further
Slide was prepared with contribution to my colleague
and i thank them for the help!
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
Slides of the Talk I gave at Devoxx Belgium 2019.
=== Abstract ===
Focusing on the creative work without being terrified of breaking the existing behavior can make software development very addictive! Good automated tests can buy you that!
However, if your tests are not maintainable they may end up slowing you down and causing you painful headaches, compilation errors and spurious failures. To avoid that, your unit tests should be significant; expressive; clean; DRY; non-overlapping; and blazing fast. Writing good tests becomes the toughest challenge for any developer, no matter how battle-hardened: you need to balance risk with test maintenance costs, while looking out for test design smells that call for [risky] refactoring to drive your design towards a set of key principles (included:).
Principles that will end up shaping the way you craft the Production code itself. Because in the end, a good, clean design is more important than coverage%.
But testing gives you the best feedback to get there.
Grab a black coffee and join this snippet from Victor’s Pro Unit Testing #training, to learn about testing priorities, buggy tests, the shared @Before, Mocks vs Stubs and how to reduce them by "purifying" your logic, testing Legacy Code and refactoring @Spy-es out.
All of that in an entertaining, dynamic and memorable session.
Vladimir Romanov - How to write code that is easy to read and change? What should you do when you see a piece of code written years ago which is hard to understand? In my experience, this boils down to 4 principles that I would like to share along with some examples in Apex
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code. You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way.
You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained. This presentation is based on C# and Visual Studio 2012. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-18 Desert Code Camp - Chandler, AZ
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
Slides of the talk held at JEEConf, Kiev and jPrime, Sofia. A personal view on the classic topics from the Uncle Bob's Clean Code bible, with some personal additions and tips&tricks. This topic actually represents the core of the training sessions that I provide as an independent trainer (www.victorrentea.ro)
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
Talk built based on several of my trainings: http://www.victorrentea.ro/#training
Covers: Clean/Onion/Hexagonal Architecture, Domain Entities, Value Objects, Repository, Extract When it Grows Principle, Dependency Inversion Principle, Clean Code and Design Patterns.
These are the backing slides of the talks given at JPoint 2017 and Devoxx PL 2017: https://www.youtube.com/embed/4-4ahz7zDiQ
"Even bad code can function. But if code isn't clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn't have to be that way." In this knolx session, a few important topics for having clean code are covered. Basically the following topics - Meaningful name, Functions, Comments and Classes.
Over the last year there has been a lot of buzz about Clean Architecture in the Android community, but what is Clean Architecture? How does it work? And should I be using it? Recently at Badoo we decided to rewrite our messenger component.
Over the years this core piece of functionality in our app has become large and unwieldy. We wanted to take a fresh approach to try and prevent this from happening again. We choose to use Clean Architecture to achieve our goal. This talk intends to share our journey from theory to implementation in an application with over 100 million downloads. By the end, you should not only understand what Clean Architecture is, but how to implement it, and whether you should.
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
Clan code is extremely essential to build scalable application which can be maintained quite easily and improved further
Slide was prepared with contribution to my colleague
and i thank them for the help!
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
Slides of the Talk I gave at Devoxx Belgium 2019.
=== Abstract ===
Focusing on the creative work without being terrified of breaking the existing behavior can make software development very addictive! Good automated tests can buy you that!
However, if your tests are not maintainable they may end up slowing you down and causing you painful headaches, compilation errors and spurious failures. To avoid that, your unit tests should be significant; expressive; clean; DRY; non-overlapping; and blazing fast. Writing good tests becomes the toughest challenge for any developer, no matter how battle-hardened: you need to balance risk with test maintenance costs, while looking out for test design smells that call for [risky] refactoring to drive your design towards a set of key principles (included:).
Principles that will end up shaping the way you craft the Production code itself. Because in the end, a good, clean design is more important than coverage%.
But testing gives you the best feedback to get there.
Grab a black coffee and join this snippet from Victor’s Pro Unit Testing #training, to learn about testing priorities, buggy tests, the shared @Before, Mocks vs Stubs and how to reduce them by "purifying" your logic, testing Legacy Code and refactoring @Spy-es out.
All of that in an entertaining, dynamic and memorable session.
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
Errata:
slide 10: "points asserts" should be "asserts"
slide 22,23,25: "// larger than that root.private static int" should be "// larger than that root"
slide 29: "three slides" should be "two slides"
slide 45,46,48,49: List.range(m,n + 1) should be List.range(2,maxValue + 1)
The Sieve of Eratosthenes - Part 1 - with minor correctionsPhilip Schwarz
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
This version of the deck contains some minor corrections (see errata section in first version for details)
Writing Clean Code (Recommendations by Robert Martin)Shirish Bari
Writing clean code is every developers responsibility.
I have studied book " Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C Martin. Based on my understanding about book I have listed down recommendations for writing down clean code.These can be good starting point while learning to write clean code
Why I use C# lambdas all the time and for everything and so should you.
A presentation on how to use functional programming techniques effectively in C#
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
3. Meaningful Names
• Avoid Mental Mapping
A single-letter name is a poor choice; it’s just a place holder that the reader
must mentally map to the actual concept. There can be no worse reason for
using the name “c” than because “a” and “b” were already taken.
• Method names
Methods should have verb or verb phrase names like postPayment,
deletePage, or save. Accessors, mutators, and predicates should be named
for their value and prefixed with get…, set…, and is…
4. Meaningful Names
• Use Searchable Names
const int WORK_DAYS_PER_WEEK = 5;
int realDaysPerIdealDay = 4;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[ j ] * realDaysPerIdealDay;
int realTaskWeeks = (realDays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
for (int j = 0; j < 34; j++) {
s += (t [ j ] * 4) / 5;
}
Single-letter names can ONLY be
used as local variables inside short
methods.
The length of a name should
correspond to the size of its scope
5. Meaningful Names
• Use Intention-Revealing Names
If a name requires a comment, then the name does not reveal its intent.
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<>();
for (int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
public List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<>();
for (Cell cell : gameBoard)
if (cell.isFlagged())
flaggedCells.add(cell);
return flaggedCells;
}
6. Meaningful Names
• Use Pronounceable Names
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = "102";
}
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
}
If you can’t pronounce it, you can’t
discuss it without sounding like an idiot.
8. Meaningful Names
• Class Names
Customer, WikiPage, Account,
AddressParser.
Classes and objects should have noun or
noun phrase names and not include
indistinct noise words:
Manager, Processor, Data, Info.
9. Functions
• Small!
The first rule of functions is that they should be small.
Functions should hardly ever be ??? lines long.
Blocks within if statements, else statements, while statements, and so on
should be ??? long.
10. Functions
• Small!
The first rule of functions is that they should be small.
Functions should hardly ever be 20 lines long.
Blocks within if statements, else statements, while statements, and so on
should be one line long. Probably that line should be a function call.
• Do One Thing
To know that a function is doing more than “one thing” is if you can extract
another function from it with a name that is not merely a restatement of its
implementation.
11. Functions
• One Level of Abstraction per Function
We want the code to read like a top-down narrative.
We want every function to be followed by those at the next level of abstraction
so that we can read the program, descending one level of abstraction at a time
as we read down the list of functions.
public String render() throws Exception {
StringBuffer html = new StringBuffer(“<hr");
if(size > 0)
html.append(" size="")
.append(size + 1).append(“”");
html.append(">");
return html.toString();
}
public String render() throws Exception {
HtmlTag hr = new HtmlTag(“hr");
if (extraDashes > 0)
hr.addAttribute(“size", hrSize(extraDashes));
return hr.html();
}
private String hrSize(int height) {
int hrSize = height + 1;
return String.format("%d", hrSize);
}
12. Functions
• Use Descriptive Names
Don’t be afraid to make a name long. A long descriptive name is better than
a short enigmatic name. A long descriptive name is better than a long
descriptive comment.
• Dependent Functions.
If one function calls another, they should be vertically close, and the caller
should be above the callee, if at all possible.
14. Functions
• Function Arguments
The ideal number of arguments for
a function is zero (niladic). Next
comes one (monadic), followed
closely by two (dyadic). Three
arguments (triadic) should be
avoided where possible.
includeSetupPage()
includeSetupPageInto(newPageContent)
15. Functions
• Flag Arguments
Flag arguments are ugly. Passing a
boolean into a function is a truly
terrible practice. It immediately
complicates the signature of the
method, loudly proclaiming that this
function does more than one thing. It
does one thing if the flag is true and
another if the flag is false!
render(boolean isSuite)
renderForSuite()
renderForSingleTest()
16. Functions
• Have No Side Effects
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
17. Functions
• Have No Side Effects
Side effects are lies.
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
checkPasswordAndInitializeSession
18. Functions
• Output Arguments
For example:
appendFooter(s);
Does this function append “s” as the
footer to something? Or does it
append some footer to “s”? Is “s” an
input or an output? It doesn’t take
long to look at the function
signature and see, but anything that
forces you to check the function
signature is equivalent to a double-
take. It’s a cognitive break and
should be avoided.
public void appendFooter(StringBuffer report)
report.appendFooter();
19. Comments
// Check to see if the employee is eligible
// for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
or
20. Comments
• Explain Yourself in Code
Only the code can truly tell you
what it does.
Comments are, at best, a
necessary evil.
Rather than spend your time writing
the comments that explain the
mess you’ve made, spend it
cleaning that mess.
Inaccurate comments are far worse
than no comments at all.
if (employee.isEligibleForFullBenefits())
// Check to see if the employee is eligible
// for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
21. Comments
• Legal Comments
Sometimes our corporate
coding standards force us to
write certain comments for
legal reasons.
// Copyright (C) 2003,2004,2005 by Object
// Mentor, Inc. All rights reserved.
// Released under the terms of the GNU
// General Public License version 2 or later.
• Explanation of Intent
Sometimes a comment goes
beyond just useful information
about the implementation and
provides the intent behind a
decision.
// This is our best attempt to get a race condition
// by creating large number of threads.
for (int i = 0; i < 25000; i++) {
WidgetBuilderThread widgetBuilderThread =
new WidgetBuilderThread(widgetBuilder, text, parent, failFlag);
Thread thread = new Thread(widgetBuilderThread);
thread.start();
}
22. Comments
• Warning of Consequences
Sometimes it is useful to warn
other programmers about
certain consequences.
public static SimpleDateFormat makeStandardHttpDateFormat() {
//SimpleDateFormat is not thread safe,
//so we need to create each instance independently.
SimpleDateFormat df =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
• TODO Comments
Nowadays, most good IDEs
provide special gestures and
features to locate all the //TODO
comments, so it’s not likely that
they will get lost.
//TODO-MdM these are not needed
// We expect this to go away when we do the
// checkout model
protected VersionInfo makeVersion() throws Exception{
return null;
}
23. Comments
• Amplification
A comment may be used to
amplify the importance of
something that may otherwise
seem inconsequential.
String listItemContent = match.group(3).trim();
// the trim is real important. It removes the starting
// spaces that could cause the item to be recognised
// as another list.
new ListItemWidget(this, listItemContent, this.level + 1);
return buildList(text.substring(match.end()));
• Public APIs
There is nothing quite so helpful
and satisfying as a well-
described public API. It would
be difficult, at best, to write
programs without them.
/// dart doc comment
/**
* JavaDoc comment
*/
24. Comments
• Commented-Out Code
We’ve had good source code
control systems for a very long
time now. Those systems will
remember the code for us. We
don’t have to comment it out any
more. Just delete the code.
• Position Markers
In general they are clutter that
should be eliminated—
especially the noisy train of
slashes at the end. If you
overuse banners, they’ll fall into
the background noise and be
ignored.
// Actions //////////////////////////////////
InputStreamResponse response = new InputStreamResponse();
response.setBody(formatter.getResultStream(),
formatter.getByteCount());
// InputStream resultsStream = formatter.getResultStream();
// StreamReader reader = new StreamReader(resultsStream);
// response.setContent(reader.read(formatter.getByteCount()));
25. Error Handling
• Don’t Return Null
When we return null, we are
essentially creating work for
ourselves and foisting problems
upon our callers. All it takes is one
missing null check to send an
application spinning out of control.
List<Employee> employees = getEmployees();
if (employees != null) {
for (Employee e : employees) {
totalPay += e.getPay();
}
}
public List<Employee> getEmployees() {
if ( .. there are no employees .. )
return Collections.emptyList();
}
26. Error Handling
• Don’t Pass Null
In most programming languages
there is no way to deal with
a null that is passed by a caller
accidentally. Because this is the
case, the rational approach is to
forbid passing null by default. When
you do, you can code with the
knowledge that a null in an
argument list is an indication of a
problem, and end up with far fewer
careless mistakes.
calculator.xProjection(null, new Point(12, 13));
27. Classes
• Classes Should Be Small!
With functions we measured size by counting physical lines. With classes we use a
different measure. We count ???.
28. Classes
• Classes Should Be Small!
With functions we measured size by counting physical lines. With classes we use a
different measure. We count responsibilities.
The Single Responsibility Principle (SRP) states that a class or module should have
one, and only one, reason to change.
The name of a class should describe what responsibilities it fulfills. The more
ambiguous the class name, the more likely it has too many responsibilities.
The problem is that too many of us think that we are done once the program works.
We move on to the next problem rather than going back and breaking the
overstuffed classes into decoupled units with single responsibilities.
29. Classes
public class SuperDashboard extends JFrame implements MetaDataUser
public String getCustomizerLanguagePath()
public void setSystemConfigPath(String systemConfigPath)
public String getSystemConfigDocument()
public void setSystemConfigDocument(String systemConfigDocument)
public boolean getGuruState()
public boolean getNoviceState()
public boolean getOpenSourceState()
public void showObject(MetaObject object)
public void showProgress(String s)
public void setACowDragging(boolean allowDragging)
public boolean allowDragging()
public boolean isCustomizing()
public void setTitle(String title)
public IdeMenuBar getIdeMenuBar()
public void showHelper(MetaObject metaObject, String propertyName)
// ... many non-public methods follow ...
}
public class Version {
public int getMajorVersionNumber()
public int getMinorVersionNumber()
public int getBuildNumber()
}
30. Environment
• Build Requires More Than One Step
Building a project should be a single
trivial operation. You should not have to
check many little pieces out from source
code control. You should be able to
check out the system with one simple
command and then issue one other
simple command to build it.
svn get mySystem
cd mySystem
ant all
• Tests Require More Than One Step
You should be able to run all the unit tests with just one command. In the best
case you can run all the tests by clicking on one button in your IDE.
31. General
• Artificial Coupling
In general an artificial coupling is a coupling between two modules that serves no
direct purpose. It is a result of putting a variable, constant, or function in a temporarily
convenient, though inappropriate, location.
For example, general enumsshould not be contained within more specific classes
because this forces the whole application to know about these more specific classes.
The same goes for general purpose static functions being declared in specific
classes.
• Prefer Polymorphism to If/Else or Switch/Case
There may be no more than one switch statement for a given type of selection. The
cases in that switch statement must create polymorphic objects that take the place of
other such switch statements in the rest of the system.
32. General
• Replace Magic Numbers with Named Constants
In general it is a bad idea to have raw numbers in your code. You should hide them
behind well-named constants. The term “Magic Number” does not apply only to
numbers. It applies to any token that has a value that is not self-describing.
assertEquals(7777, Employee.find(“John Doe”).employeeNumber());
assertEquals(
HOURLY_EMPLOYEE_ID,
Employee.find(HOURLY_EMPLOYEE_NAME).employeeNumber());
33. General
• Encapsulate
Conditionals
Boolean logic is hard enough to
understand without having to
see it in the context of an if or
while statement. Extract
functions that explain the intent
of the conditional.
if (shouldBeDeleted(timer))
if (timer.hasExpired() &&
!timer.isRecurrent())
• Avoid Negative
Conditionals
Negatives are just a bit harder to
understand than positives. So,
when possible, conditionals
should be expressed as
positives.
if (buffer.shouldCompact())
if (!buffer.shouldNotCompact())
34. General
• Encapsulate Boundary Conditions
Boundary conditions are hard to keep track of. Put the processing for them in one
place.
if (level + 1 < tags.length) {
parts = new Parse(body, tags, level + 1, offset + endTag);
body = null;
}
int nextLevel = level + 1;
if (nextLevel < tags.length) {
parts = new Parse(body, tags, nextLevel, offset + endTag);
body = null;
}
35. General
• Constants versus Enums
Don’t keep using the old trick of public static final ints. Enums can
have methods and fields. This makes them very powerful tools that allow much
more expression and flexibility.
public enum HourlyPayGrade {
APPRENTICE {
public double rate() {
return 1.0;
}
},
MASTER {
public double rate() {
return 2.0;
}
};
public abstract double rate();
}
public class HourlyEmployee extends Employee {
private int tenthsWorked;
HourlyPayGrade grade;
public Money calculatePay() {
int straightTime = Math.min(tenthsWorked, TENTHS_PER_WEEK);
int overTime = tenthsWorked - straightTime;
return new Money(
grade.rate() * (tenthsWorked + OVERTIME_RATE * overTime)
);
}
/…
}