Good and Bad Code
The Broken Window Theory
The Grand Redesign in the Sky
The Sushi Chef Rule
The Hotel Room Rule
The Boy Scout Rule
OOP Patterns and Principles
SOLID Principles
How to measure clean code?
Tools
How Data Flow analysis works in a static code analyzerAndrey Karpov
Data flow analysis is a technology for source code analysis, widely used in various development tools: compilers, linters, IDE. We'll talk about it exemplifying with design of a static analyzer. The talk covers classification and various kinds of data flow analysis, neighbouring technologies supporting each other, obstacles arising during development, surprises from C++ language when one tries to analyze the code. In this talk, some errors, detected in real projects using this technology, are shown in detail.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
Clojure is a new dialect of LISP that runs on the Java Virtual Machine (JVM). As a functional language, it offers great benefits in terms of programmer productivity; as a language that runs on the JVM, it also offers the opportunity to reuse existing Java libraries. Simon’s interest is in using Clojure to build desktop applications with the Java Swing GUI library. In this presentation Simon discusses how the power of Clojure can be applied to Swing, and whether it hits the sweet spot.
How Data Flow analysis works in a static code analyzerAndrey Karpov
Data flow analysis is a technology for source code analysis, widely used in various development tools: compilers, linters, IDE. We'll talk about it exemplifying with design of a static analyzer. The talk covers classification and various kinds of data flow analysis, neighbouring technologies supporting each other, obstacles arising during development, surprises from C++ language when one tries to analyze the code. In this talk, some errors, detected in real projects using this technology, are shown in detail.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
Clojure is a new dialect of LISP that runs on the Java Virtual Machine (JVM). As a functional language, it offers great benefits in terms of programmer productivity; as a language that runs on the JVM, it also offers the opportunity to reuse existing Java libraries. Simon’s interest is in using Clojure to build desktop applications with the Java Swing GUI library. In this presentation Simon discusses how the power of Clojure can be applied to Swing, and whether it hits the sweet spot.
Innovation durch Scrum und Continuous DeliveryPeter Gfader
Kunden begeistern mit einem konstanten Fluss von Neuheiten
Zielgruppe: Scrum Practitioners die Ihren Prozess auf die nächste Ebene bringen wollen
Unternehmen kämpfen mit Bürokratie, Abhängigkeiten, Menschlichem Verhalten, Technischen Problemen und verlieren dabei das Ziel aus den Augen. Continuos Delivery ist mehr als eine technische Praktik, kann mit Scrum funktionieren und verändert die Weise wie wir Software entwickeln.
Wir werden beleuchten, wie wir öfter etwas Nützliches liefern können, wie wir den Kunden in den Mittelpunkt unserer Bemühungen stellen und was das für Auswirkungen auf ein Unternehmen hat. Ist ein potentielles Endresultat das Lean Startup?
V1.0
How often do you get a bug report that you can’t reproduce?
How often do you struggle to find the source of the bug in your code?
How can you streamline the testing process and make sure you don’t repeat the same bugs?
With Visual Studio 2010 & Team Foundation Server (TFS) 2010 there are a lot of new features for testers and developers that will solve these problems.
In this session you will learn how to: automate more, reproduce bugs easier, maintain your tests and configuration and discover problems sooner.
from Peter Gfader
Clean Code - How to write comprehensible code regarding cognitive abilities o...Mario Gleichmann
Beside a more general motivation for readable / comprehensible code, we’ll take a closer look at the cognitive foundation of common Principles (DRY, TDA, SOLID, …) and Design Approaches (DDD, BDD, …), digging into the field of program comprehension and will derive some practical considerations on how to write comprehensible code under the given cognitive abilities of human mind.
Empathic Programming - How to write comprehensible codeMario Gleichmann
Slides to a (non-commercial) talk i gave 2011 at XPUG Rhein/Main (Germany) about how to write comprehensible code, regarding cognitive abilities of human mind.
Continuous Delivery with TFS msbuild msdeployPeter Gfader
If you are deploying your software manually, you are doing it wrong.
If you deploying once a month, you are doing it wrong.
If you as a developer are deploying from Visual Studio by clicking "Publish", you are doing it wrong.
If a bug-fix takes you 1 hour but your customer needs to wait a week until he gets it, you are doing it wrong.
Manual deployments are NOT fun. See a good way on how to automate the deployment with TFS 2010, msbuild and msdeploy.
Java 8 helps use write better looking code. Checked exceptions, however, do not. What can we do to overcome these issues?
Lambdas and streams help us write clear and concise code, but can we do better? Javaslang helps out a bit.
Want more? Maybe turn to Scala.
Clean Code (Presentacion interna en Virtual Software)jmiguel rodriguez
Presentación en Virtual Software sobre el mítico libro Clean Code de Uncle Bob. Resumen de los primeros capitulos del libro para intentar concienciar sobre la necesidad de crear un buen código
Presentation on writing clean and maintainable good. I have present really simple steps to write high quality code and share many more benefit of writing clean code.
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
Wszyscy zostaliśmy oszukani! Automatyczne zarządzanie pamięci rozwiąże wszystkie Wasze problemy, mówili. W zarządzanych środowiskach takich jak CLR JVM nie będzie wycieków pamięci, mówili! Właściwie pamięć jest tania i nie musisz się już nią nigdy więcej martwić. Wszyscy kłamali. Automatyczne zarządzanie pamięcią jest wygodną abstrakcją i bardzo często działa dobrze. Ale jak każda abstrakcja, wcześniej czy później "wycieka" ona. I to najczęściej w najmniej spodziewanym i przyjemnym momencie. W tej sesji spróbuję otworzyć oczy na fakt, że błoga nieświadomość nt. tej abstrakcji może być kosztowna. Pokażę jak może się objawić frywolne traktowanie pamięci i co możemy zyskać pisząc kod zdając sobie sprawę, że pamięć jednak nie jest nieskończona, tania i zawsze jednakowo szybka.
Beyond php - it's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
Technology: A Means to an End with Thibault ImbertFITC
Technology: A Means to an End
with Thibault Imbert
Technology is fascinating, but should this be what drives us? What are the things you can do to differentiate yourself today? With all that noise, what are things you should be looking at?
In this talk, Thibault Imbert will look at the different technologies available today to build amazing experiences and what’s coming tomorrow. He will focus on the importance of learning, crafting and getting out of your comfort zone and most importantly, to never be religious about a technology.
Presented at FITC Toronto 2014 on April 27-29, 2014
More info at www.FITC.ca
FITC '14 Toronto - Technology, a means to an endThibault Imbert
Technology is fascinating, but should this be what drives us? What are the things you can do to differentiate yourself today? With all that noise, what are things you should be looking at?
In this talk, Thibault Imbert will look at the different technologies available today to build amazing experiences and what’s coming tomorrow. He will focus on the importance of learning, crafting and getting out of your comfort zone and most importantly, to never be religious about a technology.
Beyond php - it's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
We all do code reviews. Who doesn't admit this – does it twice as often. C++ code reviewers look like a sapper. .. except that they can make a mistake more than once. But sometimes the consequences are painful . Brave code review world.
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
Один из лучших способов снизить количество багов в играх – это показывать программистам, как не стоит писать код. В своём докладе я соберу самые вкусные и необычные ошибки, которые удалось найти в C++ и C# коде таких игр, как VVVVVV, Space Engineers, Command & Conquer, osu! и даже Doom. Я уверен, что каждый из слушателей обязательно узнает для себя что-то новое. В конце концов, это просто приятно – лично увидеть ошибки из кода знакомой и любимой игры!
Lors de cette présentation, nous apprendrons à créer des applications Web plus rapidement et avec moins d'erreurs en utilisant un langage de programmation puissant et amusant.
Agenda
- Installer TypeScript et configurer un nouveau projet.
- Tirer avantage des types de données.
- Développer en Objets avec TypeScript
- Ecrire de meilleures fonctions
- Retrouver vos données avec LINQ
- Programmer de manière asynchrone
- Bonnes pratiques
- Avantages et inconvénients des projets TypeScript
- Conclusion et Discussion
Beyond PHP - It's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
While porting 32-bit software to 64-bit systems there may appear some errors in the code of applications which were written in C++ language. The cause for these hides in the alteration of the base data types (to be more exact, in the relations between them) with the new hardware platform.
Achieving Technical Excellence in Your Software Teams - from Devternity Peter Gfader
Our industry has a problem: We are not lacking software methodologies, programming languages, tools or frameworks but we need great software engineers.
Great software engineer teams build quality-in and deliver great software on a regular basis. The technical excellence of those engineers will help you escape the "Waterfall sandwich" and make your organization a little more agile, from the inception of an idea till they go live.
I will talk about my experiences from the last 15 years, including small software delivery teams until big financial institutions.
Why would a company like to be "agile"?
How can a company achieve that?
How can you achieve Technical Excellence in your software teams?
What developer skills are more important than languages, methods or frameworks?
This will be an interactive session with a Q&A at the end.
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019Peter Gfader
Our industry has a problem:
We are not lacking software methodologies, programming languages, tools or frameworks.
We need great software teams.
Great software engineering teams build quality-in and deliver great software on a regular basis.
The technical testing excellence of those teams will help you escape the “Waterfall sandwich” and make your organization a little more agile, from the inception of an idea till they go live.
---
Keynote from Testcon.lt 2019 https://www.testcon.lt/peter-gfader/
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)Peter Gfader
Our industry has a problem: We are not lacking software methodologies, programming languages, tools or frameworks but we need great software engineers.
Great software engineering teams build quality-in and deliver great software on a regular basis. The technical excellence of those engineers will help you escape the "Waterfall sandwich" and make your organization a little more agile, from the inception of an idea till they go live.
I will talk about my experiences from the last 15 years, including small software delivery teams until big financial institutions.
* Why would a company like to be "agile"?
* How can a company achieve that?
* How can you achieve Technical Excellence in your software teams?
* What developer skills are more important than languages, methods or frameworks?
----
What is the difference between Agile and Business Agility? I will use this as an intro exercise.
---
What is "Business Agility"? Why is Agility important? What is Software Craftsmanship?
What can we do to improve our Technical Excellence?
https://beyond-agility.com
What is "Agile"?
Why would someone like to be agile?
What are the 3 pillars for agile software development?
How can you achieve technical excellence in your software teams?
Are developer skills more important than languages, methods or frameworks?
Use Scrum and Continuous Delivery to innovate like crazy!Peter Gfader
How often do you release your product to your end users?
How often do your end users see and use your product?
Why is Continuous Delivery helping us to focus on business value?
How can Scrum help us to be innovative?
These and more questions are going to be answered in this talk about Scrum with Continuous Delivery.
Companies and organizations struggle with bureaucracy, dependencies, silo thinking, human behavior and technical problems and loose the real goal. Continuous Delivery being more than a technical practice can work with Scrum and changes the way we write software completely.
Let’s see how we can combine those and delight our customers with a constant flow of features and happiness.
Target audience: Experienced Scrum Practitioners that would like to take the next step to delight their customers
Why is Performance important?
Applications in general
Web applicaitons
What can we as devs do?
Tips: How to optimize
Web applications, Silverlight, Backend, …
Regression
How to maintain performance over time
How to get faster over time
Discussion: What tips do you have in your toolbox?
Overview of ASP.NET
An ASP.NET Page
Server Controls
User Controls
Validation
Master Pages
Themes & skins
Page Cycle Events
Menu, Navigation & Sitemaps
Some cool new ASP.NET 2 Server Controls
N-Tier Application with Windows Forms - Deployment and SecurityPeter Gfader
Part 1: Deployment of .NET Winforms apps
History
Deployment & Updates
Security
Issues & Warnings
Configuration and user settings
Part 2: Security
Role-based security
Authentication and Authorization
Impersonation
Code Access Security
Assembly Strong Naming
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
2. C# and .NET
(Java not anymore)
Testing
Automated tests
Agile, Scrum
Scrum Developer Trainer
Technology aficionado
Silverlight
ASP.NET
Windows Forms
LINQ,
...
Peter Gfader
http://blog.gfader.com/
twitter.com/peitor
#netug
3. • Why code matters
• Good and Bad Code
• The Broken Window Theory
• The Grand Redesign in the Sky
• The Boy Scout Rule
• OOP Patterns and Principles
• SOLID Principles
• How to measure clean code?
•Tools
Agenda
16. It's gotta ship?
It's gotta pass the tester?
It's gotta implement requirements?
It's gotta be reasonably performant?
"Wartung"?
(aka Maintainability)
What is good code?
39. "Everything I have to change,
in order to make the product owner happy!"
• Config files .config, .svc
• XAML .xaml, .CSS, ..
• Code .cs, .vb, .js, ..
• Deployment scripts .ps
• Batch files .bat
What is code?
43. public class PrintServer
{
public string CreateJob(PrintJob data) { //...
}
public int GetStatus(string jobId) { //...
}
public void Print(string jobId, int startPage, int endPage) { //...
}
public List<Printer> GetPrinterList() { //...
}
public bool AddPrinter(Printer printer) { //...
}
public event EventHandler<JobEvent> PrintPreviewPageComputed;
public event EventHandler PrintPreviewReady;
// ...
}
44. public class PrintServer {
public string CreateJob(PrintJob data) { //...
}
public int GetStatus(string jobId) { //...
}
public void Print(string jobId, int startPage, int endPage) { //...
}
}
public class PrinterList {
public List<Printer> GetPrinterList() { //...
}
public bool AddPrinter(Printer printer) { //...
}
}
45. OpenClose Principle
Open for extension
Close for modification
Every entity should be open for extension, but closed for modification
49. public class ToolbarManager
{
private readonly Dictionary<long, Action> _versionAction;
public ToolbarManager()
{
_versionAction = new Dictionary<long, Action>();
_versionAction.Add(2003, SaveForVs2003);
_versionAction.Add(2005, SaveForVs2005);
_versionAction.Add(2008, SaveForVs2008);
_versionAction.Add(2010, SaveForVs2010);
}
public void SaveToolbarStateBetter()
{
var version = Core.GetVisualStudioVersion();
if (_versionAction.ContainsKey(version))
{
_versionAction[version].Invoke();
}
}
50. public class ToolbarManager
{
private readonly Dictionary<long, Action> _versionAction;
public ToolbarManager()
{
_versionAction = new Dictionary<long, Action>();
_versionAction.Add(2003, SaveForVs2003);
_versionAction.Add(2005, SaveForVs2005);
_versionAction.Add(2008, SaveForVs2008);
_versionAction.Add(2010, SaveForVs2010);
_versionAction.Add(2012, SaveForVs2012);
}
private void SaveForVs2012()
{
Configuration.EnableSpeechRecognition = "True";
Configuration.HandGestureRecognition = AddinCommandBar.Top;
}
51. Liskov Substitution Principle
If for each object o1 of type S there is an object o2 of type T
such that for all programs P defined in terms of T,
the behavior of P is unchanged
when o1 is substituted for o2 then S is a subtype of T
56. public class Rectangle
{
protected int _width;
public virtual int Width
{
get { return _width; }
set { _width = value; }
}
protected int _height;
public virtual int Height
{
get { return _height; }
set { _height = value; }
}
public int GetArea()
{
return Width*Height;
}
}
public class Square : Rectangle
{
public override int Width
{
get { return _width; }
set
{
_width = value;
_height = value;
}
}
public override int Height
{
get { return _height; }
set
{
_height = value;
_width = value;
}
}
}
57. [TestFixture]
public class RectangleTests
{
[Test]
public void CheckArea_PassingTest()
{
Rectangle r = new Rectangle();
CheckAreaOfRectangle(r);
}
private void CheckAreaOfRectangle(Rectangle r)
{
r.Width = 5;
r.Height = 2;
Assert.AreEqual(10, r.GetArea());
}
[Test]
public void CheckArea_FAILINGTest()
{
Rectangle r = new Square();
CheckAreaOfRectangle(r);
}
}
58. public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public int GetArea()
{
return Width * Height;
}
}
public class Square
{
public int Side { get; set; }
public int GetArea()
{
return Side * Side;
}
}
59. Interface Segregation Principle
Don’t be force to implement unused methods
Avoid “Fat Interfaces”
Clients should not be forced to depend on methods they do not use
60. public override bool ValidateUser(string usercode, string password)
{
var returnValue = false;
MoneyService moneyServices = new MoneyService();
if (moneyServices.IsValid(usercode, password))
{
returnValue = true;
}
return returnValue;
}
-- snip snip snip ----
public class MoneyMembershipProvider : MembershipProvider
{
61. namespace System.Web.Security
{
public abstract class MembershipProvider : ProviderBase
{
public abstract bool EnablePasswordRetrieval { get; }
public abstract bool EnablePasswordReset { get; }
public abstract bool RequiresQuestionAndAnswer { get; }
public abstract string ApplicationName { get; set; }
public abstract int MaxInvalidPasswordAttempts { get; }
public abstract int PasswordAttemptWindow { get; }
public abstract bool RequiresUniqueEmail { get; }
public abstract MembershipPasswordFormat PasswordFormat { get; }
public abstract int MinRequiredPasswordLength { get; }
public abstract int MinRequiredNonAlphanumericCharacters { get; }
public abstract string PasswordStrengthRegularExpression { get; }
public abstract MembershipUser CreateUser(string username, string password, string email,
string passwordQuestion, string passwordAnswer, bool isApproved,
object providerUserKey, out MembershipCreateStatus status);
public abstract bool ChangePasswordQuestionAndAnswer(string username, string password,
string newPasswordQuestion, string newPasswordAnswer);
public abstract string GetPassword(string username, string answer);
public abstract bool ChangePassword(string username, string oldPassword, string newPassword);
public abstract string ResetPassword(string username, string answer);
public abstract void UpdateUser(MembershipUser user);
public abstract bool ValidateUser(string username, string password);
public abstract bool UnlockUser(string userName);
public abstract MembershipUser GetUser(object providerUserKey, bool userIsOnline);
public abstract MembershipUser GetUser(string username, bool userIsOnline);
public abstract string GetUserNameByEmail(string email);
public abstract bool DeleteUser(string username, bool deleteAllRelatedData);
public abstract MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords);
public abstract int GetNumberOfUsersOnline();
public abstract MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize,
out int totalRecords);
public abstract MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
out int totalRecords);
protected virtual byte[] EncryptPassword(byte[] password);
62. public class AuctionsPlusMembershipProvider : MembershipProvider
{
-- snip snip snip ----
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPa
{
throw new NotImplementedException();
}
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passw
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecord
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalReco
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
63. public interface IEnableUservalidation
{
bool ValidateUser(string username, string password);
}
public interface IAllowUserRetrieval
{
MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize,
out int totalRecords);
MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
out int totalRecords);
MembershipUser GetUser(object providerUserKey, bool userIsOnline);
MembershipUser GetUser(string username, bool userIsOnline);
string GetUserNameByEmail(string email);
MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords);
int GetNumberOfUsersOnline();
}
public interface IProvidePassword
{
bool ChangePasswordQuestionAndAnswer(string username,
string password,
string newPasswordQuestion,
string newPasswordAnswer);
bool ChangePassword(string username, string oldPassword, string newPassword);
string ResetPassword(string username, string answer);
string GetPassword(string username, string answer);
}
64. Dependency Inversion Principle
Depend on Abstractions
Interfaces, not concrete types
Inject Dependencies into Classes
Inversion of Control
Hollywood Principle: "Don't call us, We call you"
I tell an object its partners,
and not the object chooses its partners
65. public class WCFSalaryService
{
private IDBHelper dbHelper = new SQLHelper();
private ILoggerHelper loggerHelper = new FileLogWriter();
private IAuthenticationHelper authenticationHelper = new WebServiceAuth();
private IUserUtility userHelper;
private IConnections connectionHelper = new HTTPConnectionHelper();
public WCFSalaryService()
{
userHelper = new UserHelper(connectionHelper);
userHelper.Logger = loggerHelper;
dbHelper.Logger = loggerHelper;
// ----- snip snip snip ----
}
// ----- snip snip snip ----
}
69. public class SalaryScenario : NinjectModule
{
public override void Load()
{
Bind<ILoggerHelper>().To<FileLogWriter>();
Bind<IDBHelper>().To<SQLHelper>();
Bind<IAuthenticationHelper>().To<WebServiceAuth>();
Bind<IUserUtility>().To<UserUtility>();
Bind<IConnections>().To<HTTPConnectionHelper>();
}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
IKernel kernel = new StandardKernel (new SalaryScenario());
var logger = kernel.Get<ILoggerHelper>();
logger.LogIt("App started up");
}
81. • Readable
• Tests in place
• No duplication
"Wartung"
What is clean code?
82. • Why code matters
• Good and Bad Code
• The Broken Window Theory
• The Grand Redesign in the Sky
• The Boy Scout Rule
• OOP Patterns and Principles
• SOLID Principles
• How to measure clean code?
•Tools
Summary
88. VS2010 Code Metrics
http://bit.ly/bda4T1
JB Rainsberger The Four Elements of Simple Design
http://www.jbrains.ca/permalink/the-four-elements-of-simple-design
How to hire a programmer? Have people fix up some smelly code
http://codebetter.com/blogs/karlseguin/archive/2006/12/01/How-to-hire-a-programmer-
_2D00_-Part-2-_2D00_-Improve-this-code.aspx
C# Coding Practices
http://www.codeproject.com/KB/cs/CSharp_Coding_Practices.aspx
Object Oriented Principles
http://www.objectmentor.com/omSolutions/oops_what.html
Further Reading
93. Be a boy scout
Leave the campground cleaner than you found it
94. Be a boy scout
Leave code cleaner than you found it
All links and slides on
http://blog.gfader.com
Thank you!!!
Editor's Notes
http://blog.gfader.com
Click to add notes...Peter Gfader http://blog.gfader.com
Z1 1936ENIAC 1943, ..
Z1 1936ENIAC 1943, ..
Z1 1936ENIAC 1943, ..
Z1 1936ENIAC 1943, ..
Adams theory on this is: “We will have an exponential growth as soon as code is writing code”
Open Word and get suggestions!CorrectnessUsabilityEfficiencyReliabilityIntegrityAdaptabilityAccuracyRobustness Maintainability FlexibilityPortabilityReusabilityReadabilityTestabilityUnderstandabilityNot too many WTFsEasy to readEasy to maintainConsistent convention (naming, layout, design patterns)Follows SSW rulesCode Auditor 0No bugsDoes what it should do (Client’s needs)Easy to changeWritten in a language, that you can find dev's forPerformance
Who is a dev? Testers? BA's? PM's?
This is a VB programmer, so he probably needs that
HTML spew, I don’t say more… beginner devs underneath covers
Less code = less code to read?Shorter code = faster?Shorter code = less memory?
To get things done?Speed?Meeting Deadlines?Taking Shortcuts..But after too many shortcuts there is no progress...
DBASE was terrible!Look up wikipedia
Sushi Chef rule - Clean up as you doThe Sushi Chef has done this certain routine of hand movements already 100 times before.He is just following this routine.He cleans up as he does his jobs.#1 Software devs do something slightly different every day#2 Devs want to get something done. The brain is in "Get done mode". Clean up later
What is code?Stuff that a machine reads
High cohesion - better understandability, robustnessLow coupling - better maintainability, high resistance to changes