Clean Code Principles / How to write a clean code.

MaiAbuThraa 25 views 55 slides Sep 22, 2024
Slide 1
Slide 1 of 55
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55

About This Presentation

I have prepared this presentation to explain to students the importance and how to have clean code.


Slide Content

Mai Abuthraa { Software Developer @ DownHome Solutions Clean Code W orkshop About Me } ‹#›

‹#›

‹#›

‹#› Robert C. Martin

What is Clean Code? { } Clean Code Introduction Clean code is code that is easy to understand and easy to change. ‹#›

‹#›

Is ‘Craftsmanship’ { } Knowledge ○ Principles ○ Pattens ○ Practice ○ Heuristics الاستدلالات والاستكشافات solving problems our ability to identify a problem Work Programming Language Introduction ‹#› حرفة أو اجادة

Clean Code Introduction ‹#› 80s; شركة برمجيات، البداية كانت متفوقة لكن مع الوقت خسرت، وأي محاولة للإنقاذ كانت تكلف الشركة هل الكود كان عائق ؟ هل كنت بحاجة لفكرة أو تلميح لحل المشكلة؟ هل مدير الفريق مستعجل ,او إدارة الشركة مستعجلة؟ هل كان مدير الفريق يؤجل تحسين الكود؟

Clean Code Introduction ‹#› The Total Cost of Owning a Mess الفريق الذي يبدأ العمل بسرعة, مع الوقت ستقل إنتاجية , اي تعديل او اضافة على الكود هي عبارة عن عقدة متشابكة ,ويجب فهمها بشكل جيد, أو العقدة ستبقى تكبر الى لا يمكن إصلاحها

Clean Code Introduction ‹#› قرار المدراء: زيادة خدمات اكثر او المبيعات. مع عدم معرفتهم أو تجاهلهم للمشكلة الحقيقية . النتيجة: لا إنتاجية. ضغط على الفريق. دخول دائرة من المشاكل.

Clean Code Introduction ‹#› أو ت قرر الادارة: انشاء فريق جديد Tiger team افضل اعضاء الفريق في الشركة, لبدء المشروع من الصفر. محاولة لإنقاذ الشركة. و فريق قديم يحاول كسب الوقت, لإبقاء البرامج الحالية تعمل.

Clean Code Introduction ‹#› الحل الوحيد حسب رأي الكاتب , ان نحافظ على جودة الكود.

— Bjarne Stroutrnp inventor of C++ I like my code to be elegant and efficient. The logic should be straightforward and make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. Programming Language Quotes ‹#› انيق , فعال , وصريح , بسيط واضح = اكتشاف المشكلة بسرعة.

— Grady Booch author of Object-Oriented Analysis and Design with Applications: Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designers’ intent but rather is full of crisp abstractions and straightforward lines of control. Programming Language Quotes ‹#› بسيط و مباشر ويمكن قراءة ,كانك تقرأ مقال. يعني بتقرأ الكود وانت مبسوط

— “Big” Dave Thomas Founder of OTI and godfather of the Eclipse strategy Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since, depending on the language, not all necessary information can be expressed clearly in code alone. Programming Language Quotes ‹#› أي شخص غيرك كتب الكود ممكن يقرأ الكود بسهولة. Unit tests يكون شي أساسي في الكود.

— Michael Feathers author of Working Effectively with Legacy Code I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you are led back to where you are, sitting in appreciation of the code someone left for you—code written by someone who cared deeply about the craft. Programming Language Quotes ‹#›

Meaningful Names ‹#›

Clean Code Meaningful Names While writing the code, we name many things: -Classes -Models -Variable -Arguments -Functions ‹#› So, We have to do it the right way

— Uncle Bob's ‘author’ “The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists , what it does , and how it is used . If a name requires a comment, then the name does not reveal its intent. ” Clean Code Meaningful Names Quotes ‹#›

01 { [ Use Intention-Revealing Names ] < It is easy to say that names should reveal intent. What we want to impress upon you is that we are serious about this . Choosing good names takes time but saves more than it takes. So take care with your names > } Clean Code Meaningful Names ‹#› استخدم الأسماء التي تكشف النية\ صريحة

< /Good > < /Bad > Clean Code Meaningful Names Example ‹#› int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification; int fileAgeInDays; int d; // elapsed time in days int s; // elapsed time in seconds

