SlideShare ist ein Scribd-Unternehmen logo
1 von 73
Качествен  програмен код Светлин Наков Национална академия по разработка на софтуер www.devbg.org
Лекторът Светлин Наков ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Съдържание ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Какво е качествен програмен код?
Какво е качествен код? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Какво е качествен код? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Какво е качествен софтуерен дизайн?
Софтуерен дизайн ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Какво е софтуерен дизайн ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Характеристики на дизайна ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Процесът на дизайн ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Фази на дизайна ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Фази на дизайна ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Фази на дизайна ,[object Object],[object Object],[object Object],[object Object]
Силата на диаграмите Извикване на уеб услуга Изпълнение на SQL заявка Резултат от SQL заявка XML DataSet Променени данни във вид на XML DataSet Заявки за нанасяне на промените Клиент Web-услуга База данни
Качествен програмен код Какво са качествените подпрограми (методи)?
Защо да използваме методи? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Свързаност на отговорностите ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Допустими видове кохезия ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Допустими видове кохезия ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Недопустими видове кохезия ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Имената на методите ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Имената на методите ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Колко да са дълги методите? ,[object Object],[object Object],[object Object],[object Object],[object Object]
Параметрите на методите ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Параметрите на методите ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Функция или процедура ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Какво е защитно програмиране?
Защитно програмиране ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Проверки ( assertions) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Проверки ( assertions) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Assertions –  препоръки ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Изключения ( exceptions ) ,[object Object],[object Object],[object Object],[object Object],[object Object]
Изключения – препоръки ,[object Object],[object Object],[object Object],[object Object],[object Object]
Изключения – препоръки ,[object Object],[object Object],[object Object],[object Object],[object Object]
Изключения – препоръки ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Колко защитно програмиране да оставим в  Release  версията ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Как да използваме променливите?
Принципи при инициализиране ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],Принципи при инициализиране
[object Object],[object Object],[object Object],[object Object],[object Object],Принципи при инициализиране
Обхват, живот, активност ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Работа с променливи ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Почивка!
Качествен програмен код Как да именуваме променливите?
Именуване на променливи ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Именуване на променливи ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Именуване на специфични типове данни ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Именуване на специфични типове данни ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Кога е необходима конвенция за именуване ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Стандартни префикси ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Стандартни префикси ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Стандартни префикси ,[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Какво е преработка на кода ( Refactoring )?
Митове и реалност за процеса за разработка на софтуер ,[object Object],[object Object],[object Object]
Митове и реалност за процеса за разработка на софтуер ,[object Object],[object Object],[object Object],[object Object],[object Object]
Преработка на кода ( Refactoring) ,[object Object],[object Object],[object Object],[object Object]
Преработка на кода ( Refactoring) ,[object Object],[object Object],[object Object],[object Object]
Кога даден код се нуждае от преработка ? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Кога даден код се нуждае от преработка ? (продължение) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Преработка на код на ниво данни ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Преработка на кода на ниво метод ,[object Object],[object Object],[object Object],[object Object],[object Object]
Преработка на кода на ниво клас ,[object Object],[object Object],[object Object],[object Object],[object Object]
Преработка на кода на ниво система ,[object Object],[object Object],[object Object],[object Object],[object Object]
Качествен програмен код Какво е самодокументиращ се код и как се реализира?
Стилът на програмиране и документацията ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Характеристики на самодокументиращия се код ,[object Object],[object Object],[object Object],[object Object],[object Object]
Самодокументиращ се код – важни въпроси ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Самодокументиращ се код – важни въпроси (продължение) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
“ Ефективни” коментари  ,[object Object],[object Object],[object Object],[object Object]
Правила на “ефективните” коментари ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ресурси по темата ,[object Object],[object Object]
Качествен програмен код ,[object Object]

Weitere ähnliche Inhalte

Ähnlich wie High Quality Code Introduction

Continuous integration (d.atanasov)
Continuous integration (d.atanasov)Continuous integration (d.atanasov)
Continuous integration (d.atanasov)Deyan Atanasov
 
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)DAVID Academy
 
Курс по уеб програмиране (2015), занятие №1 - HTML
Курс по уеб програмиране (2015), занятие №1 - HTMLКурс по уеб програмиране (2015), занятие №1 - HTML
Курс по уеб програмиране (2015), занятие №1 - HTMLDAVID Academy
 
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)DAVID Academy
 
Managing Construction
Managing ConstructionManaging Construction
Managing Constructioncveta
 
FABRIQ - Short - Svetlin Nakov
FABRIQ - Short - Svetlin NakovFABRIQ - Short - Svetlin Nakov
FABRIQ - Short - Svetlin NakovSvetlin Nakov
 
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...Средства на VSTS за управление на проекти, версии на системата, извеждане на ...
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...Yosifov
 
FABRIQ - Presentation Nakov 0.8
FABRIQ - Presentation Nakov 0.8FABRIQ - Presentation Nakov 0.8
FABRIQ - Presentation Nakov 0.8Svetlin Nakov
 
Svetlin Nakov - E-Business And NASD Academy
Svetlin Nakov - E-Business And NASD AcademySvetlin Nakov - E-Business And NASD Academy
Svetlin Nakov - E-Business And NASD AcademySvetlin Nakov
 
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows Forms
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows FormsКурс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows Forms
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows FormsDAVID Academy
 
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQL
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQLКурс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQL
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQLDAVID Academy
 
Svetlin Nakov - .NET Framework Overview
Svetlin Nakov - .NET Framework OverviewSvetlin Nakov - .NET Framework Overview
Svetlin Nakov - .NET Framework OverviewSvetlin Nakov
 
Nakov - .NET Framework Overview + Security
Nakov - .NET Framework Overview +  SecurityNakov - .NET Framework Overview +  Security
Nakov - .NET Framework Overview + SecuritySvetlin Nakov
 
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#DAVID Academy
 
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)Lubomir Chorbadjiev
 
Linux: Relaxing Administration - New Horizons Bulgaria
Linux: Relaxing Administration - New Horizons BulgariaLinux: Relaxing Administration - New Horizons Bulgaria
Linux: Relaxing Administration - New Horizons BulgariaNew Horizons Bulgaria
 
Училищен курс по програмиране на C# (2013/2014), занятие №13
Училищен курс по програмиране на C# (2013/2014), занятие №13Училищен курс по програмиране на C# (2013/2014), занятие №13
Училищен курс по програмиране на C# (2013/2014), занятие №13DAVID Academy
 

Ähnlich wie High Quality Code Introduction (20)

Continuous integration (d.atanasov)
Continuous integration (d.atanasov)Continuous integration (d.atanasov)
Continuous integration (d.atanasov)
 
Soft eng.
Soft eng.Soft eng.
Soft eng.
 
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2014), занятие №3 - JavaScript (част 1/2)
 
Курс по уеб програмиране (2015), занятие №1 - HTML
Курс по уеб програмиране (2015), занятие №1 - HTMLКурс по уеб програмиране (2015), занятие №1 - HTML
Курс по уеб програмиране (2015), занятие №1 - HTML
 
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)
Курс по уеб програмиране (2015), занятие №3 - JavaScript (част 1/2)
 
Managing Construction
Managing ConstructionManaging Construction
Managing Construction
 
FABRIQ - Short - Svetlin Nakov
FABRIQ - Short - Svetlin NakovFABRIQ - Short - Svetlin Nakov
FABRIQ - Short - Svetlin Nakov
 
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...Средства на VSTS за управление на проекти, версии на системата, извеждане на ...
Средства на VSTS за управление на проекти, версии на системата, извеждане на ...
 
FABRIQ - Presentation Nakov 0.8
FABRIQ - Presentation Nakov 0.8FABRIQ - Presentation Nakov 0.8
FABRIQ - Presentation Nakov 0.8
 
Programirane i organizaciq
Programirane i organizaciqProgramirane i organizaciq
Programirane i organizaciq
 
Svetlin Nakov - E-Business And NASD Academy
Svetlin Nakov - E-Business And NASD AcademySvetlin Nakov - E-Business And NASD Academy
Svetlin Nakov - E-Business And NASD Academy
 
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows Forms
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows FormsКурс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows Forms
Курс по програмиране за напреднали (2012) - 4. Desktop приложения. Windows Forms
 
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQL
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQLКурс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQL
Курс по информационни технологии (2013) - 3. ADO.NET, LINQ to SQL
 