02 { [ Avoid Disinformation ] Don’t use names that are already used as commands by the operating system. Don't use the Container type: Don't refer to a group of accounts as "accountList," whereas it is actually not a List. Instead, name it "accountGroup," " accounts ," or "bunchOfAccounts." Clean Code Meaningful Names ‹#› تجنب المعلومات المضللة

Clean Code Meaningful Names Example ‹#›

03 { [ Make Meaningful Distinctions ] < If there are two different things in the same scope, you might be tempted to change one name in an arbitrary way. > } Clean Code Meaningful Names ‹#› قم بعمل تمييزات ذات مغزى

Clean Code Meaningful Names Example ‹#› String custs ; String customers; class ProductInfo class ProductData What is stored in cust, which is different from customer? How are these classes different? How do you differentiate between these methods in the same class? void getActiveAccount() void getActiveAccounts() void getActiveAccountsInfo()

04 { [ Use Pronounceable Names ] < Ensure that names are pronounceable. Nobody wants a tongue twister. > } Clean Code Meaningful Names ‹#› استخدم الأسماء التي يمكن نطقها

<Good /> <Bad /> Clean Code Meaningful Names Example ‹#› Date genymdhms; Date modymdhms; Int pszqint; Date GenerationTimeStamp; Date modificationTimestamp; Int PublicAccessCount;

05 { [ Use Searchable Names ] Avoid single letter names and numeric constants , if they are not easy to locate across the body of the text. If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly name . } Clean Code Meaningful Names ‹#›

<Good /> <Bad /> Clean Code Meaningful Names Example ‹#› for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; } int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for ( int j = 0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realTaskDays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; } ممكن لانهم local variables

06 { [ Avoid Encodings ] } Clean Code Meaningful Names ‹#› < Hungarian Notation and other forms of type encoding are simply impediments today, because when we change the type , we also have to change the name. They make the code also so noisier that we cannot easily read the meaningful part of the code. And they confuses the reader. >

Avoid unnecessary encodings of datatypes along with the variable name. Clean Code Meaningful Names ‹#› String nameString; Float salaryFloat; with a new compiler no need to do it

06 { [ Avoid Mental Mapping ] } Clean Code Meaningful Names ‹#› لا تتفلسف < If scope of code is very small and no other names can conflict with it, loop counters can be named as i, j, k because they are familiar to programmers. >

Cont. 6 { [ Avoid Mental Mapping ] } Clean Code Meaningful Names ‹#› One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king

07 { [ Class Names ] } Clean Code Meaningful Names ‹#› < Classes and objects should have noun or noun phrase names and should obey Single Responsibility Principle . It is always better to avoid noise words . >

08 { [ Method Names​ ] } Clean Code Meaningful Names ‹#› < Methods should have verb or verb phrase names like postPayment , deletePage , or save. >

09 { [ Don’t Be Cute ​ ] } Clean Code Meaningful Names ‹#› < Using slang language or jokes in code just to show we are clever or just to have fun can hide the intention of author or even mislead readers and thus we should avoid . > ما تخفف دمك

10 { [ Pick One Word per Concept​ ​ ] } Clean Code Meaningful Names ‹#› < Avoiding the use of similar names for equivalent methods in codebase can make the code cleaner. For instance having fetch , retrieve , get for similar concepts or having controller , manager in the same codebase can be confusing for readers. >

11 { [ Don’t Pun ] } Clean Code Meaningful Names ‹#› < Sometimes when we try to follow the “one word per concept” rule, we might me tempted to use same names even though they don’t have really same semantics or concept. > تجنب الكلمات التي تحمل اكثر من معنى تورية Add append insert

12 { [ Use Solution Domain Names​ ] } Clean Code Meaningful Names ‹#› < Use computer science (CS) terms, algorithm names, pattern names , math terms , and so forth because readers and writers will most likely be developers and they won’t be familiar with problem domain names > jobQueue Demons home Builder

13 { [ Use P roblem Domain Names​ ] } Clean Code Meaningful Names ‹#› When there is no general solution domain name for what you're doing, use the name from the problem domain. Separating solution and problem domain concepts is part of the job of a good programmer. It is not good to always use a problem domain name because they may have to ask others what it means.

14 { [ Add Meaningful Context ] } Clean Code Meaningful Names ‹#› Names themselves mostly doesn’t give a meaning to us, thus contexts(can be well-named classes, functions or even prefixing the name) in names help us to understand better.

Clean Code Meaningful Names Example ‹#› firstName lastName Street houseNumber City State zipcod User firstName lastName State User firstName lastName address State User firstName lastName User userId Street houseNumber City State zipcod Address

Functions ‹#›

1 { Function arguments (2 or fewer ideally) } Clean Code Functions ‹#› One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated . Usually, if you have more than two arguments then your function is trying to do too much .

<Good /> <Bad /> Clean Code Functions Example ‹#› function createMenu(title, body, buttonText, cancellable) { // ... } createMenu("Foo", "Bar", "Baz", true); function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true });

2 { Functions should do one thing } Clean Code Functions ‹#› This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner.

<Good /> <Bad /> Clean Code Functions Example ‹#› function emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } }); }

<Good /> Clean Code Functions Example ‹#› function getActiveClients Emails (clients) { clients.filter(isActiveClient).forEach(email); } function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); }

3 { Function names should say what they do Clean Code Functions ‹#› <Bad /> function addToDate(date, month) { // ... } const date = new Date(); // It's hard to tell from the function name what is added addToDate(date, 1);

<Good /> Clean Code Functions Example ‹#› function addMonthToDate(month, date) { // ... } const date = new Date(); addMonthToDate(1, date);

4 { Set default objects Clean Code Functions ‹#› <Bad /> <Good />

5 { Don't use flags as function parameters } Clean Code Functions ‹#› Flags tell your user that this function does more than one thing . Functions should do one thing . Split out your functions if they are following different code paths based on a boolean

<Good /> <Bad /> Clean Code Functions Example ‹#› function createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); } } function createFile (name) { fs.create(name); } function createTempFile(name) { createFile (`./temp/${name}`); } t emp ? createTempFile(name) : createFile (name)

The References { Clean Code: A Handbook of Agile Software Craftsmanship . Refactoring.Guru . Naming Conventions From Uncle Bob's Clean Code Philosophy . Clean Code - Uncle Bob - all lessons Clean Code / Javascript Here are some references that helped me to prepare the presentation: Clean Code Workshop References } ‹#›

The References { What Is Clean Code 🔗 Naming Conventions / Part 1 . What Is Clean Code 🔗 Naming Conventions / Part 2 . Naming Classes - Why It Matters, and How to Do It Well . The Total Cost of Owning a Mess Meaningful Names in Ruby Code Here are some references that helped me to prepare the presentation: Clean Code Workshop References } ‹#›