Svetlin Nakov - .NET Framework Overview
Svetlin Nakov - .NET Framework OverviewSvetlin Nakov - .NET Framework Overview
Svetlin Nakov - .NET Framework Overview
 
Nakov - .NET Framework Overview + Security
Nakov - .NET Framework Overview +  SecurityNakov - .NET Framework Overview +  Security
Nakov - .NET Framework Overview + Security
 
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#
Курс по програмиране на C# 2013 - 1. Въведение в компютърното програмиране и C#
 
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)
Enterprise Content Management with Nuxeo EP 5.3.0 (in bulgarian)
 
Linux: Relaxing Administration - New Horizons Bulgaria
Linux: Relaxing Administration - New Horizons BulgariaLinux: Relaxing Administration - New Horizons Bulgaria
Linux: Relaxing Administration - New Horizons Bulgaria
 
Училищен курс по програмиране на C# (2013/2014), занятие №13
Училищен курс по програмиране на C# (2013/2014), занятие №13Училищен курс по програмиране на C# (2013/2014), занятие №13
Училищен курс по програмиране на C# (2013/2014), занятие №13
 
Security Log Management
Security Log  ManagementSecurity Log  Management
Security Log Management
 

Mehr von Svetlin Nakov

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиSvetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and StartupsSvetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for EntrepreneursSvetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal LifeSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковSvetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПSvetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТSvetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the FutureSvetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperSvetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)Svetlin Nakov
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their FutureSvetlin Nakov
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobSvetlin Nakov
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецептаSvetlin Nakov
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?Svetlin Nakov
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)Svetlin Nakov
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Svetlin Nakov
 

Mehr von Svetlin Nakov (20)

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

High Quality Code Introduction

Hinweis der Redaktion

  1. The variable has never been assigned a value. Its value is whatever bits happened to be in its area of memory when the program started. The value in the variable is outdated. The variable was assigned a value at some point, but the value is no longer valid. Part of the variable has been assigned a value and part has not.
  2. Here are guidelines for avoiding initialization problems.
  3. The code between references to a variable is a “window of vulnerability.” In the window, new code might be added, inadvertently altering the variable, or someone reading the code might forget the value the variable is supposed to contain. It’s always a good idea to localize references to variables by keeping them close together.
  4. Doing this improves the chance that when you modify the loop, you’ll remember to make corresponding modifications to the loop initialization. Later, when you modify the program and put another loop around the initial loop, the initialization will work on each pass through the new loop rather than on only the first pass. C++ Example of Good Variable Declarations and Initializations int receiptIndex = 0; float dailyReceipts = TodaysReceipts(); double totalReceipts = TotalReceipts( dailyReceipts ); C++ Example of Using Two Sets of Variables in a Confusing Way void SummarizeData (...) { ... GetOldData( oldData, &numOldData ); GetNewData( newData, &numNewData ); totalOldData = Sum( oldData, numOldData ); totalNewData = Sum( newData, numNewData ); PrintOldDataSummary( oldData, totalOldData, numOldData ); PrintNewDataSummary( newData, totalNewData, numNewData ); SaveOldDataSummary( totalOldData, numOldData ); SaveNewDataSummary( totalNewData, numNewData ); ... } C++ Example of Using Two Sets of Variables More Understandably void SummarizeDaily( ... ) { GetOldData( oldData, &numOldData ); totalOldData = Sum( oldData, numOldData ); PrintOldDataSummary( oldData, totalOldData, numOldData ); SaveOldDataSummary( totalOldData, numOldData ); ... GetNewData( newData, &numNewData ); totalNewData = Sum( newData, numNewData ); PrintNewDataSummary( newData, totalNewData, numNewData ); SaveNewDataSummary( totalNewData, numNewData ); ... } Part of minimizing the scope of a variable is keeping it as local as possible. It is much more difficult to reduce the scope of a variable that has had a large scope than to expand the scope of a variable that has had a small scope—in other words, it’s harder to turn a global variable into a class variable than it is to turn a class variable into a global variable. It’s harder to turn a protected data member into a private data member than vice versa. Use each variable for one purpose only It’s sometimes tempting to use one variable in two different places for two different activities. Usually, the variable is named inappropriately for one of its uses, or a “temporary” variable is used in both cases (with the usual unhelpful name x or temp ). Avoid variables with hidden meanings Another way in which a variable can be used for more than one purpose is to have different values for the variable mean different things. Make sure that all declared variables are used The opposite of using a variable for more than one purpose is not using it at all. A study by Card, Church, and Agresti found that unreferenced variables were correlated with higher fault rates (1986).
  5. Considerations in Choosing Good Names You can’t give a variable a name the way you give a dog a name—because it’s cute or it has a good sound. Unlike the dog and its name, which are different entities, a variable and a variable’s name are essentially the same thing. The Most Important Naming Consideration The most important consideration in naming a variable is that the name fully and accurately describe the entity the variable represents. An effective technique for coming up with a good name is to state in words what the variable represents. Problem-Orientation A good mnemonic name generally speaks to the problem rather than the solution. A good name tends to express the what more than the how . In general, if a name refers to some aspect of computing rather than to the problem, it’s a how rather than a what . Avoid such a name in favor of a name that refers to the problem itself. Optimum Name Length Gorla, Benander, and Benander found that the effort required to debug a program was minimized when variables had names that averaged 10 to 16 characters (1990). Programs with names averaging 8 to 20 characters were almost as easy to debug. The guideline doesn’t mean that you should try to make all of your variable names 9 to 15 or 10 to 16 characters long. It does mean that if you look over your code and see many names that are shorter, you should check to be sure that the names are as clear as they need to be. The Effect of Scope on Variable Names Are short variable names always bad? No, not always. When you give a variable a short name like i , the length itself says something about the variable—namely, that the variable is a scratch value with a limited scope of operation. Use qualifiers on names that are in the global namespace Common Opposites in Variable Names
  6. Considerations in Choosing Good Names You can’t give a variable a name the way you give a dog a name—because it’s cute or it has a good sound. Unlike the dog and its name, which are different entities, a variable and a variable’s name are essentially the same thing. The Most Important Naming Consideration The most important consideration in naming a variable is that the name fully and accurately describe the entity the variable represents. An effective technique for coming up with a good name is to state in words what the variable represents. Problem-Orientation A good mnemonic name generally speaks to the problem rather than the solution. A good name tends to express the what more than the how . In general, if a name refers to some aspect of computing rather than to the problem, it’s a how rather than a what . Avoid such a name in favor of a name that refers to the problem itself. Optimum Name Length Gorla, Benander, and Benander found that the effort required to debug a program was minimized when variables had names that averaged 10 to 16 characters (1990). Programs with names averaging 8 to 20 characters were almost as easy to debug. The guideline doesn’t mean that you should try to make all of your variable names 9 to 15 or 10 to 16 characters long. It does mean that if you look over your code and see many names that are shorter, you should check to be sure that the names are as clear as they need to be. The Effect of Scope on Variable Names Are short variable names always bad? No, not always. When you give a variable a short name like i , the length itself says something about the variable—namely, that the variable is a scratch value with a limited scope of operation. Use qualifiers on names that are in the global namespace Common Opposites in Variable Names
  7. If the loop is longer than a few lines, it’s easy to forget what i is supposed to stand for, and you’re better off giving the loop index a more meaningful name. Because code is so often changed, expanded, and copied into other programs, many experienced programmers avoid names like i altogether. Java Example of Good Loop Names in a Nested Loop for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) { for ( eventIndex = 0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) { score[ teamIndex ][ eventIndex ] = 0; } } C++ Examples of Cryptic Flags if ( flag ) ... if ( statusFlag & 0x0F ) ... if ( printFlag == 16 ) ... if ( computeFlag == 0 ) ... flag = 0x1; statusFlag = 0x80; printFlag = 16; computeFlag = 0; C++ Examples of Better Use of Status Variables if ( dataReady ) ... if ( characterType & PRINTABLE_CHAR ) ... if ( reportType == ReportType_Annual ) ... if ( recalcNeeded == True ) ... dataReady = True; characterType = CONTROL_CHARACTER; reportType = ReportType_Annual; recalcNeeded = False; Moreover, because the variables are officially given a “temporary” status, programmers tend to treat them more casually than other variables, increasing the chance of errors. Names like done and success are good boolean names because the state is either True or False ; something is done or it isn’t; it’s a success or it isn’t. Names like status and sourceFile , on the other hand, are poor boolean names because they’re not obviously True or False . Negative names like notFound , notdone , and notSuccessful are difficult to read when they are negated—for example, if not notFound When you use an enumerated type, you can ensure that it’s clear that members of the type all belong to the same group by using a group prefix, such as Color_ , Planet_ , or Month_ . When naming constants, name the abstract entity the constant represents rather than the number the constant refers to. FIVE is a bad name for a constant (regardless of whether the value it represents is 5.0 ). CYCLES_NEEDED is a good name.
  8. If the loop is longer than a few lines, it’s easy to forget what i is supposed to stand for, and you’re better off giving the loop index a more meaningful name. Because code is so often changed, expanded, and copied into other programs, many experienced programmers avoid names like i altogether. Java Example of Good Loop Names in a Nested Loop for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) { for ( eventIndex = 0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) { score[ teamIndex ][ eventIndex ] = 0; } } C++ Examples of Cryptic Flags if ( flag ) ... if ( statusFlag & 0x0F ) ... if ( printFlag == 16 ) ... if ( computeFlag == 0 ) ... flag = 0x1; statusFlag = 0x80; printFlag = 16; computeFlag = 0; C++ Examples of Better Use of Status Variables if ( dataReady ) ... if ( characterType & PRINTABLE_CHAR ) ... if ( reportType == ReportType_Annual ) ... if ( recalcNeeded == True ) ... dataReady = True; characterType = CONTROL_CHARACTER; reportType = ReportType_Annual; recalcNeeded = False; Moreover, because the variables are officially given a “temporary” status, programmers tend to treat them more casually than other variables, increasing the chance of errors. Names like done and success are good boolean names because the state is either True or False ; something is done or it isn’t; it’s a success or it isn’t. Names like status and sourceFile , on the other hand, are poor boolean names because they’re not obviously True or False . Negative names like notFound , notdone , and notSuccessful are difficult to read when they are negated—for example, if not notFound When you use an enumerated type, you can ensure that it’s clear that members of the type all belong to the same group by using a group prefix, such as Color_ , Planet_ , or Month_ . When naming constants, name the abstract entity the constant represents rather than the number the constant refers to. FIVE is a bad name for a constant (regardless of whether the value it represents is 5.0 ). CYCLES_NEEDED is a good name.
  9. There are no hard-and-fast rules for when you should establish a naming convention, but here are a few cases in which conventions are worthwhile:
  10. Standardizing prefixes for common meanings provides a terse but consistent and readable approach to naming data. The best known scheme for standardizing prefixes is the Hungarian naming convention, which is a set of detailed guidelines for naming variables and routines (not Hungarians!) that was widely used at one time in Microsoft Windows programming. Although the Hungarian naming convention is no longer in widespread use, the basic idea of standardizing on terse, precise abbreviations continues to have value. Standardized Prefixes are composed of two parts: the user-defined–data type (UDT) abbreviation and the semantic prefix. User-Defined–Type (UDT) Abbreviation The UDT abbreviation identifies the data type of the object or variable being named. UDT abbreviations might refer to entities such as windows, screen regions, and fonts. A UDT abbreviation generally doesn’t refer to any of the predefined data types offered by the programming language. UDT Abbreviation Meaning ch Character (a character not in the C++ sense, but in the sense of the data type a word-processing program would use to represent a character in a document) doc Document pa Paragraph scr Screen region sel Selection wn Window Semantic Prefix Semantic prefixes go a step beyond the UDT and describe how the variable or object is used. Unlike UDTs, which vary project to project, semantic prefixes are somewhat standard across projects. Table 11-7 shows a list of standard semantic prefixes. Semantic Meaning Prefix c Count (as in the number of records, characters, and so on) first The first element that needs to be dealt with in an array. first is similar to min but relative to the current operation rather than to the array itself. g Global variable i Index into an array last The last element that needs to be dealt with in an array. last is the counterpart of first . lim The upper limit of elements that need to be dealt with in an array. lim is not a valid index. Like last , lim is used as a counterpart of first . Unlike last , lim represents a noninclusive upper bound on the array; last represents a final, legal element. Generally, lim equals last + 1 . m Class-level variable max The absolute last element in an array or other kind of list. max refers to the array itself rather than to operations on the array. min The absolute first element in an array or other kind of list. p Pointer
  11. Avoid misleading names or abbreviations Be sure that a name is unambiguous. For example, FALSE is usually the opposite of TRUE and would be a bad abbreviation for “Fig and Almond Season.” Avoid names with similar meanings If you can switch the names of two variables without hurting the program, you need to rename both variables. Avoid variables with different meanings but similar names If you have two variables with similar names and different meanings, try to rename one of them or change your abbreviations. Avoid names like clientRecs and clientReps . Avoid names that sound similar, such as wrap and rap Homonyms get in the way when you try to discuss your code with others. One of my pet peeves about Extreme Programming (Beck 2000) is its overly clever use of the terms Goal Donor and Gold Owner, Avoid numerals in names If the numerals in a name are really significant, use an array instead of separate variables. If an array is inappropriate, numerals are even more inappropriate. Avoid misspelled words in names It’s hard enough to remember how words are supposed to be spelled. To require people to remember “correct” misspellings is simply too much to ask. For example, misspelling highlight as hilite to save three characters makes it devilishly difficult for a reader to remember how highlight was misspelled. Avoid words that are commonly misspelled in English Absense, acummulate, acsend, calender, concieve, defferred, definate, independance, occassionally, prefered, reciept, superseed, and many others are common misspellings in English. Most English handbooks contain a list of commonly misspelled words. Avoid using such words in your variable names. Avoid multiple natural languages In multi-national projects, enforce use of a single natural language for all code including class names, variable names, and so on. Reading another programmer’s code can be a challenge; reading another programmer’s code in Southeast Martian is impossible. Avoid the names of standard types, variables, and routines For example, the following code fragment is legal in PL/I, but you would be a certifiable idiot to use it: if if = then then then = else; else else = if;
  12. Myth : a well mange software project conducts methological requirements development and defines a stable list of the program’s responsibilities. Design follows requiremnets, and it is done carefully so that coding can proceed linearly , from start to finish, implying that most of the code can be writeen once, tested, and forgotten. Accoring to the myth, the only time that the code is significantly modified is during the software – maintenance phase, something that happens only after the initial version of a system has been delivered Reality : code eevolves substantially during its initial development. Many of the changes seen during initial coding are at least as dramatic as changes seen during maintenance. Coding, debugging and unit testing consume between 30 to 65 percent of the effort on a typycal project, depending on the project’s size. If coding and unit testing were straight-forward processes, they would consume no more than 20 – 30 percent of the total effort on a project. Even on well-managed project, however, requirements change by about one to four percent per month. Requirements changes invariably cause corresponding code changes – sometimes substantial code changes.
  13. Myth : a well mange software project conducts methological requirements development and defines a stable list of the program’s responsibilities. Design follows requiremnets, and it is done carefully so that coding can proceed linearly , from start to finish, implying that most of the code can be writeen once, tested, and forgotten. Accoring to the myth, the only time that the code is significantly modified is during the software – maintenance phase, something that happens only after the initial version of a system has been delivered Reality : code eevolves substantially during its initial development. Many of the changes seen during initial coding are at least as dramatic as changes seen during maintenance. Coding, debugging and unit testing consume between 30 to 65 percent of the effort on a typycal project, depending on the project’s size. If coding and unit testing were straight-forward processes, they would consume no more than 20 – 30 percent of the total effort on a project. Even on well-managed project, however, requirements change by about one to four percent per month. Requirements changes invariably cause corresponding code changes – sometimes substantial code changes.
  14. Повторение на код – при наличие на проблеми в такъв код се налага да се правят модификации на много места Даден метод е прекалено обемист – един метод не трябва да е по - дълъг от един екран; един начин да подобрим системата е да повишиме нейната модуларност чрез добре дефинирани методи, изпълняващи ясни и точни задачи. Даден цикъл е прекалено обемист – тялото на даден цикъл е добър кандидат за декларирането на отделен метод, като по този начин се намаля сложността на даден цикъл Даден клас има несвързани отговорности – ако намерите клас който реализира несвързани едни с други отговорности, вероятно този клас е по добре да се раздели на няколко различни класове, всеки от които има ясна група от взаимосвързани отговорности Даден клас не предоставя добро ниво на абстракция – интерфейсите на класовете имат склонност да еволюират в течение на времето (във време на бързи промени, които целят предимно бързото реализиране). По този начин интерфейсът на класа в даден момент става като чудовището Франкенщайн – грозен и труден за интелектуална поддръжка
  15. Даден метод има дълъг списък с променливи – обикновено се счита че списъкът с параметри не бива да надвишава 7. Една промяна налага паралелна модификация на няколко класове – например ако имплементирането на един специален формат налага модификацията на 15 класове които ще го използват, това е добър момент в който ние можем да се замислим дали не можем да създадем нов клас който енкапсулира този нов формат Свързани една с друга данни се използват заедно, но не са обединени в клас – ако подаднете в ситуация в която променяте една обща група от променливи, вероятно е добре да помислите да обедините тези данни в отделен клас Даден метод използва повече функционалност от други класове отколкото от собствения си – това предполага че метода трябва да бъде преместен в друг клас Даден клас е прекалено обвързан с друг – encapsulation/ енкапсулацията ( information hiding ) е вероятно най-силното средство с което можете да направите вашите програми лесно поддържани и да намалите вероятността от каскадни промени в кода. Всеки път когато видите че даден клас знае прекалено много за даден друг клас, по добре се насочете към по силна енкапсулация отколкото към по – слаба Полета на даден клас са public – public data members винаги заличават разликата м/у интерфейс и имплементация и най-вече нарушават правилата за енкапсулация и ограничават гъвкавостта на кода.
  16. Преработете даден условен израз в метод – обикновено това се прави в случаи в които този израз се среща на много други места; друга употреба е когато условния израз е много сложен и включва в себе си други изрази Използвайте междинни променливи – присвоете на променлива стойността на даден израз и и дайте подходящо име така че то да обяснява целта на този израз Преобразувайте обикновени данни ( data primitive ) в нов клас – ако обикновенните данни се нуждаят от обслужваща функционалност, преобразувайте данните в обект и добавете функционалността от която се нуждае; по този начин се постига и по добра типова сигурност и валидност ( stricter type checking ) Групирайте свързаните константи в изброими типове ( enumerations ) – спомага за по стриктна провека на типа, след като е обособен като клас, или ако е във вид на изброим тип – тогава кода е по-изразен
  17. Извадете определен код от даден метод и го превърнете в нов метод – в случай че използвате даден кодов блок многократно, по добре създайте нов метод който съдържа тази функционалност и извиквайте директно новия метод Премахнете даден метод, ако кода който съдържа е прекалено елементарен и кратък – вземете кода от тялото на даден метод ако той е прост и самоописващ се Преработете дълъг метод в няколко по малки или в изцяло нов клас – ако един метод има прекалено голяма имплементация, помислете дали този метод не може да се раздели на отделни самостоятелни подчасти, който да бъдат по-нататък реализирани в нови методи или в отделен клас Ако има нужда от допълнителен параметър за даден метод добавете го към списъка с параметри – вместо да се използват глобални променливи, предпочита се добавянето на нов параметър към списъка с параметри на даден метод
  18. Променете обекти подавани по стойност с такива подавани по указател – поддръжката на копия на един клас е трудно и непосилно; това оказва и влияние върху производителността на системата като цяло (особено в C++ ) Преобразувайте един клас в два – ако даден клас има 2 различни по типа си отгороности, по добре е да разделите класа на 2 отделни такива че всеки да има точно определени и взаимосвързани отговорности Премахнете даден клас – ако даден клас не върши много работа, просто го премахнете
  19. Създайте абстракция на данните върху които нямате контрол – пример е данните които са въведени през GUI-to и които се подават по късно на дадени контроли – в такъв момент можем да създадем отделен клас CControlData който да представлява данните който искаме да получим ( CControlData ще предоставя интерфейс за заявка и достъп до данните, като евентуално ще бъде възможно не винаги да се връщат валидни данни) Използвайте factory метод – кагато е необходимо да създадем определена инстанция на клас, според дадена константа или флаг, тогава е по добре да създадем статичен factory метод който ще връща правилните инстанции според подадения параметър
  20. Характеристики на добрия стил на програмиране: добра структура на програмата използване на ясни и лесни за разбиране похвати добри имена на променливи, методи и класове използване на именувани константи, вместо “магически” числа или стрингове добро структуриране на кода минимизация на сложността на реализация
  21. Писането на коментари ви помага да осмислите по-добре това което искате да реализирате – ако не можете да напишете лесно коментари, това е ясен знак че вие не разбирате добре това което трябва да реализирате