Master the Art of Writing Clean Code in C# | Elias Spock | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Master the Art of Writing Clean Code in C#

teacher avatar Elias Spock, Chance favors the prepared mind.

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

86 Lessons (7h 16m)
    • 1. Promo

      5:17
    • 2. Introduction

      2:17
    • 3. Meta Principles - Outline

      2:17
    • 4. DRY

      9:50
    • 5. KISS

      7:37
    • 6. YAGNI

      11:37
    • 7. SoC

      4:28
    • 8. CQS

      2:14
    • 9. PoLA

      3:03
    • 10. Encapsulation

      19:13
    • 11. Meta Principles Conclusion

      2:41
    • 12. Names Outline

      1:28
    • 13. General Principles of Naming

      12:46
    • 14. About Names Once Again

      11:01
    • 15. Violating Naming Conventions

      1:29
    • 16. Naming Conventions in .NET

      7:26
    • 17. Names Conclusion

      1:11
    • 18. Writing Clean Functions Outline

      1:26
    • 19. Variable Declarations on the Top

      1:04
    • 20. Magic Numbers

      1:31
    • 21. Stringly Typed Smell

      1:08
    • 22. Property vs Method

      6:41
    • 23. Implementing Parameters

      3:20
    • 24. Too Many Parameters

      2:28
    • 25. Too Long Methods

      6:20
    • 26. Creational Patterns VS Constructors

      3:11
    • 27. Method Extraction

      2:40
    • 28. Simplifying Complex Logic

      2:47
    • 29. Sequence of Arguments

      4:17
    • 30. Guard Clauses and Early Returns

      2:27
    • 31. Poor Conditional Clauses

      3:46
    • 32. Output Parameters

      3:00
    • 33. Comments

      3:13
    • 34. Prefer Positive if statements

      1:02
    • 35. Writing Clean Functions Conclusion

      3:17
    • 36. Common Architectural Design Smells Outline

      1:10
    • 37. Primitives Obsession

      2:50
    • 38. Violation of Law of Demeter

      6:49
    • 39. Temporal Coupling

      1:36
    • 40. Switch Statements

      5:49
    • 41. Refactoring to Strategy

      3:13
    • 42. Refactoring to State

      7:01
    • 43. Common Architectural Design Smells Conclusion

      1:37
    • 44. Functional Programming Extendibility and Immutability Outline

      2:16
    • 45. Programming Paradigms

      5:00
    • 46. Defining Functional Programming

      3:29
    • 47. Functions Are Everywhere

      2:42
    • 48. Why Functional Programming

      2:30
    • 49. Immutability

      6:59
    • 50. Immutability of Structs

      4:17
    • 51. Temporal Coupling and Immutability

      5:26
    • 52. Pipelining

      1:39
    • 53. Extending IDisposable

      9:08
    • 54. General Extensions

      10:23
    • 55. Extending StringBuilder

      10:36
    • 56. Primitive Obsession Abusing Extension Methods

      7:49
    • 57. Builder Design Pattern

      9:08
    • 58. Errors and Functional Programming

      2:58
    • 59. Handling Errors by Methods Chaining

      5:35
    • 60. Functional Programming Extendibility and Immutability Conclusion

      2:52
    • 61. DI Related Anti Patterns & Refactorings Outline

      1:57
    • 62. Control Freak

      7:22
    • 63. Hidden Dependencies with Service Locator

      4:08
    • 64. Temporal Coupling and Constructor Injection

      1:47
    • 65. Constructor Over Injection

      4:02
    • 66. Ambient Context

      3:39
    • 67. Facade Service

      2:58
    • 68. Property Injection vs Bastard Injection

      3:34
    • 69. Cyclic Dependencies

      11:34
    • 70. DI Related Anti Patterns & Refactorings Conclusion

      2:19
    • 71. Clean Unit Tests Outline

      0:53
    • 72. Singletons and Static Classes

      7:02
    • 73. Too Many Interaces

      5:32
    • 74. Reducing Interfaces

      14:02
    • 75. Testing Trivial Code

      2:59
    • 76. The Rule of Testing a Single Concern

      3:06
    • 77. More on Best Practices

      9:52
    • 78. Clean Unit Tests Conclusion

      1:08
    • 79. Clean Code and TDD Outline

      0:48
    • 80. What is TDD

      5:00
    • 81. Red Green Refactor

      4:16
    • 82. Three Laws of TDD

      1:42
    • 83. Reading Roman Numerals

      12:07
    • 84. TicTacToe

      36:17
    • 85. Continuous Testing

      3:57
    • 86. Clean Code and TDD Conclusion

      1:04
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

129

Students

--

Projects

About This Class

Learn how to write clean and maintainable code in C# as bequeathed by Uncle Bob. Learn how to perform refactoring in C#.

Learn how to design and implement types in C# so that the other developers won't hate you when using one of the types developed by you. It means you are going to learn how to write code of the high quality: readable, understandable and reliable.

Improve your knowledge in object-oriented programming in the context of clean coding and building types of high quality.

  • Learn how to give the best names for API members 

  • Learn all the tricks related to writing clean functions

  • Avoid common architectural smells. Get rid of unpleasant smells

  • Apply principles of functional programming: achieve immutability, remove side effects, extend types

  • Avoid smells related to dependency injection

  • Write cleaner unit tests

  • Practice Test-Driven Development

Foundations of building object-oriented infrastructures

Despite the fact that C# is a very rich on features language, it's very common to see poorly designed and implemented types in a real world. In fact, C# is one of the richest on features language among object-oriented languages in the world nowadays. But with great power comes great responsibility. It's challenging  to use all those features in a right way.

You probably have already heard the following well-known statement: most code sucks. Well, this course is all about how to produce code which doesn't suck.

Owning skills of producing a well-designed and well-implemented types is the prerequisite for the other developers to treat you as a real professional.

Content and Overview

This course is aimed at all the C# developers, from beginners to seniors. Topics which are covered in the course are relevant for all kinds of C# developers since all developers design and implement APIs. The topics complexity is very different. There are plenty of very simple topics, and at the same time, there are topics which require from you a solid C# background. There are plenty of code examples throughout this course, so you will learn both theoretical and practical material.

The course covers the following topics:

  • Meta Principles: DRY, KISS, YAGNI, SoC, CQS, PoLA, Encapsulation

  • How to give better names for API members and what naming conventions exist in the .NET platform and suited for C#

  • Common problems encountered by C# developers in the process of designing and implementing APIs: classes vs structures, creational patterns vs constructors,  poor naming, excessively long methods, output parameters and so on.

  • Common Architectural Design Smells such as Primitive Obsession, Hidden Dependencies, Violation of Law of Demeter and other.

  • Functional Programming: immutability, temporal coupling, pipelining, extending IDisposable, Builder Design Pattern, abusing extension methods, dealing with errors

  • DI-related anti-patterns: control freak, hidden dependencies, temporal coupling, ambient context, facade service, bastard injection, cyclic dependencies

  • Clean Unit Tests: singletons and static classes, excessive number of interfaces, testing trivial code, testing of a single concern, different best practices

  • Practicing TDD: definition, 3 laws, parsing roman numerals, continuous testing, implementing Tic-Tac-Toe

The list is far from being complete. The course covers a great number of topics. Enroll and start Mastering the Art of Writing Clean Code in C#!

------------------------------------------------------------

Keywords related to the course:

  • C# Clean Code

  • C# Best Practices

  • API in C#

  • Building API in C#

  • Clean Code in C# tutorial

  • Refactoring

Meet Your Teacher

Teacher Profile Image

Elias Spock

Chance favors the prepared mind.

Teacher

I'm thankful enough for that I love what I do.
I began my career as a postgraduate student participating in Microsoft ImagineCup contest.
I've been working with .NET platform since 2003. I've been professionally architecting and implementing software for nearly 7 years, primarily based on the .NET platform. I'm passionate about building rich and powerful applications using modern technologies. 
I'm a certified specialist in Windows Applications and Service Communication Applications by Microsoft.
I'm one of the coordinators of the MSK.NET User Group in Moscow.

"If it's work, we try to do less. If it's art, we try to do more." - Seth Godin.

What I can say is that software is my art.

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Promo: Hi. This is injury spark from injury spark dot com, and they'll be leading you through the course. I've been working with the dot net platform since 2003. I've been professionally architect ING and implementing software more than 10 years, primarily based on the DOT that platform I'm passionate about building reach and powerful applications using modern technologies. I'm a certified specialist in Windows applications and service communication applications by Microsoft, and I'm one of the co organizer's off the most kudos that user group in Russia. And here's my teaching approach. No fluff, no ranting, no beating the air. Steam your time course material is succeed. Yeah, comprehensive. All the important concepts are covered particularly important topics not covered in depth for absolute beginners. Offer my help on Skype absolutely free if requested. Take this course and you'll be said it's fine. Learn how to design and implement types in C shop so that the other developers won't hate you when using one of the types developed by. It means you're going to learn in this course how to write code of high quality, readable, understandable and reliable. Improve your knowledge in object oriented programming in the context of clean Cody and building types of high quality. Learn how to give the best names for a P I members. Learn all the tricks related to writing clean functions. Avoid common architectural smells. Get rid of unpleasant smells. Applied principles of functional program. Achieve mutability, remove side effects, extend times, Avoid smells related to dependency. Injection right cleaner unit tests and practiced has driven development. Despite the fact that See Shop is a very reach, all features language. It's very common to see poorly designed and implemented types in the real world. In fact, See Shop is one of the richest on features language among object oriented land, which is in the world nowadays. But with great power comes great responsibility. It's challenging to use all those features in the right way. You probably have already heard the following well known state. Most code sucks Well. This course is all about how to produce cold, which doesn't suck. Owning skills of producing a well designed and well implemented types is the prerequisite for the other developers to treat a serial professional. This course is aimed at all the sea shop developers, from beginners to seniors, topics which are covered in the course are relevant for all kinds of social developers. Since old developers design and implement AP ICE, the topics Complexity is very different. The Reese plenty off very simple topics and at the same time there are topics which require from us on Etsy shop background. There is plenty off code examples throughout the scores, so you learn both theoretical and practical material insured. The course covers the following topics. Mata principles. Dry keys. Yeah, Agni sock Sick US cola and encapsulation. How to give better names for a prime members and what naming conventions exist in the Dark Net. Platform and Suited Forces shop common problems encountered by sea shop developers in the process of designing and implementing AP. Eyes, glasses versus structures creation, ALS patterns versus constructors poor naming excessively long methods out with parameters and so common architectural smells. Sanchez. Bring me to obsession. Hidden dependencies violation off lofty meter and other functional program, including a mutability temporal company pipeline ing extending I disposable builder designed pattern abusing extension methods and dealing with errors. D I related in type betters, including control freak, hidden dependencies, temporal couple, Ambien context facade serves bastard injection, Cycling dependence is and dollars. Clyne unit tests, Singleton's and stated classes, excessive number of interfaces testing, trivial call, testing of a single concern and different best practices. Practicing TDD, including definition three laws off TDD, Barcelona Roman numerals, continuous testing and implementing a tick tick toy game the least is far from being complete. The course covers a great number of topics in role and start mastering the art of writing clean code in C shop. 2. Introduction: Hi. This is ingenious bark from engineers bag dot com. And in the introductory lecture, I want to explain why we need to write clean and maintainable code. According to Ken, back one of the greatest minds in programming software development implies the following statements. Developers read code way much more than write it. The development process never stops. It can only be frozen for some time modification and maintenance. Often existing application costs much more than writing in your own. A code reader has to understand both overall concepts and implementation details. Sometimes he need to concentrate on concepts, sometimes on details. According to Yordan and Constant tiene. We need to develop software in a way which allows to minimize its overall cost where overall cost equals development cost plus maintenance cost. In this formula, the heaviest part is maintenance Cost. This is because of maintenance is a highly error prone process, which takes much time Understanding off the existing code base is the most costly part here , so the maintenance cost equals cost of understanding, plus cost of changes plus cost of testing and plus costs off delivering, taking into account what I said about maintenance costs a logical strategy would concentrate on decreasing the cost off understanding in the maintenance phase. Therefore, we need to keep code bases esque Llinas possible, and these course is entirely dedicated to practices aimed at writing clean code before moving to concrete practices off writing clean code, we're going to learn about matter principles, the fundamental principles on which all the other principles are based. The next section, the 1st 1 opens up the course where we are going to talk about programming matter principles. 3. Meta Principles - Outline: Hi. This is Injurious Park. And in this section we're going to learn what the matter principles are. We refer to the principles we're going to talk about in the section as to matter principles because they're the roots off all the other more concrete principles adhering to which we're actually trying to conform with the matter principles. We will start from the dry or don't repeat yourself principle. You learn the definition and the most common smells off violating the dry principles. After that, you learned the keys or keep it simple. Stupid principle. Here we're going to talk about simplicity and complexity, accidental and essential complexity and how to achieve simplicity. The next Met the principal we're going to talk about is the Yagi or you ain't gonna needed principle. It is related to the needless complexity smell and concerns the anticipations off upcoming features. We will look into practical problems which will face and what are the consequences off implementing features we actually don't need. After that, we're going to talk about the sock or separation of concerns principle. This principle underlies, in a sense, all the solid principles. Separation of concerns is very important for achieving well maintainable applications. You'll see the most common ways off violation. The separation of concerns principle command query separation principle makes easier to reason about the code. Separately, we will talk about the principle off least astonishment. In the end, we will touch the topic off information, hiding and encapsulation. By the way, I'll use the word principle sometimes instead of matter principles in this section for the just for the sake off saving some time In the next lecture, we will learn about the dry principle. Let's start. 4. DRY: this lecture is titled Dry Principle. A substantial number of box in software are caused by repetitive code. If you have 10 functions which do the same, and you need to change the behavior of such a function, you'll have to modify all 10 functions. So the definition off the dry principle was formulated in a famous book, The Pragmatic Programmer by Andy Hunt and Dave Thomas. And it sounds like this. Every piece off knowledge must have a single unambiguous representation in the system. This principle concerns all the different aspects off software it can be applied toe any programming code or database schemers or anything else, including documentation of the most common ways of violating the dry principle are the following magic strings or any other magic values, duplicate logic in multiple locations and repeated give than logic or multiple switch cases scattered throughout the code base? Let's look at examples. Look at this example. You don't get the response from a device, then we compare the results with 188. Such magic values tend to spread over a class which Inter operates with the device. This is how duplication appears. A side of the duplication who knows what 188 means toe understand the meaning of the code? We need to read the documentation. Wouldn't it be nice to define a constant with a meaningful name? This constant can now be used everywhere we need. It is now clear what 188 means. It means that there is no connection with the device. Here's another example. The similar situation here We see that magic values started to spread aside from the fact that it is absolutely impossible to understand what's going on here. And the dip location may lead to unfortunate consequences. For example, if one of the duplicated values is going to be changed, then you're going to change that values everywhere. It was used to fix the problem. We can apply the same technique defining constant values that become the single sources off change. I defined constant values only for duplicated values, but most likely I would do the same for all the other values. Now it's apparent that commands at first initialize a device than send a command, and after that, closed the device. Here's the same example. What's wrong here? We fixed the duplicated magic numbers, but what can be enhanced. In addition, we have the duplicated logic here, and it is not to speak that there can appear 10 new methods with the same pattern off sent commands. Look how we can reflect her. This coat I extracted a method which removes the duplicated logic by taking the responsibility off, wrapping actual commands by initialization and termination. The benefits might be not others, but in case off more than three methods, benefits would become of this. This is a simple example of duplicated logic. There is much more interesting case related to duplicated logic. The question is, Is that true? That duplicate logic is always a bad thing, and then, sir is quite interesting. Imagine that you develop three applications which belonged to the same domain. Logically, such applications would have significant similarities in the functionality they implement. This fact logically leads to a natural desire to create a shared library, which contains pieces off functionality. That is the same for all the three applications. As you remember, every piece of knowledge must have a single unambiguous representation in the system. So if you implement the same functional knowledge thrice wants for each application, then seemingly you violate the dry principal? Yep. Now let's consider the following case. From my practice, we had three applications which shared the logic of the following function. Here we have a class with three properties and the function which checks give the card is valid for some time. This function worked well for all the three applications, but one day one of the applications changed. The requirements is required to check first name and less name as well. Implementing another function for that particular application would be considered a violation of the drive principle. So a decision to introduce a bull flag was made. And here is the second version of the same function. Cool. We preserve the ability to use the same function all over the code base. Peace has settled down and we continued our work for some time. Everything was okay until one day when Boss said that there is another requirement from the third application. The third application now can allow ideas to be longer than 10 characters to preserve the ability to use the same functional over the code base who introduced a new Boland flag. Here is how the new version of that function looked like. Yeah, yeah, I know this function turned into riel Mass, and this is only the beginning. If you start to apply solid principles and all the best practices to avoid this mass, you'll often end up with a separate implementation for each application. Often not always. But often it's better not to share your logic between applications. It's better to grow that logic separately, at least until you get absolutely sure that you can merge the same implementations. Indeed, there are cases when we are 100% sure that particular business logic will never change. Or the probability off changes is extremely low. If semantic is different, don't merge the code, which looks like duplicated code. Let's look at another case when duplication is actually not a duplication at all. Here's an example, by the way, this example is also from my own practice. Questions are just named differently. You have two classes which were president, different devices. Both of them have the same data properties. A junior developer from our team decided that this clearly violates the dry principle, so he decided to extract the same data properties into based glass. He came out with the falling reflected version of this code. Here's the device glass, which contains the duplicated properties. Now all the devices will inherit from the glass and the dry principle is Matt. Unfortunately, that was a bad decision and there are several reasons. The first reason is that it's hard to believe that all the devices will share the same properties. I'm pretty sure that L S P is violated by this her factory. The second reason is that now we have a strong coupling between based class and inheritors . And actually, I don't see where the benefits of such inheritance friendly. It's a very rare case when inheritance off data is a good idea. You know, all languages, objects are comprised of public functions. The data should be hidden. The third reason is that the first intention was wrong. There was no any duplication. The fact that toe objects have the same data properties doesn't make them similar. What makes the object similar is their behavior. So there's no need to couple objects which have different semantic. Vladimir Horcoff even came out with the notion off utility inheritance. Vladimir Horcoff, there've uber off this video course even came out with the notion off utility inheritance, this example demonstrates exactly that evil technique. On the slide, you can see the reference to the block bossed about utility inheritance. Take a look at this code here have an enumeration off shapes and the Visualize ER class, which defines toe operations. There are only two operations just for the sake of simplicity. In the real world scenario, there would be many classes which used that in, um, orations and dozens off methods filled by switch cases. So which cases on the same in admiration, which are scattered all over the code base, is one of the worst nightmares. You may senior life when some kind of the behavior aspect changes regarding one of the enumeration of Alice. You have to find all the places in the system where switch cases are implemented and change the corresponding chunks of code. If you add a shape, you have to find all the places with switch cases and modify them, adding cases for that new shape. This is a true evil duplication. How to fix the problem. The open close principle is answer. You can define the base glass and turn the enumeration values into inheritors represented by classes. If something changes, you have a single place where you need to make that change. Now the client code can just rely on the base shape glass. No switch cases scattered all over the code base. Remember that repetition and logic calls for abstraction. Great. In the next lecture, we will study the kiss principle. 5. KISS: this lecture is titled Kiss Principle. Have you heard the statement off Albert Einstein? Make everything as simple as possible, but not simpler. This statement is the essence of the kiss principle. Kiss means keep it simple, Stupid. The more a system complex, the more possibility that it can break. Therefore, simplicity should be a key goal in design and on assessor complexity should be avoided while young me you ain't gonna need it. Principle is about removing an assessor coat kiss is all about how to make the implementation as simple as we can. So the statement of this principle is a simple solution is better than a complex one even if the solution looks stupid, the principle is deeply philosophical indeed, just trying to come up with a true definition off the simplicity, how to define and measure the simplicity the straight forward definition would be the following simply cities the state of quality of being simple. Don't you find such a definition not were helpful? I do. What does it mean to be simple? Seemingly that the only way we can treat the simplicity in software is that something which is easy to understand or explain, Can be considered simple. In contrast to something complicated. It's very hard and sometimes even impossible to come up with a simple solution that solves a difficult problem. The complexity off implementation tends to grow along with growing number off requirements , so the feeling off simplicity is relative. The main technique we used to struggle with complexity is the decomposition, and by the way, the composition is the aspect, which is strongly related toe almost all the solid principles. Adhering to the SRP, we apply the composition to the coupled objects or modules, confirming with the gossipy not always but often involves the composition as well, especially when we need to create a new type toe isolate source of change into face segregation. Principle is all about the composition. Dependency in the version is all about making the system world too composed. The list of substitution principle is mostly about how to avoid bet decomposition so of the soul. Principles are aimed at achieving solutions as simple as possible. On the other hand, abusing solid principles always lead toe on accessory complexity. This is the true manifestation of the unity and struggle off opposites law. It resembles me, a herb called value. Aaron Valerie in has sedative qualities, So when you take the Lear in Aceh medicine, you expect to become calmer at the same time. It's a very well known fact that if you take too much off while you're in, it will cause the feeling off anxiety. The fact will be the opposite. The problem off simplicity relative nous leads us to two related notions. Accidental and essential complexity. I said earlier that complex systems are actually complex and you can do nothing about that . You can't implement the software of bank system and expect that it will be a simple as a solitaire. The complexity imposed by the domain itself is called the essential complexity. The essential complexity cannot be reduced by any means. The only way how essential complexity reduces is when the domain rules change in the direction of simplicity. Unfortunately, you barely can enforce such changes. Accidental complexity is the complexity off our solutions, which are intended to solve the problems off the domain we are responsible for. The accidental complexity is the developers. The design of the software optimization are all related to accidental complexity. Kiss is fundamental philosophical principle, so we can mark out the following rules, which of course, are not dogmas. I prefer composition over inheritance were possible. Stick with if Ellison's, which gave statements until you see that you need to introduce polymorphism, avoid bringing to optimization in 90% of cases. Slower solutions work enough fast Exceptions from this rule is when you know for sure that you are working on a very complex software, one of the main aspect of wishes. The performance when the performance is absolutely critical. Smaller glasses and smaller methods are batter. The best method is a one liner, Google. For the technique, which is called extractive you drop, which is about methods re factoring. Don't rush to extract utility classes for private methods which are used from a single place within the class. Leave it s cities until there are other parts of code. Will require that method as well. Don't write perimeter arised. General methods prefer methods which solve a specific problem. Divide and conquer. This is a principal aimed at solving complex problems. Divide the problem into smaller problems and solve them one by one. Strive to avoid comments. Comments mean that you failed trying to express the intent in programming language, right brother types, And don't be afraid to throw them away. Keep the number of fantasies which solve a problem roughly from 5 to 7 humans. Mind is not good at keeping in memory. Modern seven things simultaneously, Constantly working. Simplifying your code base. Uncle Bob Martin even suggest a rule that before making a check in, you should always ask yourself whether the code base is better than it was before you checked it in. This is the rule off a Boy Scout. Optimization is the main excuse for writing complex code, but strive to keep the amount of such gold closer to five or 10% of the code base, not more. Optimize only if you're absolutely sure that there is a performance problem. Don't measure the performance by your I rely on special tools for tracking the performance . Remember that there are two values off software. The 1st 1 is that software should work correctly, and the 2nd 1 is that the software should be designed well, and the 2nd 1 is much harder to achieve them. The 1st 1 in most cases. The next principal we're going to talk about is the young principle, which stands for u N Gonna needed This principle is similar to the kiss principle. In the next lecture, you find out what is the difference between these two principles and what Yogi means in practice? 6. YAGNI: this lecture is titled Yardeni Principle. The Power People are always looking for ways to make all around them as much powerful. It's possible developers are also people, and they also tend to make all the program code as general as it can be. For example, when a software developer has a task to create a simple library for generating simple income outcome reports, he will allow the whole general purpose library for generating any possible financial reports. I need to parse one key value pair from a custom buying a reformer. What am I doing? Correct. I'm writing the whole damn sparser with handling all the possible cases. Yeah, Agni means you ain't gonna need it is all about avoiding over engineering. Do you remember the smell cold? Needless complexity? Yeah, Detail says that we should avoid this smell. Do you remember our talk about anticipation of upcoming changes? Anticipating upcoming changes, developers start to introduce points of extension. The problem is that it might happen that all those points of extension will never be used. Points of extension have their cost. They're not free. They make systems more complex and therefore harder to understand you. Agnese deeply philosophical principle. There is no well defined criterion, which allows to measure the young neatness of the system. If you look at Wikipedia, you'll see that Young is a principal off extreme programming or Experian shirt that states programmers should not add functionality until deemed necessary. As a type of federal software development, extreme programming advocates frequent releases insured development cycles, which is intended to improve productivity and introduced checkpoints at which new customer requirements can be adopted. XP, co founder on Jeffries, has written, Always implement things when you actually need them. Never. When you just for see that you need them, you have knees. The principle behind the XP practice off do the simplest thing that could possibly work. Another interesting concept, which is also strongly related to Young Me is called Worst Is Better. Also known its New Jersey style regarding software development. Worse is better implies a model of software design and implementation, which has the following characteristics. Simply sitting, the design must be simple, both an implementation and interface. It's more important for the implementation to be simple than the interface. Simplicity is the most important consideration in the design correctness. The design should be correct in all observable aspect, but it is slightly better to be simple than correct consistency. The design must not be overly inconsistent. Consistency can be sacrificed for simplicity in some cases. But it's better to drop those parts of the design that deal with less common circumstances than to introduce either complexity or inconsistency and implementation completeness. The design must cover as many important situations as is practical. Well, reasonably expected cases should be covered. Completeness can be sacrificed in favour off any other quality. In fact, completeness must be sacrificed whenever implementation simplicities. Joe pard ized consistency can be sacrificed to achieve completeness if simplicities retained, especially worthless is consistency off interface. There is a problem with all the matter principles. The waste we can follow them and apply on practice are vague. The only thing we can do is to discuss the young name or details. But in band, our discussion will also contain such hard to measure things like complexity of software. For example, consider the following sentence from a block off Martin Fowler. This is a good sentence, which makes clear the meaning off ya guinea, but it's still not so easy to apply on practice Here's the sentence. If you do something for a future need that doesn't actually increase the complexity of the software, then there is no reason to invoke your acne the complexity off the software. But the question arises. How the hell am I going to estimate the complex nous before looking at a couple of examples of applying the principle? Also want to stay that you shouldn't adhere to any principles blindly. For example, if you blindly adhere to the young, me, you'll end up with these organized code and will face sooner or later the necessity to perform a massively work. So you have to heavily rely on several other practices, such as continuous re factoring continues, automated unit testing and continuous integration to avoid negative consequences. The Agni depends on supporting practices, and this is stated in the original definition. In extreme programming. Let's consider two cases when we can apply your Agni, I'll call the first case of high level one, and the second case I'll call a low level. Imagine the situation. A team is working on the payment system, which Inter operates with many devices such as going dispensers bill except er's and so on There can be many models off any type of those devices. Working on a current version, you need to implement a driver for Inter operating with models e off a bill dispenser. At the same time, a project manager expects that in four months they will need to support the Y model off a bill dispenser. It's a temptation to implement that expected model in barrel with Z Motile to avoid task switching in the future. And by the way, it would be great to say to Boston the future. Hey, we'll write it down it when the time to implement the white model comes. Deciding to implement such presumptive features is a classic violation off the agony principle. Do you realize the possible financial wasted in the case that motile will never be needed to be implemented? The cost of Butte is comprised off all the efforts spent on analyzing programming and testing this now useless feature. Okay, imagine that the project manager was right about that feature. Do you think that there is no cost of such a decision? The thing is that implementing that expected feature you still time, which could be spent on other really needed features. This is a cost off delay, since other features will be delayed. The delay will be equal to the time spent on implementing that expected feature. And this is not to say that you initially could be wrong and that feature could never be needed. And this is not the end and other cost of implementing features. We anticipate being in demand in the future by using a crystal ball for fortune telling. Is the coast off Kerry? Very often, Additional code makes the system hard to understand, maintain and modify. So if you also need to implement a really needed feature, which depends on that code related to devices, you likely spend more time to implement it. And this is not then there is a very unfortunate scenario when the necessity off a feature is correctly forecasted. But the implementation of the future is wrong. When the times comes and you realize that a feature is implemented, not us expect by clients. You'll face yourself in a situation when you have a wrong feature, sometimes completely wrong, and you have to make a hard decision whether to throw away the current implementation and er implement the feature completely from the ground or to invest resources into the repairing of the existing run implementation. This is a very hard dilemma. It's hard to estimate whether you should rewrite the feature or to repair the existing one . Martin father came up with a great skin, which demonstrates all the potential problems related to Young a violation. The example we discussed is the high level case and, yeah, Agnese much simpler to apply on this level, though, of course, even at this level, sometimes we make mistakes. Another case is low level, and it concerns every day choices we make in the process of coding. For example, imagine that right now you're writing a function within a class which needs to parse a number from a custom string retrieved from a plastic card. You basically have two choices. One is to just implement a separate function, which passes that string within that class you're working on right now. The second choice and this is the way which was by default very often is to implement a passing function and extract the utility class, which contains the passing function. This sounds logical. Seems we may anticipate that our colleagues might also want to use the feature off parsing from other parts of the code base. I don't want to answer this question in relation to this particular case. I want to answer the question. Generally, there is a simple algorithm which helps to make a right decision in the coding process and in such situations. First, ask yourself if the function or a future is needed to be implemented right now. Events were is yes, then implemented. If the answer is no, ask yourself another question. How many efforts will it take to implement that function or a feature in the future? In the case, it will be required. If the answer is, it will definitely be very simple. Then keep all the things as they are. Don't introduce anything additional. If the answer is, it will take enormous amount of time to write many things to tweak the design to make it enough supple to introduce the feature, Then consider to perform summer factories, which allow you to avoid massively writings in the future. Remember that neither gile practices nor any matter principles imposed the idea to avoid planning. On the contrary, you should always carefully plan what you'll need in the future. And what resources and efforts will it take from you to meet new requirements again? It doesn't mean that you have to perform a big up from design, but it owes. Doesn't mean that you have to forget about planning the goal we want to achieve. Applying. Yeah, Agni is to save some time. Please don't apply. Young me to re factory. You need to perform a factory to enable Yanni. I hope now you better understand how to achieve the Holy Grail with algorithm. I laid out in this lecture. Be ready to fail. Applying the Agni principle, It will take some time to get enough experience and invent. Your perseverance will pay off In the next lecture. We will take a look at the separation of concerns principle. 7. SoC: This lecture is titled Separation of Concerns. Separation of Concerns or a Sock and Short is a principle which were actually discussed in the section off Single responsibility principle SRP in soccer strongly related. Basically, soccer is a principle, which means that we have to separate different concerns into different modules. Adhering to sock allows to build modular systems. The difference between soccer and SRP is that soccer is mostly applied at the highest level . The value of separation of concerns is simplifying development and maintenance of computer programs. When concerns are well separated, individual sections can be reused as well as developed and updated independently. A special value is the ability to later improve or modify one section of code without having to know the details off other sections and without having to make a responding changes to those sections. Most of the time, you can treat SRP and sock as the same concepts, and you can use them interchangeably. Here's the list of concerns we must often face in enterprise software development. You are business logic, presentation, logic and database. Imagine a room where all the things are scattered all over the floor will be simple. To find a particular book there. Wouldn't it be easier to keep all the things separate books on the shelf, toys in the boxes and so on? The same we can say about programming and separation of concerns. If you enter tangle you. I was business logic. Then it will be harder for you to maintain all the mass, find anything you need, their change, anything you need to change and so on. There is a thing which can ruin our best intentions regarding separation of concerns. This nasty thing is called licking abstractions with separate concerns. By playing the constant off encapsulation Onley by encapsulation, we can protect objects and hide their internals. Unfortunately, abstraction stand to leak, especially in complex AP eyes. There is a great number of popular cases off licking abstractions. One of my favorite example. One of your model or, in other words, presentation logic knows something specific to you. I here is an example when a view model exposes a property of type collar, this is a classic example when presentation logic is incorrectly implemented from the sock point of view. To fix this example, we need to remove the property and expose another one which just returns a bowline you are on its side should decide what color to peak. This is not a concern off a presentational layer. Another good example. When the main logic operates with unique identifiers stored in a database. In such of the case, a concern of persistence is mixed with the domain logic. Domain logic should be agnostic regarding any persistence mechanisms, actually there in turns off examples of flicking abstractions. Keep in mind that layers, which represent different concerns, should be isolated from each other in such a way that none of them should know about any intrinsic details of each other on the other side. I must admit that there can be exceptions from this rule from the perspective of Domine Dreamin designer Didi Dean shirt writing start procedures, which implement any kind of business logic. For example, they perform validation and mutation of data is considered a violation of separation of concerns. Principal At the same time, unfortunately, running directly, surgical procedures are way much faster in certain scenarios than performing operations through an object. Relational mapper such as entity framework, treat such cases as exceptions. In the next lecture, you'll learn the sick US or command query separation principle 8. CQS: This lecture is titled Command Query Separation Command. Query Separation is a principal off imperative programming. It was devised by a but admire as part of his pioneering work on the Eiffel programming language. It states that every method should either be a command that performs in action or a query that returns data to the cooler, but not both. In other words, asking a question should not change the answer. Generally, we can divide functions into two major types. Functions which perform commands and functions, which perform a query and return a result. Often beginners mix squares and commands. As a result, they create functions which perform a command and return a result off acquire. At the same time. This is almost always a bad thing. Consider an example. What color is asking here? Was Logan attempt successful? Maybe true means that a user has already been locked on. It's hard to tell looking at the function signature. The thing is that it's impossible to express the meaning off a boudin result by the functions name. The problem is not in the bad name of the function, but the problem is that a command is not separated from a query. The command logic and queer logic are mixed in the same function. So sick. US is one of the core principles which helped to design better AP eyes concerning this example. It would be better to roll out a function which implements a command and one or more functions which implement queries for example, like this by the names and signatures off these functions. It's clear what they mean and what they do. In other words, these functions are honest that they don't imply something hidden and they don't lie to a caller. In the next lecture, we will look at the law off dean meter. 9. PoLA: this lecture is titled Principal Off Least Astonishment and other basic Principle, on top of which a great number of Father Prince will stand is the principal off least astonishment. This principle states that a component off a system should behave in a manner consistent with how users off that component are likely expected to behave. The following principles and techniques are based on the principle off list astonishment. And, of course, they help to conform with this principle. Full safe. A p I command query separation in mutability designed by contract and now prevention and many others. Look at the following example. We have a reporting class with two methods brings report a and print report. Be and this code snippet works fine. But if a client changes the sequence of this calls like this a database connection error of yours. The thing is that a database connection opens at the beginning of the bring to Reppert a method and closes at the end of the print Reppert be method. This is a simple example, which has a strong smell of temporal coupling where the root causes the side effect which is hidden from the client making the very astonishing from the client's point off view. Humorously, we can conclude that the metric which reflects the factor off astonishment often FBI is the number off shouted WTF is permitted. Put simply, the principal off list astonishment means a design should both great expectations and fulfill those expectations. It should do pretty much what people expected to do. Another example of an eight b I, which astonishes its clients, is the guy over the standard Java stack. Standard stack implementation in Java exposed Bush and pop methods, and in addition, it exposes the ad method inherited from the vector class God's sake. What the ed math it is supposed to do where the item is going to be added. It's absolutely astonishing. I was almost grand when I faced the day by for the first time. Here's an example from the sea shop. A user would expect from the at least that it allows toe add items. Unfortunately, even the Sea shops type system is not ideal in this case. They're not supported. Exceptional the throne. In the next lecture, you learn what is the information hiding and encapsulation, and what is the difference between them 10. Encapsulation: the question. What is encapsulation and information hiding and what is the difference between them is a very common question. At interviews. There are many false, widespread opinions and statements about these terms. Because of that, a great number of developers, even intermediate developers, are confused when they need to talk about encapsulation and information hiding. You have to understand these concepts not only because you need to pass an interview, but because you want to be a better developer. At least I hope you want to. I like the definition off encapsulation given by Mark Semen, the author, off bestselling book dependency injection in that that the definition from Mark Semen. This is what encapsulation is all about, exposing a solution to a problem without requiring the consumer to fully understand the problem domain. That may sound too broad, however, This definition is great and defines encapsulation precisely to imagine what is encapsulation. I'll give you some examples. If you have ever worked with WP F or Windows forms or Zamarripa, then you should know that to draw controls on the screen, you don't need to actually draw them. You just put controls on the designer so office and everything is done seems very simple. But there is a town off intricate details of how toe actually render that control. There are 10 layers hidden behind that control. You drop on the designer Sofus. The framework encapsulate all the stuff related to building your eyes. You don't need to understand the internals off those frameworks to use them, achieving the goals you have first of full. Try to look back and answer to the following question. Do you build your applications on top of reusable components? I'm sure on 100% that you answered. Yes, I do. Of course you do. If you program on Java or C shop than your applications stand on top off a whole damn framework. And the following question is, do you find yourself reading the source code off that reusable components? If it's available on a regular basis, most likely you don't from time to time. We need to read the source code of BCL, for example. But that's a rare case. This is because those components are encapsulated. They allowed to use them without digging their internals. We don't need to understand the kitchen off reusable components to use them this is what encapsulation is. Encapsulation allows to reuse components without understanding of their internal implementation. Encapsulation is based on two major concepts. Information. Hiding and in variance protection. The class must hide the information it encapsulate in order to protect it against naive users so that the code should be a foolproof. It should be protected from a stupid user. Wikipedia defines information hiding like this. Hiding the internals off the object protects its integrity by preventing users from setting the internal data off the component intern invalid or inconsistent state. We always strive to hide that information, which is irrelevant for clients. When a client sees what it doesn't need, it makes more difficult to understand such an A p I so encapsulation is a fail safe mechanism. At the same time, encapsulation doesn't imply hiding off complexity, saying that I mean that the intrinsic complexity off a problem the main rarely can be properly hidden. For example, the problem domain off dates and times is extremely complex. However, BCL developers implemented the date time structure, which hides all the complexity off the problem d'Alene. As a result, it's easy and convenient to work with daytime type unless you face the complex cases when you need to handle time zones. This is where daytime type fails to do its job. It fools its users, and they start to draw all in the complex details and ben implementation off the daytime time. If you want to learn more about the problems of daytime, take my course Dayton time fundamentals in dot net and Sequel server. So encapsulation is not about hiding complexity but, conversely exposing complexity in the fail safe manner. Another part off encapsulation concerns the so called in variance in variants are the statements that have to stay true in each moment, often object existence. For example, we have a class that represents a human being. A human being has the age, so the class has the corresponding property. In such a case, one off it's in variance could be described by the following statement. A human beings age has to be greater or equal to zero and less than 160 in any moment. The state of the human beings instance has to be correct, preserving the encapsulation by defending the in variance Look at the example off a poorly encapsulated class. Here it is. It might seem that this is a silicon example, but I've seen a lot of such gold basis. Off course. This is the worst case, but even one AP I member implemented badly can lead to serious unfortunate consequences. What's wrong with this? A. P I look at the pace celery method. Why does it return a string value? Is it a code off response? Is it a customer I d return? Who the hell might know what can be encapsulated by string value? It takes the amount represented by string. What is expected here, a decimal or what may be an integer look. Further, the get customer method returns void toe. Understand how this method returns a customer, a client Off the safety I has to know about the customer received event and the last one remove customer method. It returns an integer again. Anything can be represented by an integer value. In such a case, I've seen once how a C programmer used integers to return bulletins as ones and zeros in Seasia up. Yes, I've seen even such a scary trash look at how this code might look like Here is the pay celery, which returns void and accept decimal. Everything is understandable. Now it is a command which accepts the money value in decimal. Another option is to return a result moment, which is out of the scope of this course. If you're interested in building robust AP eyes regarding errors with using the result moment considered to take my course a p i N c. Shop the best practices of design and implementation on you Timmy, another method get customer now returns a customer. Everything is quite clear. Another option is to return. And maybe of customer maybe is also so cold moment which is out of the scope of this course . You also can learn about it. In my course I already mentioned they remove customer can either return the void or a result. We use a result moment to explicitly state in a signature that the operation may fail If it returns void. It means they're the operation is successful. Always. This is an example off a good, clear FBI. The intention off encapsulation is to protect the in variance by making invalid states impossible. Command query separation principle is one of the most important principles related to encapsulation. And then I want to joke that you should always remember that you should write code so that the reader off your code might be a psychopathic mass murder. Who knows your home address? Sleep well, my dear student. Okay, let's briefly look at the practical moments off this topic in the next lecture. Unfortunately, we can talk about this very important topic too long, since the whole separate course can be dedicated to encapsulation. Let's pretend that we need to implement a type which represents a character of that character. Has a name, health and speed sounds like a game, but that doesn't matter. Actually, the example is synthetic, but enough good to explain the concepts. The in variance imposed by the problem domain are the following. Health has to be greater or equal to zero and less or equal 100. Speed has to be greater or equal to zero end. The last than or equal 25 name should not be empty. We also have the following requirements. A character can move and respond to some requests like Is it alive? Is it running and so on? Well, the task is Britta symbol. Let's implement it with proper encapsulation. At first, let's define three fields and one property. Health, speed and engine, which managers all the rendering process and the property cold name. - Right now, anyone can construct an instance off this class and by default the name will be. Now what violates one of the in variance, an object of type character that has no name is in invalid state. We need to protect the in variant. For that, we can rely on the one of the best ways to protect in variance a constructor. - Now the default constructor is no longer available for the users. A user can only create an instance by our constructor, which takes three parameters, and it doesn't allow to pass now or white space as the name of the character. However, health and speed are not protected. Anyone can use our constructor passing negative values as health and speed. What violates the in variance imposed by the problem domain? We can either right the defense here in the constructor or we can encapsulate our fields by properties and defending variance there. Since I know that there will be other places from which speed and health are going to be modified, I'll prefer properties. - The in variance now are protected. There is no way to get dr and instance into an invalid state. Let's exposed to queries notice that clients cannot modify the state of health and speed directly via properties or fields. Direct access is hidden from the clients. Very often, clients cannot even get the current value, since there is no getter just a row field. These two methods do not expose data to clients as well. They encapsulate some logic that defines who are alive and who are running. Clients do not see the logic that they can only use the properties, getting the results as he's so to speak. A client doesn't set speed directly, and we also want to expose method of damaging notice that clients do not incur any damage directly. Everything is encapsulated. The rendering engine is completely hidden from the sight of clients. This is how insurance encapsulation works 11. Meta Principles Conclusion: in this section, you learned that every piece off knowledge must have a single unambiguous representation in the system. And this is the definition off the dry principle. The most common ways off the dry principal violation are magic strings or values. Depp lick it logic in multiple locations repeated if their logic or multiple switch cases scattered throughout the code base. You learned that Kiss implies that simplicity should be a key call in design and a necessity. Complexity should be avoided. The main technique we used to struggle with complexity is the decomposition. The complexity imposed by the domain itself is called the essential complexity. Accidental complexity is the complexity off our solutions, which are intended to solve the problems of the domain. Young is all about avoiding over engineering. There is no a well defined criterion, which allows to measure the ugliness over the system. Yeah, he's a principal off extreme programming that states a programmer should not add functionality until deemed an accessory. As our Pete and Sock are strongly related. Basically, separation of concerns is a principle which means that we have to separate different concerns into different modules. Adhering to sock allows to build modular systems here is the least of concerns we most often face in enterprise after development. You I business logic, presentation, logic and database command, query, separation or seek us is a principle that states that every method should either be a command that performs in action or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. The principal off least astonishment underlies a great number of other principles and two creeks. These principle states that a component off a system should behave in a manner consistent with how users off that component are likely to expect it to behave. You learned that information hiding and encapsulation are different concepts. Encapsulation is intended to protect the in variance information. Hiding is one of the ways we chief proper encapsulation. 12. Names Outline: Hi, This is engineers Bach, and I'm glad to see you in the second module. Correct naming is extremely important from the perspective off readability and the sick consequence from the perspective. Off maintenance maintenance is especially important in the field of enterprise development . Naming rules were different in the past. A decent amount of time passed away since AL goal was in use. Naming in Pure C and C Sharp are very different, and there are reasons why this is so. The thing is that modern, powerful PC's and managed languages with meta data make us able to develop very powerful ID's, which endow us by great power. We can rename variable and all dependent declarations in a second just by using the corresponding feature of the I. D. You can extract glasses into faces and make other effect A rings. A decade ago, you couldn't imagine such a power. That's why naming conventions have changed in this module. We're going to look at general principles off naming you learn how to reason about choosing one name or another. We're going to look a naming convention specific for the dot net platform. Okay, fine. Let's die off a little bit deeper 13. General Principles of Naming: the first, and the most important rule is that you have to give intentional, revealing names. You give a certain name once or maybe twice if it was renamed, but you'll read the given name most likely hundreds of times. This means that you have to give names, which reflect the intention off a member. If you declare a variable named Z, which really implies a zip code instead of zip code, then how we're going to understand what you meant. Giving that name and months ago, you have to read all the code which is relevant to that variable and logically deduce its real meaning. Sometimes it is simple to find a good name, and you can give it within a couple of seconds. But sometimes the process off finding an appropriate name can last much longer. Anyway. The first rule is, to his intention, revealing names. The name see reveals nothing. The name customer reveals the meaning off a variable variable declared like This ain't age is also not a good choice. Take a look at this variable. Why do you think this is a bad name? You can pause the video and think a little bit right just looking at this declaration. We can't say what unit off measurement is implied by this variable, the aging years or days. So it would be better to name that variable s age in years or aging days. Some names may look like very informative. For example, in Pearl, the length function called with a string passed in as a parameter returns the number of characters in that stream logically, in the same pearl of the length function called with an array passed in S A parameter returns. What do think? The number of elements? Nope. It returns the number off array dimensions so that function returns one from the one dimensional array. No matter how many elements are stored in it, this is what I call this information. A function should do what is expected from its name. Different meanings should not be expressed by the same or similar name. This is a common case when developers come out with similar names for different domain concepts. After that all the way along, all developers will misuse similarly named members Your writing code for humans, not for a compiler. Put that in your pipe and smoke it for the sake off a better readability. Follow English grammar rules. For example, the name horizontal alignment is better than the alignment. Horizontal and can scroll vertically is better than scroll herbal. Why off course? You should apply this rule wisely, so don't start to include everywhere air and their articles. Don't give a name to a variable such as the counter. Instead, just name it counter. Don't give such names like Jean W, V, W E or G W R sp. Even if this is meaningful from the domain perspective, express the demand concept in the pronounceable way. If you're not a native native, language is not English. Then don't try to program using your native language. I can name a variable ist collision store in Russian. What means in English count. Use English as the language for naming all the members. Please forget about the Hungarian notation. We live in the 21st century. Our I DS are very powerful. You just don't need to add those junkie prefixes to your member names. If a variable is off type end, then don't add I before the name. For example, I underscore Count. Just leave it as count when you hover The mouse pointer over the variable name. It will show you it's type. Don't add graphics A for local variables, for example, for function parameters. All the breath fixes should stay in the past, with the exception from this rule in dot Net is the I prefix for interfaces. This is an established agreement. Don't go against it. The code is not a place for jokes in a project I've participated in. Developers started to use an absolute string property for jokes. They said it toe send to the administration off the president string value. Ha ha ha! Very funny. A colleague of mine said he knew a developer who named temporal variables like I'm sorry, but I will say what I have heard. He named Variables like Sock Fuck Dick after that, Eventually he came up with a good name and performed Aaron a manufacturing he forgot to reflector That name's a couple of times, so other developers were astonished when faced the names. Remember, the code base might be read by many developers, even by developers with whom you're not familiar yet and don't use cute names. Don't name and method wack. Instead, off keel, feel free to add valuable information from the technical perspective. For example, you're allowed to name a class as customer builder or customer factory. This is very helpful for understanding the design of dependent classes for any normal developer. It is obvious that those suffixes means the pattern which was implemented by those glasses . It's a very good practice to use names which come from a problem domain. When you use problem domain names, then you can easily communicate with customers. This is especially helpful when implementing domain Dreamin design or D d D. In short, for example, if people who work in the problem domains say shift instead of session, what implies a working period, then you should name a class shift, not Sachin, even if you like the letter. People love symmetry. Symmetry is easily understandable. A good example of symmetry can be found in can bags, book implementation patterns. Here's an example off a method which lacks symmetry. The second statement is more concrete than the other two function calls. It's better to rewrite this on the basis off symmetry. The result may look like this. Still, this method violates symmetry. The input and output operations are named after intentions, while in Crim and Count is named after an implementation. Looking for senators. I think about why I am incriminating the count, perhaps resulting in the following code. I should admit that this is a very subtle example. Actually, the problem can be explained not only by the bad name but by different level off details in the method. Here's another example provided by Curious Key, which reveals the problem. Compare the falling two methods. Which method is more understandable? I bet you'll say the 2nd 1 The thing is that the second method consists off a couple off calls to well named methods, which encapsulate corresponding logic. That's a trick off course. The guts of logic are still there. They're just hidden. Such a perfect rings lead to many small functions. It makes classes more cluttered. However, the irritability gets improved anyway. The reader will dig into the internal working on Lee if he needs to. In the first case, the reader was forced to read everything. No matter whether he needs to understand only the overall meaning off the method, he would be forced to read all the details. Here are some straightforward examples off symmetric names, which are super understandable as well. Begin and first last Locked unlocked. Mean max. Next, breathe this all new, open, closed, visible, invisible source. Target source. Destination. Up, down. Let's talk about the scope and name length. The general rule here is the wider the scope of the length here, the name, the narrower the scope, the shorter the name. If a variable exists within three lines off cold, then it's not so important to give it a long, descriptive name. Take a look at the following function. Do you see that E variable, which is used in the for each loop? We can name it employer, but it's perfectly clear what he means. The scope is very short. At the same time, you shouldn't give very short names for variables, declared its fields. If you read the function, which uses a field named D, then you have either to jump up to the declaration or toe over the mouse pointer over the variable in order to find out. At least it's type. Oh, Stipe is document. So couldn't it have been better to name it s document or just dark? 1 may be confused by this rule. For example, one would think that instead off declaring total variable, we could declare a variable named T. The total variable carries on important semantics. However, it means that it is an accumulator naming it S T would hide that semantics, making the cold much less readable. There is one special case which concerns nested loops. Usually we use I J K letters for iterated er's. Well, consider the following piece of code off course. I would try to avoid such deep nesting off loops by using link or any other available techniques. However, if you have to write this kind of code, then try to use a more slick way off naming it aerators. Do you see a mistaken this piece of code? It is in the if statement, we reiterate members by K and users by J. This is wrong. It would be better to rename the traitors. Yes, this see? I am I you I the If statement would look like this in this case, a mistake would be apparent and the author would fix it. That class name should been now, for example, customer fainter daytime, parse er and so on. Try to avoid too broad names like manager data info. Try to avoid adding these garbage words. Date our info How the hell customer is different to customer data. Why were they separated? Functions. Names should be verbs. Get customers generate. Dump our good names for functions. Functions which return Boolean values should be named ESP Reddick It's can remove. Student is a good name for a function which returns a bull in value. By the way, Boland perimeters are also should be named. S predicates, for example, is correct is busy can extract and so on code should be readable. Essay Well written prose. Consider the following examples. The 1st 2 examples are much more readable. List contains item is better than least is contained Item The 1st 1 sounds more nature. So the general advice is you shouldn't forget about English grammar. Strive to make your code readable. S a well written prose 14. About Names Once Again: once in a company I've been working for. One of the developers got retired, and I had to pick up one of his projects. I opened his solution written in Delfay. Then I opened one of the wife forms and, ah, what I've seen frustrated me very much. All the buttons were named, but one button to button three button for all the elements were named by name is generated by default. He literally named all the things in his code base like that. All the event handlers were named button one underscore click button to underscore, Click and so on. It's much better to give descriptive names. Toe all members in your code. Consider the following great names for buttons. Generate Reppert for the bottom, which triggers the generation of For Reppert close work. Shift for a bottom, which triggers the closing process off a work shift close window for a button, which triggers the closing off the window. Notice that buttons are usually named by using verbs, since they usually intended to trigger some kind of action. Gless won. Is that a good name for a class? What would the reader off such a class do? He would have to read all the content before figuring out the actual meaning of this class . Customer sounds much better as the name for a class. If it contains data in functionality concerning customers, do not use mysterious names. Meaningless names. Have you ever seen methods named like this? Start processing retrieve data. Almost always, such names are meaningless. Yes, they're not named like function juan or function to, but nevertheless, you cannot say what they're intended for exactly. The 1st 1 starts some kind of process. The 2nd 1 retrieve some kind of data, but this does not help much again. The reader would have to read all the content for figuring out the meaning off these methods. Much better names are bars XML file rather than start processing or retrieve student in. For though this is still one of the best one. But this is much better than the previous version. Sometimes developers give excessively descriptive names. For example, they sometimes include into the methods. Name the details off its implementation. Look at this method line your search, which takes I d off integer time. The better version would be the following. You shouldn't include all the needed greeted details into the member names. If details are extremely important for clients, then consider the following variant fest find If a client wants to dig into the details, he will just do it by either reading the documentation or the source code itself. Certain names. In the early days of programming, there was a lack of tool support, and people struggle with navigation and understanding their code. Very often developers shortened variable names. Consider the following example. These names are from the project. I have been working with the first Field Man initialization message. In this case, we can make it in need message since in it is a widely known term Doc V manned document group. For some reason. Hell, I even don't understand why he used Visa fix here. Adder to mount addressee. Try to avoid shortening variable names in the modern world. This looks ridiculous. Names within codings a que hunger imitation. Many old developers can become accustomed to the fact that modern ID's for managed languages are so powerful that we just don't need any in codings like Hungary Imitation. My boss, a developer with more than 15 years of experience, applied some kind of notation which I actually do not understand. Until now. He named all the function parameters with a prefix like in the following example a sat a row. He argued that when he uses parameters in the methods body, he always knows that variables with the A perfect SAR function perimeters, my colleagues and me, we we have never faced the problem of distinguishing local parameters from class fields. I d will always say that there is some kind of ambiguity. In the worst case, avoid immunizations like in the following examples. Much better names are name length, session numbers, ambiguous names sometimes you may encounter and big ears names. Look at these declarations. Document Name I D Field money to string method document Name I D. Is that the name or I D? Is it an idea off the name? If so, then why it is of type string. The 2nd 1 just blows my mind. This is a real example from one of the projects have been working in how the hell the function can be named money to string when it returns. An integer avoid ambiguous names. Names should clearly reveal their only one well expressed intent. Here is another example off a misleading name. Well, can you say which objects will be filtered? Will the results continue? Those customers who were born before 1988 or after I think a second? Yes, there is a less or equal operator, but it doesn't mean anything. Seems the method which filters the objects is named future. But what does filter mean? How is it going to filter the objects If you want to select those who were born before 1988 then used? Select. If you need to exclude them, use the word exclude or select with a negative expression. Here is another example. What would clip function due to the past text? Would it remove the last and characters defined by the length argument from the text? Or maybe it would truncate or shrink in some way the taxed, making it in its length equal to the length argument. Who knows? You cannot be sure. If you want to try okay to the taxed, then it would be better to declare that function is this. I also renamed the Second Argument since length could mean bites. For example, Max is also good graphics, which enhances readability in this case mocks chars is a good name. However, you shouldn't addict to expressing the units of measurement in member names. Consider an advice from one of the famous books about clean coding. I'll quote. If a variable stores the results of measurements such as number of bytes or elapsed time, then it's neat to include the units of measurements to the name of variables. That book gives the following example in Java script language. Further authors say that it would be better to include the unit off measurement like this Start underscore milliseconds and elapsed underscore milliseconds. I want to say a couple off words about this advice. I already said that you shouldn't become addicted to expressing the units of measurement in member names. And here's why. The right design decision would depend on the complexity off units we need to express in the member name. For example, Marks chars name in the trial Kate function we discussed before was fine because there was no need to abstract away the concept off chars as a unit of measurement. However, I wouldn't recommend to follow this advice concerning expressing time spans. Often, such naming shows the so called primitive obsession. Smell you learn about that smell later in the course. For now, I'll just say that often would try to replace the lack of abstraction by other things, like specific names or method extensions. Long story, short time spends imply an abstraction. That's why I don't know. BCL defines the time spent structure. So if you use the daytime structure trying to subtract one time stamp from another one, you'll end up with an instance off the time span structure, which is very neat because it's intrinsically convertible between different units of measurement so you can convert between seconds Miller seconds, minutes, hours and so you can call different properties on the Elapsed. Instance. An obstruction for representing time spans is very need. Noisy names. Sometimes developers think that applying English grammar is a good idea, and they're right. But you shouldn't do that blindly. Consider the following examples. The first method should be named just in your all student without article. There suffix least is needless. In the declaration off list of students, it's much better to just declare students don't add needless noise to the member names naming predicates. As you said previously in the course, it's a good practice to give predicated names for Boolean variables. Most of the time, developers start their names with ease or can predict it's Sometimes it's better to go meet them. Consider the following example to read it. If is found, we can make it better by Rene Me like this. Read it If found. Well, that's better, in this case, with Follow the rule that the coach should be readable as a well written prose. 15. Violating Naming Conventions: Very often you can encounter projects which used inconsistent naming. One developer uses underscores for private fuels. The other don't. One developer uses capitals for a Cronin's longer than three characters, the other don't. The list may be very long. Even if a team agreed to violate some of the default at night conventions, it would be better if the entire team have been consistent in that violation and followed the agreement everywhere in the code base. I do not encourage the violation off default .net conventions. But if your team agreed to violate a rule, the entire team has to obey the agreement. Violation off agreements here and there is much worse than consistent violation everywhere . Such violations by agreement is not a violation anymore for the concrete team. In order to impose naming agreements, you should look at some tools that help to enforce naming rules. There are some tooth that enforced conventions style cop, a free tool that enforces the naming rules. Ethics Cop is a free tool that enforces designing rules integrated into visual studio since version 2012. Very sharp ER is a paid tool that has a great number of features, including enforcing, naming and designing rules and much more 16. Naming Conventions in .NET: There are two ways off naming any a pie. Members in dot net basket casing and camel casing. Camel gazing is used for naming private and protected fields and for parameters. The other members are named with paschal casing. Here you can see that the glass name, public event, public property and public methods name. They're all named using paschal casing. Only the private backing field and a payment parameter are named via the camel casing. Off course. Private methods are also should be named by Abascal casing. Also, I want to add that private fields can be named using the underscore per ethics. This practice cannot be considered a hungar imitation, they underscore for private fields allows you to distinguish local variables and private fields, since there are tons of situations when they're named. Equally off course, there is, ah, these keyword. But despite that, you can rely on the underscore. This is a matter of taste to some extent, concerning acronyms. Acronyms, which consists off two letters and are not a part off a camel cased perimeter, have to be upper cased. For example, the name, space system dot io or the method start io with the perimeter IR stream, which is camel cased acronyms, which are lengthier than two letters and are not a part off a camel case perimeter. Have to be upper cased Onley. At the first letter, consider an example. The name space system dot xml. Only the first letter is upper cased the method Bro Sis HD Male tag Onley. The H letter is upper cased and the perimeter html tag, which is camel cased compound words. Now let's look at how to write down compound words in code. Generally speaking, you should delimit er awards by the casing. Here are some examples I D. And OK are exceptions from the rule of two letter crimes scenes. They're not acronyms at all. They're just commonly used short versions off the identify rearward and Orel correct a joke . A misspelling off All correct, which was current in the U. S. In the 18 thirties. Strive to avoid using off common short names such as wind instead off a window X instead, off extension and so on. The intelligence sense is powerful enough, and it provides the auto completion feature so you don't have to tap the whole world when a parameter does not bear any semantic payload, you should name it as value or item. For example, stream inheritors in the BCL exposed the following overloaded right functions, right. Double value, right Float value and right shortly. If you're developing a collection, then you can name a parameter in the ad method s item. If you have already exposed the class, say string parse er and the many clients currently use it and you want to add a new version of the A P I. And then you should name it as string Parsons too. I prefer numeric suffixes for new. A perversions off course. We're talking here about the case when you can't extend the previous version anymore. For some reason, you should not roll out in you class every time you add new functionality. There is one general rule regarding names off inheritors. If this does not evoke any contradictions than other parents class name as a suffix to the inheritors name, for example, File stream inherits from stream customer user exception inherits from exception interfaces . Names should begin with I perfects. Some people, including Uncle Bob, think that this is a stupid agreement because of the same reason by which hunger and notation is stupid and redundant. Nowadays, in my opinion, you have to stick with the dot net agreement, since it is now widely used. Don't puzzle anyone by refusing this naming agreement. Don't forget that it's a good idea to just remove the I prefix for default interface implementation names. For example, customer inherits from my customer. So here we just remove the I perfects. Let's talk a little bit about naming generic types. The most common name for generic types is T. For example, add T item or leased off T. You're encouraged to add some valuable Suffolk's if it helps to clarify the meaning of the generic perimeter, for example, you also can often face the following type names. T mean t out T input tea output, especially when there's a pair of generic parameters t mean is foreign Out is for output parameters logical. Try to use singular names for an immigrations. Here is an example. Device is a good name for a minimum. Devices would be a bad name. Use Blue RL names for beat in, um, orations saying Beat. I mean decorated by the flags. Attribute. Here's an example. Keyboard keys Also don't add in, um, as a suffix like device in, um, it's also a bad idea. Use verbs for naming events. Here are some examples State has changed, era cured and so on you stances If they're connected in time events, for example, processing and processed, closing and closed strife. Do not declare your own delegates. Nowadays there a generic action and funk delegates and even handler off t Don't make Constance upper cased. Constance should have only the first letter upper cased, for example, public stated in age or public constant max and don't use any prefixes. The only meaningful perfects you can use is the underscore. In private fields, it is useful because fuels and method parameters often have the same name and too easily distinguish them. You can add the underscore signed to the private fields. Don't use any prefixes in other cases 17. Names Conclusion: in this module. We talked about a great number of general naming principles. Let's recall them. Used intentional, revealing names. Don't use these informative or controversial names. Use easily readable and pronounceable names. Use English as a coding language. Don't rely on in codings such as Hungary. Invitation. Don't try to be funny in your code. Use well known programming terms such as names of betters. Use domain names. Use symmetry in naming like add and remove bush and pop. The wider the scope of variable the longer it's name can be. Glasses should be named by announce, whereas functions by verbs remember code should be irritable. As a well written prose alongside the general naming principles, we've taken a brief look at naming conventions specific for the dot net platform. 18. Writing Clean Functions Outline: Hello, Engineer sparkles speaking. I'm glad you're Ridge. This module in this module, we're going to talk about writing clean functions. We're going to talk about clean variable declarations, magic numbers and how to avoid them. Smell off string Lee typing and how to avoid it. How to choose between method and property, the peculiarities off, implementing parameters, the smell of too many perimeters and how to effect her them out. The smell of too long methods. And what can we do about that? How to choose between constructor and the creation? All pattern. You'll see the extract Math Adra Factoring How to simplify complex logic. It's not so simple in some cases the problem off right sequence of arguments when to use guard clauses and early returns, poor conditional clauses and how to factor them. The smell of out parameters and how to avoid them, which commence are good and which are bad and the smell of double negative statements or proof for positive of statements. We have many things to talk about. Let's kick off the module discussing the waste off variable declaration 19. Variable Declarations on the Top: in the early days of programming, developers tend to write. Long functions nowadays were encouraged to write even one liners functions, which consists off only one line. Because of problems with the navigation, developers declared variables on top of methods to keep them all in one place. Nowadays in Java or C shop, this practice is meaningless. This practice has a drawback off context switching because readers have to remember all the variables and then read chunks of code related only to certain variables. Here's a bad example. You can see here that two variables are declared on the top. Look at the improved example. No need to look around in order to find declarations there close to the usage in the reality. If you write clean code, this problem even will not arise, since the best option will look like in the code snippet that you see on the slide 20. Magic Numbers: Magic Numbers is a well known code smell. In order to understand the scene off introducing magic numbers, look at the following example. In order to understand the meaning off the if statement, we need to read the inner body of the statement because no one could understand the meaning of the code 188. In order to make it clear, the developer would have to declare a constant like this. Now it's clear that this if statement checks if there was a response from the device, avoid magic number and Magic cars always reflector them out into well named Constance. If you have to define several Constance, consider turning them intern enumeration. Look at the following piece of code these gold lax and enumeration, a construct which is suited for such scenarios. We have three Constance here. Look at their factored version. This code is much more expressive, depending on the context. This code could also be smell is specifically from the object oriented programming point of view. You'll see later what can be done to remove multiple if statements were huge, switch statements 21. Stringly Typed Smell: Once I worked on a project which was initially developed by C programmers. They used strings instead of strong types everywhere. They could look what the previous example with lights. They would implement it like these piece of code instead of Constance or in, um, aeration. They use string literal red, yellow, green. This smell is called strongly typed code. Avoid using string instead of an IMS and proper abstractions. You learn later that it's not a good idea to use strings for representing even zip codes, for example. In this case, we could reflect her strings into an enumeration you've already seen in Terms are strong types, and it's impossible to make a mistake using Denham's strings are too broad, and developers can assign literally anything to them. Beware off using strings instead of imams or abstractions. 22. Property vs Method: Sometimes we face the dilemma to implement a certain member. Either it's a property or a method. The problem may seem obvious, but it's not even experienced. Programmers make mistakes when choosing between property and method. So what's the difference between them? Let's consider the first case. Sometimes methods may require more than three parameters. In such a case, you generally have three options. All the parameters, which can be set to a meaningful default state convert to properties, create a bunch of overloaded methods and create a method with a long list off optional parameters. Let's take a look at how this examples look in the code. All the three options have their own advantages and disadvantages. Let's consider them in turn. The first option of converting parameters to properties is not the worst one. It can make your A P I cleaner. The more parameters required by a method, the preferable this approach becomes. If a method takes four parameters where only the 1st 1 is always required, then you'll end up with eight method over loose to cover all the cases. There's another peculiar difference between the 1st 2 approaches. If you convert on required parameters to properties. And there are other properties with public centers which are relevant for other methods than how our clients should suggest which properties are used by which methods. So if you stick with the first approach, then be sure that your class is highly cohesive. What means that all the methods used all the properties? You can extract glasses to achieve this level of granularity. The second approach with over lutes does not have this problems because the client always sees the available options directly through Intel sense. When calling to a method, though your code in this case tends to become a mass is, you can see the third option is the most beautiful, but the most inappropriate for public 80 IES. The thing is that it does not allow to at parameters without breaking existing clients and compile time. Let's look at an example here we have three optional perimeters, but what will happen if you want to add a new optional parameter? You can't just at a new parameter to the existing method, since it will break all the existent clients in the run time, it means that all the clients have to bear compiled in order to use your new version. I'll not demonstrate the runtime crash, but you can check it on your own. You also can't easily add an overload, adding a new parameter to the end of the tougher load. Why the things that after that, all the clients which called the first method version, will be broken? A compiler on the client side will say that it cannot resolve the difference between these two methods. Signatures. Let's look at it. You can see here that the compiler says that it sees ambiguous signatures. The last problem you should be aware of when using optional parameters is that the default values get backed into the COLLI into code. Thus changing the default value will have no effect on existing clients without Rick compiling their code. That was the first concern regarding methods and properties. Now let's look at the semantic difference between properties and methods. I remember you should great properties as simple as you can. They should not throw exceptions in getters. They should not connect to database, and they should not be a synchronous the most notorious fail of creating a property inside the BCL in dot net instead of a method is the date time now property. In my opinion, this particular case is not the worst in history, though it's an embarrassing one. So what's wrong with that? The daytime now is implemented as a property rather than a method. This is not wrong. From the point of the actual implementation, it is implemented correctly. The point is that this is semantically wrong from the A P. I design perspective if every time the getter of a property returns different values there . This is a method, not a property white. Because the property is a natural, beautiful entity. For example, year is an attribute off a date, so it would be correct to get the year as it follows. Yes, that's it. That's how it should look like. Not like a chain wreck, By the way, similar to the case, Green, you greed member is implemented a PSA method. In this case, there were new dictates that this should be a method, but for example, they could have named it greed next, And even in this case, it should be a method as well as the daytime. Now I'll show you the example off misusing a property from my own practice. So there was a simple window which was implemented without MVV m and all this stuff in the Zamel CS file was a string property which in its centre, said the text in a text block and for some reason it did it a synchronously using application Current dispatcher begin invoke method 10 minutes. I couldn't understand why the following code didn't work as expected. Don't think about the secret meaning of this code. The point is that the color of a property settle never expects that it will not be changed immediately. In this case, the center unintentionally deferred its work. If the property is stately, semantically coupled with the y, and you want to use such a nice in construction than the property, at least should not be a part off a public contract. To recap. I should say that properties and methods are very different from the perspective. Off usage scenarios use cases say no toe any multi threading synchronization, externally pickles, CPU intensive calculations and even simple. Yet each time returning different results pieces off gold inside of your properties 23. Implementing Parameters: we can find tons of horrible examples of bad parameters implementations in other to implement parameters in a good way. Let's consider a bunch of rules. First, use the most specific type for parameters. For example, if a method receives a collection which can be modified used by innumerable instead of fire list, avoid out on draft parameters, especially in public AP Eyes out and ref parameters confused a great number of Donna developers. Many developers even don't understand the difference between out and draft parameters. Ref parameters, especially those which used for passing reference types, lead to very subtle box throw exceptions defined in the BCL. When parameters validation fails, it doesn't mean you can't rule out your own custom exception types. In short, if a parameter is now and this is an invalid state throw argument now, exception never ever thrown out a reference exception. Explicitly. If a parameter value exceeds allowed boundaries, throw argument out of French exception. Methods should not require more than three parameters. Sometimes you need to require more than that, but almost always this is a smell off. Violating the SRP single responsibility principle. Try to reflector parameters out, for example, you can create a separate class to aggregate some of them. Most likely you're missing a concept which should aggregate those parameters and represent them as a separate object. Let's talk a little bit about using Boolean parameters. Look at the following function. Call What the hell through and false mean there. Bullen flags As function parameters are much harder to understand. Them in M orations always prefer enumeration, especially in public AP eyes. Here's how the previous cold might look like now everything is clear. I also noticed that a function which takes either a bowline or enumeration parameter, most likely violates the single responsibility principle, since it has several execution paths. If there is only one bullet flag considered the option off, exposing to separate methods instead of using a bowline, flak or an enumeration. Here's an example. Sets which bull is on much better to expose to separate functions, sat on and set off or the following example. Change student status. Taking Bullen and Roll. It is much better to expose to separate methods in role and expel use named parameters everywhere you call methods that require Bullen parameters. Named Parameters is the feature of the shop since dot net. Four. Look at the following example. Change student status in They're all true instead of change student status. True, it's very convenient to see the name off a Boolean parameter when calling a function. 24. Too Many Parameters: Another common coding smell is a big number off parameters. A serial of thumb. You should strive to make functions, which require no more than three parameters. When you see more than three parameters, consider extracting some of them or all of them into a separate class. The other possible re factoring is to create two or three methods instead off one, because the method which takes so many parameters, most likely violates the single responsibility principle. In many cases, having too many arguments in a function is the silence. Absent abstraction, consider the following simple functions. In all the three cases, there is the same problem. The lack of abstraction. In the first case, we could introduce a parameter object by extracting a class. In this case, I extracted X and Y ackwards into a separate structure. Now it's obvious that X can go only with why they cannot be separated. In the second example, we can introduce the arrange structure, look at how the function is improved. Instead of four primitive parameters. We have two objects. This is much cleaner, both from the readability point off you and from object oriented design. The same riff actor can be performed in the third case, it's subs that the third functional ax of the date range abstraction in this case I joined to daytime values in a structure. Now they will go by hand with each other. I'm sure you see that such gold is much better. By the way, the next re factoring would be to move the overlaps method into the newly extracted object . It would be bad if the overlaps method would continue hanging somewhere outside of the single source off logic. For example, in case of date range, I would move the overlaps method inside the date range structure, and that single source of logic should be the object which contains data. 25. Too Long Methods: of the longest method I've seen in my career. It was 5000 lines long, Really, I mean it. I don't want to get deeper into this story, but I want to mention that the five K lines function was the core of the roughly 150 K Lines program. That program was eventually dream into a corner because of that piece of shit which tremendously influenced on the whole architecture of the application. In the end, the decision was made to rewrite the program completely from the ground. 10 or 20 years ago, developers came to the agreement that the longest function should spend roughly one screen , but that was from 10 to 20 years ago. Nowadays, most programmers consider such functions very long. As a rule of thumb, you should strive to make her functions no longer than 10 lines of Coke. Roughly, this rule is not made of stone. When we're talking about the length of functions or a number of function parameters off course. We're talking about Yuri stick parameters. We can't just state that from the current moment, we will never write functions longer than 10 lines. That would be ridiculous. There's a technique introduced by Uncle Bob called Extract Ilya Drop. Let's talk about it. This technique means that you should extract chunks of code from a method until theres nothing to extract. The story I've told at the beginning of this lecture illustrates one of the extremes of the function size problem, which can lead to so unfortunate repercussions. The other extreme is to turn off your brain completely and start extract glasses everywhere . With one line functions inside. I don't mean that one liners are bad. When I'm talking about is to not forget to harness the power of your brain. There have to be some considerations in the first place about what do you want to achieve before I'll try to investigate this problem further? I want to mention that actually, there was a quite exciting episode off a battle sort off between Uncle Bob and Christian Gorman. On the topic, Uncle Bob introduced the technique named Extract Till You Drop, which in short means extract functions till there's nothing to extract anymore. Kristen Gorman argued that this technique sounds like a no brainer. For addition, there was a block posed by John Soundness about re factoring off .net BCL method using this technique, though their original intention was to show that the Komen's mostly are bad. You can check out links attached to this lecture. If you want to look at the original sources, let's consider the example of Johnson factoring. He took the following method with the intention to make this goat easier to read. John extracted a glass and then extracted some functions. He ended up with the class you see on the right side, download source code and compare the initial code with the re factor. Wow. Yep, It's not so simple to decide whether they're factoring. Helped to make the code easier to read or not. Seems like it became harder to read. Actually, there was a relatively short function with useful Commons, which was turned into a class with four functions without comments. I wouldn't say that the new class is a bad class, and the overall manufacturing was a mistake, and the programmer who did this must be executed. Not at all. I'm not so bloodthirsty. There are a couple of differences between these two code examples. Let's consider them first your drank too deeply. Understand what the higher level function does, then they're factored. Function is harder to read than it was originally because you have to hop over all the functions and understand what's going on inside each of them. Conversely, the original example is simpler to quickly skim through. Second, If you're trying to understand the overall concept of the original function, then it's reflected. Contra part is better because we immediately see what conceptually this function does inside of itself. The third difference I see here is the maintenance cost. Considering our concrete example, I'd say that they're factored version is more expensive than the first. At least you have to spend some time to do re factoring generally. The answer to the question off which example is more expensive in maintenance lies in the field off requirements. Those requirements dictate us whether it is so important in this situation to adhere SRP the single responsibility principle or not. If this function can be once written and for gotten till the end of times, then there are no any reasons to extract additional class. With four method inside, there are no reasons to spend time on re factoring in opposite if the functionality is expected to grow over time, then you have all reasons to reflector it into class. In addition, I want to address the situation when you accidentally or deliberately come across the similar function in the legacy system. Are we going to rush for extracting the class with four functions? My advice don't do that without a reason. Even if your code based test coverage is closer to 100%. Why? Because there is no any technical debt. I am talking about a solid technical debt which causes the rial harm. So there is nothing wrong with the extractive. You drop technique. You just have to keep in mind some considerations, in my opinion, to sum up, I want to stay that you should not do mindless acts. You should think at first analyse make the conclusion, and only after that act. 26. Creational Patterns VS Constructors: there are different gration patterns. Factory builder Singleton are the most commonly used. There are two commonly used factory patterns, factor method and abstract factory. More on these patterns you can find on the Wikipedia and many other different places in this lecture, I want to stress that the difference between constructors and factories from the FBI building perspectives I'm not going to discuss design patterns deeply. Let's go. Obviously, a constructor is simpler than any possible factory. One of the irritating flaws of factories is that they are not discoverable by the intelligence. Intelligence can show only constructors off a given type. It cannot discover factors of the type Onley. This fact makes factories much harder to use from practical perspectives. Always keep in mind that tools support is an indispensable part of modern, powerful languages such as Java and C sharp, thus rolling out factories instead of constructors with sacrifice. The benefits off support by tools, making the object creation scenario harder to understand and use. Sometimes benefits of factors outweighed the disadvantages. Let's look at scenarios when factories are preferable than plain constructors when you need to apply some kind of constrained like clients can create only one instance off a certain type, you can rely on a single term pattern In such a case. Singleton is not a factor, actually, but it's also one of the creation all patterns, which ensures that the client can create only one instance of a certain type when you need affluent AP I off object creation. In this case, you may want to rely on the builder pattern. Here is an example of the order creation process when it is implemented via the builder pattern looks very expressive. Feels like the specific language for the domain order object was introduced When you need to return a base type from creation all procedure, you just can't rely on a constructor in the BCL. You confined the following examples. When you need to expose more contextual information about the creation process, for example, you have a money type, and you can create bypassing sense or dollars. As a side note, I want to say that you'll find more on the money class at my blawg when you need to expose conversion operations. There are two common types of this rule. Try parts pattern and direct conversion. Consider the difference. You can live on Lee the direct way like parse if you're absolutely sure that there cannot exist any invalid conversions, otherwise you have to expose both bars and try parts patterns. 27. Method Extraction: Let's look at one of the most frequently applied They're factoring is called method extraction. Consider the following code. We have a method here called Search. This method takes two arguments. The 1st 1 is an instance off the geo cord struck, and the 2nd 1 is the least off jail cords these methods reiterates over the least off jail courts, searching for the closest to the first argument. For that, we convert latitudes and longitudes to radiance and calculate the distance of I a well known formula. This code is quite good, though I would apply a couple of free factoring at first, I would rename the method to get closest instead of two broad search. I'll use the power of free, sharper get closest Done. Another small improvement Aiken do here is to transform the for loop into forage. For each loop is easier to read, since it removes the needless noise off the for loop. Let's do that. Another factoring that can be performed here is actually described by the command, which says calculating the distance in the majority of cases commands, which describes some piece of functionality, actually imply that you need to extract a method with the name is similar to the meaning off the command. In this case, I would extract a method for calculating the distance. Again. I'll use the power of free, sharper, and now I can remove the command. Done. Do you see how powerful motor and code editors are and you're factoring? Scan be performed in 23 clicks, like by the wave of a magic wand. By the way, extracting a method often helps to separate pure logic. What makes that piece of functionality more testable isolation off pure logic is always a good thing. 28. Simplifying Complex Logic: Let's look at a well known, quite complicated case of determining the overlapping ranges, taking into account that we have a range structure which defines begin and and properties. Look at the following picture. Notice that the end property is not inclusive according to this picture. That's why a, B and C do not overlap, while de overlaps all of them. Look at the following implementation off the overlaps method. These and the following slides assumed that the overlaps method to recite in the arrange structure. Thus it has access to begin end and properties. These logic seems simple, but actually it's quite functional. Here's the logic of this code expressed in the form of a tree. We have many different conditions here, and that's why it's quite simple to introduce an error here. And indeed, we have a mistake here. According to this implementation, the range from zero inclusive to two exclusive overlaps the range from two inclusive to for exclusive while in the reality that's no the case. The problem is in. The operator weaves for comparisons. After fixing the problem, we end up with the following condition. Everything is right now yet, actually, there is still a mistake. This code doesn't cover the case when begin and end off. Two ranges are the same, so the right code will be the following. Now the logic is even more complex than before. How to simplify the logic in this case? Sometimes we need to come up with known trivial solutions like in this case, to simplify the logic. We can solve the problem going the opposite way. It's easier to determine whether to ranges do not overlap rather than whether to ranges. Do overlap to determine whether to ranges do not overlap when you took cover. Two cases, one range ends before another begins, and one range begins after then off another. Let's implement this logic. Each line of this code is easier than before, since they contain single comparisons. Always try to simplify complex logic were possible. Sometimes you need to come up with a sleek wear for factoring 29. Sequence of Arguments: in this lecture, I'm going to cover two cases related to positioning off arguments. The first case concerns the sequence of far garments in if statements. The second case concerns positioning off arguments and methods. Let's start with the first case. Have you heard about the so called yoed imitation? I hope not. But since I cannot be sure, I need to explain what that is and why you need to avoid it. Compare these two examples. Which example is more readable for you? I bet you will say that the first example is easier to read, and I even don't have to explain why, since it's obvious without any explanations. But how the hell the second way of writing if statements came up at all? If you haven't ever seen the second way of positioning arguments, then you're a lucky guy. I have seen that approach. Developers invented that approach in old land, which is such a C plus plus because of the possibility to write the following if statement , this gold will compile and it will assign 10 to the length variable and evaluate the if statement is true because 10 is greater than zero. However, in 99% of cases. That kind of code appears because off in this type, most likely that if statement had to be written like this, this is irregular comparison where we compare length and value 10. To avoid such miss types, developers invented the Yoda notation positioning arguments in this way You can't forget to enter the second equal sign since the code will not compile. This is a slick protection from miss type. Unfortunately, 20 years ago, I d Ys were not enough powerful to detect possibly role constructions. And because of that, developers had bean inventing different strange techniques. By the way, this notation is called yodel notation because Master Yoda from Star Wars positions words in a reversed order like when 900 years old, you reach look as good. You will not return of the Jedi. You should never, ever rely on your limitation in C shop since the shop compiler will complain about the if statement which takes not a Boolean argument. So in C shop, there is no such a problem at all. There is a quite irritating problem with binary internally functions. If you have ever written unit tests, then you must know about the following method, which look almost the same in any unit testing frameworks. Here it is how many times I passed actual instead of expected, really a great number of times. This is because there is no in natural order for such kind of arguments. This order is just a subjective agreement between developers. However, it's very easy to misuse the arguments. It's hard to keep in mammary that kind of arguments. Look at the following Turner method. Oh my goodness, this is even more complicated. If expected and actual are of strength type, Then you may find yourself confused sometimes by all the arguments. Unfortunately, some binary internally functions like a certain are equal, are doomed to be unreadable, and no one knows a good way of improving the readability except using named parameters and see Shop like this unnamed parameter shows you the name of the argument, which should the past here and there. However, developers, including myself, avoid this practice. In this case, it looks cumbersome when it's applied consistently in hundreds off tests. So sometimes you just have to leave with binary Internal functions like assert are equal 30. Guard Clauses and Early Returns: many developers have a strong opinion that functions should have only one return statement . There are two main arguments giving by developers in favor of that approach. Functions with several Reiter and statements are harder to read. And when you have only one return statement, it's easier to guarantee that the cleanup part of the code will be reached, saying cleanup code They mean code, which frees up acquired unmanaged resources. The second argument is sealing into sharp since we have the using statement or try. Finally, it solves the problem of cleaning up the acquired resources. So let's discuss the first argument. Compare these two pieces of code. Can't back considers the second piece of code more readable than the 1st 1 This is because you need to think off the else branch, even if there is no the else branch. In the first case, the second piece of code immediately cuts the shortest part. We see the return statement in case something was already initialized. Consider another example, nested. Now checks are caused by the flawed design, but this example is here just to illustrate the benefits off early returns. So consider the previous example re written with early returns, early returns or guard closes. In other words, got degenerative logic branches as earliest possible, reducing the nasty. What makes code more readable? Yes, I know that with the power off Nell Propagation featuring See Shop, we can avoid early returns. But this is because this example is based on now checks. The Nile Propagation feature cannot be used with checks not related to now's, so the technique can still be beneficial. Here's another example provided by Can Back. This example demonstrates the guard close a swell. These guard clothes separates of the normal flow of the cycle from the logic of exclusion and wanted cases and makes it more of this. 31. Poor Conditional Clauses: I've seen so many poorly written conditional clauses. I want you to avoid writing over complicated or unreadable conditional clauses. Let's look at well known but betters. The first pattern, which can be often seen, is that people don't use tannery operators. Here. You can see a check off a customer status. This gold spends seven lines. This is insane because we actually can shorten it to a one liner using a turnaround operator. Here's the improved version. Beautiful, clean, Simple, By the way. Re sharper, for instance, will advise you to reflector if else into eternity operator automatically so you can do it with a sharper in one click. On the other hand, I've seen a couple of times abusing of Turner operators. Consider the following example. What the hell is that? You have to blow your mind in order to understand this horrible, nasty Turner operators help. It would be much better to convert this hell into switch statement. Great. Now the intention is much clearer. So we statement in this case makes this gold much easier to understand. Now all the execution paths can be easily seen and understood. Another smell I want to mention can be illustrated by the following example. It's unclear what means the intersection off all these Bolan flags. What does it mean when all these flags are true? It can be written by introducing an additional flag. Great. Now it's clear. What does it mean by introducing an interim flag, we made the code cleaner and more readable. We don't need to investigate the meaning off three Logical and operators between Four Flags . Another possible re factoring is to reflect around this condition into well named method, which returns Bullen value. Here is another example of introducing a descriptive intermediary variable before a factoring the code looked like this. It's hard to read such a condition. It would be better to introduce a descriptive intermediary variable like this. Several times I encountered meaningless temporary variables like in the following example. Here it is. The now variable is needless here, and the author could just write that code using daytime UTC. Now directly in the statement like this, repetition is the mother of learning. So here is another example off a poor conditional clause. These clothes can be significantly simplified by extracting a method which will be responsible for validating the request. Look at Helle Nice. This Cody's All of the extensions are assigned to the least named allowed extensions. I also declared to descriptive brilliance, and in the end, I just check them now the view file Math just delegates. All the work to the well named separate method who's single responsibility is to check if the request was valid. Yes, they're factors. Version is longer, but it's much more maintainable. They're factoring will pay off over time. 32. Output Parameters: output parameters are often used when we want to return more than one parameter from a method. Generally speaking, this is a code smell and the bed idea, except for the try parse pattern, because it's widely used in the BCL and it became sort Off a convention between C sharp developers. I have seen a great number of times code like in the following example God's sake. This is clearly abusing about parameters. How the hell the clients code is supposed to look like. I'm not even going to show you what it will look like. The gold will just look insane. In such situation, you have to reflect her out all the arguments into a separate class. In this case, it might be a class named railway dictionaries container, which contains all the required information. As a result, the get dictionaries method would have been looked like in the following example. The second problem here is that the initial developer of this method wanted to return an error code in the case of first during retrieving. All the information in the second version would still return that error code. As a result of the function call. How can we make this method better. In order to overcome this problem, you can rely on the result moment, which will be discussed in details in the module about errors handling. In short, the result moment is a class ridden in a functional style, so it allows you to store an error, a returning value and allows you to build method chains. Look at the module dealing with errors, lectures, errors and functional programming, and by planning by a method chaining here are just will show you how this signature would have been looked like. Do you feel how much simpler is this comparing to the first version? Let's consider another factory. Sometimes we just want to return a couple of values from a function. And because developers are very lazy, they don't want to create a separate structure or a class for them. Most likely, see Shop seven will get an improved suffered off so called pupils, so we will be able to write a function with the following signature. Here's an example. Surprisingly, the cooler will be able to use this function as in the following code snippet. As you can see, you get the ability to use named returned arguments as they were named in a function declaration. This is awesome, so I hope we'll get this feature in c. Sharp seven. This is also a great way for avoiding out parameters, thus strive to use out parameters as rare. It's possible the most common way off using out parameters is to use them in the tri parts Better. Okay, we're done without parameters. Let's talk a little bit about comments. 33. Comments: to write comments or not to ride. This is a holy work topic, though most developers came to some agreements regarding Commons. So let's talk a little bit about them when we should write comments when we shouldn't which comments are good and which are bad. In the early days of programming, developers extensively used comments since programming languages and existing tools didn't provide enough features for making the code based, expressive and self explanatory. That's why developers used comments everywhere to describe what they meant here and there by writing particular lines of code. For example, writing in pure See You just can't avoid writing comments extensively. You'll experience that the lack off expressiveness in the language itself c sharp Java and their environment is the different story. Nowadays, they're all of comments is significantly diminished. We have enough language and two features for expressing our intent in code by the code itself. Without comments, let's consider an example with Commons. Let's have a brief look at a very simple re factoring when we can avoid comments. He received the glass Shelvey model. It has a handle method, the content off, which is a sketch off code from a real project. Here you can see two comments which explain the intention off code blocks. This is a textbook example of bad comments. Let's reflector them out to named methods. Great. Now the intent of the handle method is clear, since it just calls to methods which have self explanatory names. Another example off. Ridiculous comments. Look at this code. Does this comment at any value? Absolutely not. And by the way, it would be better to extract a one line function and name. It can vote. This is much better. Let's look at helpful comment. Get primes. Method generates prime numbers, and the comments says that it is based on the erratic offensive algorithm. This comment is great. It reveals the semantic off the algorithm. I don't think that it would be better to name get primes as get Bram supplying a red US Finnessey algorithm. That would be ridiculous. So comments which describe internal details which cannot express by names are helpful. Remember, comments should add value to the understanding off the code 34. Prefer Positive if statements: Let's start with an example right away. Consider the following code. Snippet, not found, is a negative Bullen by its name in other. To get affirmative, we should Blind negative Operator. Thus was semantically work with double negative expression. In the first example, the author used the not found variable with else so the affirmative bath will recite inside the else statement. Unfortunately, it's just a matter of time when he will come up with the double negative expression like in the second example. Always prefer affirmative names for brilliance. Consider the following example. This code is much more readable, so always prefer positive or affirmative. Bullen predicates over double negative expressions he found, is much better than, if not not found right. 35. Writing Clean Functions Conclusion: in this module, you found out that it's a bad idea to declare variables on the top side of methods. After that, we briefly looked at the magic numbers and how to re factor them into a well readable Constance. You learned that you shouldn't use strings instead of strong types. Well, string is a strong type, but it's so general. It's a container for storing data that developers sometimes use them for storing integers and values, which can be represented by imams or encapsulated by abstractions. You learned how to choose between properties and methods. When you should implement one or another. Properties in general should stay very simple. You learned that methods should take the most specific type for parameters. A very common smell. Is the smell off a long least off methods arguments. We found out that it's better to aggregate arguments into separate classes. The long method is also a very common smell. We concluded that nowadays we should strive to make our functions about 10 lines long. Roughly, you learned when to prefer a creation pattern over irregular constructor. Usually it's better to use a creation pattern when the creation process is more complex than usual. Always try to find a way to simplify complex logic. Indeed, Sometimes you need to think a bit. Invent a slick wear for factoring its engineering. We don't have silver bullets for all the problems. Never used the so called yoed imitation. It's a stone age. Forget about it. Beware of the so called Byner Internal Functions. You have to remember the sequence of arguments that have to be passed in the specific order used. Guard closes and early returns to cut the degenerative logic branches as early as possible , reducing the nasty. What makes called more readable defector conditional clauses. Always when there is a room for a factoring, usually applying simple techniques, I showed here you can make conditional closes as clean as possible. I'll put parameters as well. A Saraf parameters are hard to use, understand, and they clawed her the code based very much. In order to avoid them, we can introduce separate classes to avoid out parameters. In the case, we need to return an error code. We can rely on the result moment about which we will be talking a little bit further in this course. After that, we discussed to the role of commands. Good commands should add aerial value to understanding the implementation details. They should not every state obverse things. In the end of the module, we briefly looked at the problem of double negative Braddock. It's strive to avoid them implementing positive if statements. 36. Common Architectural Design Smells Outline: Hi. This is Engineer Spark and welcome to the architectural Design Smells module. Please notice that electricity this module are completely independent from each other. What means that this module will extend over time? I'll add new lectures from time to time. Currently, we will look at the following topics in this module. Primitive obsession. The smell is about misusing primitive types for presenting high level concepts. The law off Demeter is one of the most interesting principles in object oriented programming, which is about coupling between objects. You learn how to adhere to this principle. Temporal coupling is a well known smell, which can be cured by applying the functional programming principles. So each statements switch statement is a procedural structure. You'll see how to reflectors, which statements out by playing template, method, strategy and state designed patterns. Okay, let's dig into the topics. 37. Primitives Obsession: almost all languages, perhaps, except the Assembly have some sort of primitive types for presenting characters. And digits in C. Sharp have bite into long care, string and so on. These types are primitive. They represent the most primitive concepts. We build systems on top of these primitive types. Just think of it. This is astonishing. Enormously big systems are built on top of this primitive types. While these primitives are great, extensive, using off them for representing inappropriate concepts lead to procedural code. Let's look at the design smell. In practice, you can see here a class which represents an address, and along with other information, it carries the ZIP code property. The problem here is that the ZIP code is represented by a string. Not all strings are valid zip codes. So in thes design you have to define a validation methods. Somewhere in this class, which villa days as it goes, you can call it I'll from the Property center or from the address constructors or from both places. I am pretty sure that sooner or later you'll want to perform the same validation. Somewhere outside of that dress glass, you can stick to guns and make the validation methods stated in order to call it from anywhere you want in the code base. Eventually the problem will get bigger and bigger, because sooner or later you'll need to implement some business rules on top of ZIP codes. Oh, to determining off the U. S. State or something like that, And from that point, he will start to suffer from the lack of an appropriate obstruction. The problem arises because the string is not sufficiently high level obstruction for representing such a concept like the ZIP code. In order to cure the disease, you have to create a separate class for a presenting ZIP codes and implement all the related business logic there. Consider their factor. Example. Now you can implement all the related business logic here. You can even implement casting operators, so in the end they use yourself the safety. I'm I write code like in the following code sleeping. They're factoring technique in this lecture is based on the encapsulation concept. What we really did here is that we encapsulated a string value and depreciated illegal values of zip codes. The additional article on this topic you can find on my blawg you'll find a link attached to this lecture 38. Violation of Law of Demeter: If we look at Wikipedia, we will see that the law off the meter allowed in short or principal off least knowledge is a design guideline for developing software, particularly object oriented programs. In its general form of the Lord is a specific case off loose coupling. Okay, sounds great. But what does it really mean? A general formulation of the law is the following. Each unit should have only limited knowledge about other units on Lee units closely related to the current unit, or each unit should only talk to its friends. Don't talk to strangers. Raid sounds clearer, but still not enough Practical. The formal object form of the law can be summarized s and method often object may only called methods off first of the object itself. Second, an argument off the method Third, any object created within the method. Fourth, any direct properties fields off the object. Oh, at last, the practical meaning becomes clear. Moreover, all these guidelines in the end came to the following simple statement. Don't talk to strangers. Another simple formula of this law is used only one dot Okay, then let's consider a practical example, which was suggested long ago by David Bach as a great illustration off the problem. Consider the following case. Let's pretend that we should model the business relationships between a paper boy and the customer who wants to buy magazines at paperboy rings the doorbell. A customer opens it. A paperboy somehow has to be paid and then hand over a magazine to the customer. Let's look at the code. Example. Which models? The case. Here's a simple customer class, which has first and last names, and it also has a wallet off type world. Here you can see the wallet class. It is extremely simple. It just stores the decimal value, which determines the amount of money in the world. The client off the wallet. AP. I can add money to the wallet, can withdraw money and check the current amount of money. Looks good and simple. It is just fine and should fit our needs. The last thing is to implement the logic off a paper boy. Let's look inside the paper Boy class exposes a single method Deliver magazine, which takes the cost of the magazine and the customer toe, which your paper boy has to deliver. The magazine looks great. Let's look at the implementation. A paper boy just takes the wallet off the customer and then checks the amount of money. If there is enough money, the paper boy just takes the needed some. Otherwise, a paperboy just goes away. Great, one would say, But what do you think? Is it really great? If you think a little bit deeper, then you may come out with the idea that there is something strange in the fact that paper boy takes the wallet off a customer in order to be paid a paper boy has access to customers wanted. What a nonsense Would you be so kind to give your wallet toe unknown paperboys? I doubt so in this case that the violation off the lot off de Mita is obvious. The paper boy operates with a wallet through a customer. The first dot here in the code is when a paperboy takes the wallet. Then there's a second dog when he checks them out of money in the world, the same case when a paperboy withdraw some money to describe the problem more seriously, I should say that the main problem with this design is that the paper boy is being exposed to more information that he needs to be. All the problems are the consequences off this fact. So now these three classes are tightly coupled. If we change the wallet class, we may have to make changes to both of the other classes. By the way, if a wallet is now than a paper boy will throw than other reference exception. So it might be that in the real world Gold Base, the paper boy class will have to deal with it, introducing now checks and a second sequence cluttering the code. So how to fix the problem in order to fix the problem? Weaken. Just model the aerial world scenario. When a paperboys delivers a magazine, he just asks for a payment. Let's look at the improved design. Now. The customer class exposes a public method named Get Payment. While the underlying wallet object is now contained in a private field, no one except the customer has access to its wallet. The paper boy now is forced toe. Ask the customer to get a payment. The paper boy now does not have the rights and, by the way, the responsibility, as in the previous design, to fumble in the customer's wallet, so the improved design is better in three ways. First, it better models to the real world scenario. The paperboy code is now asking the customer for a payment. The paper boy does not have direct access to the wallet. Second, the wallet class can now change, and the paperboy is completely isolated from the change. Third were now free to change the implementation off the get payment method. To sum up, I want to say that the rule about the number of dots sometimes can be deceitful. The thing is that the law off Demeter is not about the number of dots. Actually, this law is about reducing the coupling and improving the encapsulation. When we're talking about data structures like data structures, which are exposed by the Excel document, it's perfectly fine When it's a P, I allows you dig the structure of the document like Excel document dot sheet dot cell else alone. The same can be applied to fluent AP eyes. When each call returns an object so you can build method chains, you'll see the math of chaining approach in the module about errors handling. So a Soleri's do not treat rules as dogmas and try to understand the underlying meaning off the rule. Instead of applying rules blindly 39. Temporal Coupling: temporal coupling between members is a well known smell, which means that there is a hidden interconnection between two members of an FBI, which requires the right sequence off calls made by a color. Let's look at the problem In practice, Mark Semen provides the following example. There is a class in the BCL named endpoint address builder. This is a factory for producing new endpoint addresses with specific property values. Consider the falling use case for the glass at the end point address Builder is designed in a way that the second call will fail at runtime because for using this builder, you have to at least provide a your eye so the following code will work fine. Yes, you can see there is a temporal coupling between setting the your eye property and a call to the two endpoints address method. In this case of the A, P, I developers could eliminate this kind of temporal coupling by requiring your eye in the constructor. Consider the following example Now an attempt to create empty endpoint address builder will fail at compile time. So by this simple way we can eliminate the temporal coupling between setting a property and call to a method which depends on the property value. Remember, always try to make invalid states unrepresented ble 40. Switch Statements: C sharp, as well as Java C, C plus plus and many other languages have a switch statement, which allows matching one value with another switch. Statement. Acts like multiple if statements, despite the fact that object oriented languages have. This. Which statement at their disposal switch statements is a procedural construct, not object oriented. It doesn't mean that's which statements are bad and should not be used in other languages or programs. Always makes procedural and, oh, approaches. It is coming to use. Which statements on in Yuma rations. Let's have a look at this case from my practice. You can see here an and, um, aeration named payment device motile. Some of these devices can dispense coins. Some can dispense bills, the other Candace pans, coins and the other can accept coins. Our team initially came up with the enumeration and used it everywhere. In switch statements. Look at the con feet class. It exposes several queries which answer to the color whether or not a concrete device is cash dispenser or accept er and so on. Each query uses switch statements in order to answer to the request. Imagine what will happen in a huge code base hundreds off switch statements everywhere. And do you know what will happen if someone extends? Then you narration. Yes, you're right. In such a case, you'd have to find all the corresponding to that enumeration, switch statements and modify them taking into account than you value. Added to that in Hume oration, this is a really painful What can you do about that? Look at the O. A way of dealing with multiple dispatch. In order to reflector an enumeration with switch statements, you have to create an abstract glass and give it the same name as in, um, aeration has. Then you need to define all the operations which you performed over that in admiration. In this case, I do find all the queries. After that, you have two great separate glasses which represent values of that in admiration. In this case, we need to create a separate class for each payment device model and inherited from the abstract glass Here. I defined the cash code payment device motile and implemented all the abstract members. Now, users off our A p I can rely on the abstract glass, thus harnessing the power off virtual Cole's provided by our old languages. Users off our A P. I do not need any switch statements anymore. Now we can extend the functionality in the appropriate places in the device. Model simply matters if we need to add one more device, weaken just at a new class inherited from the abstract glass and implement all the necessity remembers these satisfies of the so called open closed principle. It means that objects should be opened for extension but closed for modifications. Our are factored code can be extended by adding new classes. The previous one has to be modified everywhere in the code base. Remember, if you're sure that your enumeration will never be extended where you are not going to pollute all the code base, then you can stick with a couple of switch statements. In other cases, consider more object oriented design. Bear in mind that the O approach with many classes provides simpler extension if in you type required. But it makes harder to add new operations, since you will have to implement them in each class, so it's always in engineering. You have to decide what benefits are most important to you. It depends on the requirements off your application before going further. I want to mention one treek about re factoring switch statements. Sometimes switch statements are used for mapping one data to another or some data to some corresponding action and sometimes some data to several corresponding actions. You know that cases you may consider to use the approach based on using a dictionary. Since dictionary allows you to map data to data and data to actions, let's look at how the 1st 2 cases might look like in code. If you want to read more about the topic, click on telling attached to this lecture. Okay, here you can see a simple mapping from states to cities. Instead of repeating the same switches, you always can rely on a dictionary by introducing such a dictionary. You can always just request they needed city by requesting the dictionary. And, by the way, don't you feel like this approach looks much cleaner than the 1st 1 with a switch statement . In the second example, we have a function which calls to methods corresponding to certain in admiration values. Sticking with this approach, you might find yourself repeating the same ugly code many times in order to overcome the problem you introduced the dictionary, which maps in admiration values to corresponding methods. After that, you can call the dictionary to invoke methods thanks for delegates into shop, which allows us to easily map in an values to actions. 41. Refactoring to Strategy: the street is you. Pattern, which is also known as the policy pattern, is behavioral software design pattern that enables selecting an algorithm at run time. Instead of implementing a single algorithm directly, Gold receives around time instructions as to which, in the family off algorithms to use strategy. Let's the algorithm there I independently from clients that use it. Deferring the decision about which algorithm to use until around time allows the calling code to be more flexible and reusable. You'll see that the strategy pattern is closely related to the notion of dependence. Injection strategy always gets injected into a class in some way or another, usually via constructor, rarely via property or method. Let's switch to visual studio. You can see here the terminal class, which takes terminal type and I D in it's Constructor terminal, defines the Celtic It method. Look at it. It checks the type of a terminal and Iran's specific logic. According to the actual terminal type, the logic is quite different. Types used for selling a ticket are absolutely different. Lotus that all the responsibility for managing the selling process lays on the shoulders off the terminal class. Any new terminal type will cause the changes in this method, the terminal class will grow accordingly. To defeat the problem of too many responsibilities, we can apply the strategy pattern. So it first I'll declare the interface called I cellar and I'll define these cell function which accepts decimal price and string passenger data. Now I'll inherit these interface for service and carried exc service glasses. And now I can remove the parameters from the constructor and take the ice seller here. Now we can move the implementation logic to the corresponding classes which implement the ice seller interface down and with the post service the same thing. Great notice that the only thing now the Celtic it method ours is that delegates all the work to other class via general interface. Now, if a new terminal type comes up, the only thing we will do is that we will implement that interface. No changes would have to be introduced by the way we can remove the I. D. S. Well, the creation off the implementer off the ice seller interface now will be the responsibility off a client 42. Refactoring to State: Let's look at another case off potentially harm switch statements. Here we have a turnstile class which manages a turnstile. It can lock, unlock, reject a coin and launch the alarm. There are two states looked and unlocked and two events coin and pass, by the way, we have here the public into face. I turn style controller with four methods. The end to in admiration, state and event with two states. So the turnstile class takes an implementer off the I turn style controller interface that implementer would interact with a turnstile directly in the real world. The default state is locked to manage the turnstile. A cooler can call the handle event method passing an event. The implementation is based on this, which case in this case, it's even and nest. That's which case example is pretty simple. And because of that, the switch statement doesn't look extremely scary. However, I've seen nasty. It's which cases longer than several screens. Believe me, it was horrible. Changing such switch case blocks is like walking through a field full of mines. You never know where you will blow up. To defeat the problem, we can apply the state design pattern If you search for state on Wikipedia, you'll find that the state pattern is a behavioral software designed pattern that implements a state machine in an object oriented way. With the state Better estate Machine is implemented by implementing each individual state s A derived class off the state pattern interface and implementing state transitions by invoking methods defined by the better super class, the estate better and can be interpreted as a strategy pattern, which is able to switch the current strategy through invocations off methods defined in the patterns into face. This pattern is used to encapsulate variety behavior for the same object based on its internal state. Like in this case, these can be a cleaner way for an object to change its behavior at run time without resorting to a large, monolithic, conditional statements and thus improve maintain ability. So the main idea in our case is to encapsulate different states. For that, we need to expose an interface. Let's open another file. So let's earl out another into face. I turn style state with two methods. Coin, which will receive the instance of the turnstile class, will implement it in a minute. Uh, miss type coin and another event was passed. Okay, this interface exposes the events going and passed. Both methods take the turnstile instance as the argument. Since we have two states, we need tour allowed to. By the way, let's allowed a stub to in style to satisfy the compiler. Okay, and now implement to inheritors I'll co P and paste code I have prepared and the turnstile would look like this. We have two states here locked and unlocked, and the current state and all the methods like going and pass, said logs that unlocked, We'll change the current state and the actual actions like alarm, lock and unlock. They will call the corresponding methods On the Torrance style controller instance, states are encapsulated here. When an event happens, it gets handled by corresponding instance off a class which deals with that event. The state pattern has a major drawback, which shows itself when there are more than about, you know, seven states. I'm not even saying about 20 states or so that would look like hell and very hard to maintain. Since all the logic is scattered throughout many classes in case of many states, we should consider re factoring to table of transitions. Let's er factor the code to the table of transitions. And by the way, if you don't understand something here, you always Candelo the source code and try to understand it in a pace you prefer. For that, let's introduce the transition class for storing needed data. I mean, for a factoring to the table of transitions, let's implement the turn style class. At first we can declare the least of transitions and their default state. And now we can implement the constructor and a helper method at transition, which adds the transition to the least off transitions. So the constructor initialize is the list of transitions, and the remaining part is just to handle the events. And actually, it's quite simple. We just search here for they needed transition, change the state and called action pretty simple and enough powerful toe work with a great number of states 43. Common Architectural Design Smells Conclusion: Let's sum up what we've learned from this module. Firstly, we discussed the problem of primitives obsession. We found out that representing the concept off a zip code by the string type is a bad idea . Primitive obsession leads to a procedural clattered code over time and increases the maintenance cost. The law off the meter is a law which often me someday stewed. This law is not about number of dots. This law is about coupling between objects and improving encapsulation. In short, the object should not talk to strangers. Another topic we discussed is the smell of temporal coupling. The smell is about the interconnection between two members, often FBI, which requires the right sequence off calls made by color strive to avoid this smell by any means. The last but not least, is the topic about sweet statements. Generally speaking, it's which statement is not a smell by itself. Switch statement may become a smell if applied inappropriately. Switch statements can be a factor to the O designed with class forage statement by playing the template method designed pattern. Another option is to rely on a dictionary instead of his switch statement, and he also can apply strategy and state designed patterns to remove switch statements 44. Functional Programming Extendibility and Immutability Outline: Hi. This is injury or spark from in junior spoke dot com. The section is going to be very practical. The majority off taps were implemented even before extension methods feature was introduced , so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes get a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. The section covers programming paradigms and wife functional programming is beneficial. Mutability s one of the primary concerns off functional programming. The problem off mutable structures, temporal coupling and the mutability and how they are related to each other by blinding what it is and how by blinding differs in C shop and F sharp extending the I disposable interface allowing disposable types to be used to build coal chains extending string builder s an example demonstrating that we can extend anything we want implementing general extensions, saying General, I don't mean generic though most off general extensions are actually generic. I mean that we need to implement some extensions which allow us to compose objects which haven't been compose herbal yet primitive obsession, smell and how to struggle with it. The builder designed pattern how mutability helps in unit testing, handling errors in the functional style. This module is going to be quite long. Let's start with looking at different programming paradigms. 45. Programming Paradigms: you might be wondered, but a significant number of developers are even not aware of such programming. Paradigm is functional. Yes, believe me, I remember how I talked to one of my colleagues, and during our talk, I mentioned the functional programming paradigm. And he replied, Like what? Paradigm? He thought that Onley, object oriented and procedural programming exist. I was astonished by that kind of ignorance, since it's hard for me to imagine that a programmer with more than 15 years off experience haven't ever heard about functional programming. After that I realized that indeed, many programmers don't know what ISS functional programming, so let's talk a little bit about programming paradigms. It's quite hard to mark out the main programming paradigms, which paradigm to include and which exclude from such a list. Wikipedia says that the main programming paradigms are the following imperative programming structured and derived from a procedural programming declare a tive programming functional programming object oriented programming event driven programming and automata based programming. In fact, there are much more programming paradigms than in this list, so that least is far from being exhaustive. It's hard to tell why Wikipedia authors chose exactly these paradigm says the main ones. I even don't understand what the criteria was applied to filter the whole list off programming paradigms. I would say that if I had listed the top several programming paradigms, I would exclude the automated based paradigm and selected the aspect oriented paradigm instead, for example, but even in that least we see the functional paradigm. Functional programming paradigm or just functional programming, in short, is the oldest 1 60 years has passed since the first functional programming language appeared on the horizon's. I say this because I don't want you to have a feeling that functional programming is something very exotic. No one knows about it, and thus only nerds and Alfa geeks use it. This is far from being the truth. Actually, most off C sharp developers supply functional programming on everyday basis, being unconscious about that fact. Roughly speaking, generics and link you expressions in C sharp are the constructs weishar strongly related to functional programming. You see that method extension since the shop is one of the core parts on the way of a blank functional paradigm. I'm sure you know that See Shop is an object oriented programming language. However, most off modern programming languages are multiple enigmatic. Functional programming was brought into C sharp three with link you and method extensions Functional Paradigm enforces the mutability off types and operations s you may recall link . You'll methods return. I innumerable. What allows you to build method chain calls? The state off input stays unchanged. You always get newly created objects. C. Sharp is an imperative programming language as well, since you easily can mutate the state of objects when you write, Avoid method, which mutates the state of the object you right in the imperative programming style, object oriented programming is the primary style off see shop and functional paradigm. I would say the second by importance. It would be a lie if I had told you that functional programming is the main programming style and see shop. Unfortunately, it's not functional. Programming was not in mind. Off see shop inventors seemingly, however, now see Shop has method extensions and link you and other features. And all these features are so powerful that the functional paradigm can be implemented by harnessing some powerful techniques. Let's try to define functional programming in the next lecture 46. Defining Functional Programming: functional programming is a programming paradigm, a style of building the structure and elements of computer programs that treats compute ation as the evaluation off mathematical functions and avoids changing state and immutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead off statements in functional code that the output value off a function depends only on the arguments that are passed to the function. So calling a function F twice with the same value for an argument X produces the same result f off x each time. This is in contrast to procedures depending on the local or global state, which may produce different results at different times when called with the same arguments but a different program state eliminating side effects i e. Changes in states that do not depend on the function inputs can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development off functional programming. You can notice that we use the word function talking in terms off FB, and we tend to use the word method talking in terms off. Oh, this is because these two different paradigms street functions differently. Classic functions in F B are true mathematical functions, which return the same result as the answer to the same input, and a function expresses all the information about itself in its signature. It transforms the input to the output. Now we can see the difference between O P and F B. Yes, Michael Feathers. One sad oh max code understandable by encapsulating moving parts, F B makes goto understandable by minimizing moving parts. Oh is all about changing states of objects, whereas FB tries to avoid state changes at any means. If B implies that we build a system by sticking independent functions together, every function just depends on the input it receives and doesn't depend on any external state. F B is a paradigm which concentrates on computing results rather than on performing actions . You'll soon practice what it means very soon. As a result, programs written in a functional style are generally more predictable, easier to maintain and easier to test. Since you need to test independent functions, that means you don't need to use difficult marking techniques and other advanced oh approaches to achieve testable design. Oh, and the speed try to achieve the same goals with different approaches. Let's talk a little bit about functions in the next lecture. 47. Functions Are Everywhere: the core concept off the object oriented programming is object. In Si shop, you even can declare a function outside of class. It is sin tactically impossible. I remember how I was astonished by this fact after programming in Old visual Basic, where we could declare global functions. Functional paradigm is based on the functions. Functions are the first glass citizens in cold basis. An interesting fact is that the best practices off implementing functions in Opie languages are lined with Howie right functions in functional languages. Here are those best practices. Keep functions small. Don't repeat yourself. There should be only one source off. Authoritative knowledge functions have to do only one thing. Avoid side effects. Functions should accept no more than three parameters. I like joke from the talk at NDC by scott slash In Every oh programmer knows about classic design patterns and principles and all the related stuff to tackle the regular standard problems which arise in the everyday basis, we'll know them single responsibility principle, open closed principal dependence, inversion principle and other solid principles. Strategy pattern, abstract factory pattern, decorated pattern visit or pattern terms of patterns. If we try to convert all these concepts into functional ones end up with the following. SRP transforms into functions so Sir Peas function soaks, appease functions in F B D eyepiece functions in F B strategy. Pattern is functions in F B abstract factories, functions, functions, functions, functions. Everything is functions in functional programming. This is, ah, humorous definition of the functional programming, which is very close by the way to the reality. Let's talk about why you need to learn more about functional programming. 48. Why Functional Programming: so you may ask yourself again, why would they need to learn functional programming? You may also think that you'll never use a truly functional programming language. However, you don't need to learn truly f B language to harness the power of FBI ideas. Apart from that, you'll get a better developer learning new programming concepts and looking at the same code base from other perspectives. Considering different concepts. Believe me, after learning new fundamental programming concepts, you'll get a fresh look at what you did before. If I'd need to mark out the benefits off a functional programming style, I would list the following. Minimizing the code base functional style in the end leads to them more understandable and shorter. Code functional programming leads to constructing more compose herbal components, which have very high reusability. These benefits are very important, especially in enterprise development field. Since domains become more difficult to understand on every year basis, there is another benefit we haven't marked out yet. Local currency didn't expect yes. Indeed, a truly functional program is safe for concurrent access by default. The main problem of concurrent access is the possibility off damaging the shared state in the functional programming. There is nothing to damage scenes. There is no shared state. This is also one of the reasons which explain why functional programs are safer. They're more predictable. Okay, as was said before, functional paradigm in forces in mutability, off types functions with outside the facts and improved compose ability, off types and functions. Following all these principles together will lead you to improve design off your applications. 49. Immutability: in mutability is one of the core concepts in functional programming. When are talking about mutability, we imply mutable or immutable objects. So what does it mean for an object to be immutable? It means that such an object doesn't mutate or change. In other words, it's internal state. Junior developers often get confused when hear about the mutability for the first time. Indeed, how is it possible to implement on an immutable type? However, any see shop developer can recall that this drink type is actually mutable. When you change the string instance, you get in you modified string. Instance. As a result, the initial instance Original one stays unchanged. This is a mutability, in essence. Okay, then let's look at a very simple code snippet. Here is the character class. Is this glass immutable? No, of course not. This class is mutable. The heat method mutates the internal state. It changes the value off the health property. We can't say that this is a very bad piece of code. However, we can make it better. We can make it immutable, automatically making it safe for concurrent access. At least, Actually, the benefits are more profound, and you'll see that later. So how to make this type immutable easily. Look at this. The heat method now returns a new instance on each call. It doesn't mutate the internal state anymore. This is exactly how the string type is implemented. Well, actually, not exactly, but similarly, let's look at another example, which demonstrates how mutability reduces readability. The first glass we see here is called a rectangle. This type is mutable, since the scale method mutates the internal state, the width and height properties. The next type we have here is called al Apps, and it takes a rectangle instance in It's Constructor. It takes their tangle to draw itself around that rectangle. We don't have a full blown implementation, since it doesn't matter from the learning perspectives. And now is the most interesting thing. Let's look at the client's code Logically. The color at first greats, in instance, of their Kangol type var wrecked equals new rectangle pressing, say, 10 and 20 as the arguments. And now the cooler should create an instance of the Ellipse type. So we were at a lips e l equals new al IPs passing that rectangle instance. And now let's scale Derek Tingle by the factor off to Uh huh, Interesting Looks nice looking only at this piece of clients code can you understand what will happen to the Ellipse after scaling their tangle. Seems like we mutate the internal state of their tangle Instance. But will the size off the al apps change correspondingly? Mm, This example demonstrates how mutability reduces their readability. Let's look at how we can improve design off these toy example. I'll co p and pace to these example into a new source file and change it to make their tangle immutable, weaken do the same trick we've done to the character type. Let's look at how the clients go change. Uh huh. Now we see that the scale method that returns in your instance off the rectangle type. That off course means that the Alps stays unchanged since the internal state off. Their tangle type obviously stays unchanged in the first place. That is a small but a very important improvement, which increases irritability and improves the predictability off the programs behavior. Let's look in the next lecture how to defeat the problem off temporal coupling by enforcing mutability 50. Immutability of Structs: Why do we need to learn about mutable structures? A great number of developers underestimate the potential harm that can be caused by an appropriate implementation off structures. Let's start investigating the problem. One of the most popular questions on interviews for C Sharp developers is what's the difference between class and structure? Most interviewers expect that you'll answer that glasses are referenced types allocated on the heap, whereas structures are value types allocated on the stack. Most of the candidates answer exactly that. While this is mostly correct, the deeper answer is different. The main difference between structures and classes is that structures implement the semantic off copping by value were asked glasses, implement of the semantic off, copping by reference. This is the most important aspect, especially from the A P I. Designing perspective. The only case when allocation method matters is the case of performance problems. If profiling data shows your riel problems than you might be interested in converting reference types into value types, let's consider a good and bad examples off using structures. Let's switch to a visual studio and look at an example. Here is a structure named Mutable, which contains an integer value It also has a public method which increments that integer value by one and returns the result. This is a very bad I D. And you'll see why very soon. Consider also the following client code. We have a glass named a here, which contains three members of type mutable. The 1st 1 is a property with getter. The 2nd 1 is a public Redon left field, and the 3rd 1 is a regular field without any additional modifiers. In the main method, we make three call players to the increments X method for each case. What do you think will be printed out to the console both in the first and second cases, one wanna will bring it out, while in the third case it will be 12 Let's explain why this is so. In the first case, we work with a property which has a somatic off returning a value. It leads to copping a new valley on each call. So each call to the property mutable returns a brand new copy off the mutable structure. That's why incriminating doesn't work. The second case is the interesting one. Seems like we have a direct access to a variable here. But the thing is that compiler generates temporal variable for calls to redundant feels so in the reality it will look like in the following code snippet. In the third case, we have a direct access to the structure instance. So in both goals we work with the same instance. Do you feel how bad the design of the structure is? It's a pure evil. This is because that structure, which implements the copy by value semantic by the language design, is implemented. A sim you double reference type in the code. Let's look at a good example of a structure. Here. You can see the point structure, which contains two values of type in. It exposes the increments operation, which always return in your instance off a structure so we don't modify the internal state of the instance. We just always create a new one. This is true in mutability. It's impossible to misuse the time which is designed in this way. Mutability logically implies referential identity. Values do not have a referential identity. That's why they're called value types, not reference types. If you need to mutate something, make it a reference type 51. Temporal Coupling and Immutability: This is a second part which demonstrates the problem off temporal coupling from another angle from the angle, often mutability in object oriented and functional programming. An immutable object unchangeable object is an object whose state cannot be modified after it is created. This is in contrast to immutable object changeable object, which can be modified after it's created. Immutable objects are usually comprised off so called pure functions, which do not cause side effects. In other words, they do not change the state off the object and surprisingly temporal coupling depends on in mutability. Let's look at the problem more closely. Here is an example which demonstrates the problem. This class takes the board size and players name as the arguments in the start method, and the most interesting goes in the start Methods body firstly, eat grades and object off the player type by calling their create Blair method. Passing in the player name. Right after that, it calls the create board method, passing in the board size to create an object off type board. If you look at the create board method, you'll notice that it also passes in the constructor, the player object. In the end it caused the start game method, which creates the game object passing to its constructor. The board object and finally calls the start method. I wrote such functions as the start function many times myself. What's wrong with it? The things that all the three functions are coupled in a sense off gold sequence, you have to keep the calls to ride in the order they're now. Unfortunately, nothing protects us from rearranging them. I can easily so up calls like this or like this done. The code is broken and nothing indicates the problem off inconsistent calls from the first side. If we know nothing about the code, we can say that something is wrong here. Despite that, this code won't work. It will fail in the round time. The worst possible thing why this is happening to us. What is the reason of the problem? The primary reason is the two functions create Blair and Great board cause side effects. They change the state of the object. Another reason and this is the consequence of the first reason, is that all the three functions share state that state change it by two functions. Let's get rid of the side effects and look at the result. - The effect Erred version doesn't have any estate anymore. There is nothing to share. Those two functions which mutated the state are now turned into pure functions, which don't cause any side effects. They accept arguments and return the results. Just a syrah Giller Mathematical functions do now. We don't need to keep in mind the right sequence of calls. You can't mass them. Let's try to do that. It won't compile. One call logically flows to another call. Now, functions explicitly demonstrate that they're connected. Biological data flow between them. Okay, I cheated on you a little bit. There's a steel aside the fact, and it hides in the start game method. This method doesn't return anything, and it calls the mutating operation, which is called start game. We don't know why the game class was implemented this way and actually doesn't matter. We can't avoid side effects totally, and it's fine. Mutating is a usual thing, especially at the external bounder Zoff, a system such as user interface or a database. So try to avoid mutating functions as much as possible. It makes your code much easier to read and understand, and thus more maintainable 52. Pipelining: by planning is a technique which allows and out off one function to be passed to the next one. This allows organizing the natural flow of data. At first, let's consider a counter example. Consider the next code snippet. The reading order off this coat is reverted from the human point of view because in order to understand the meaning of this code, you have to read it from the innermost statement to the outermost. Sometimes you can find yourself writing such cold with foreign five levels off nasty. Why would write code like this? This is because we don't want to introduce unimportant intermediate variables like in the following example. The previous gold sample is rewritten here with intermediate variables. We don't like such cold as well as the previous one we have here meaningless variables. We actually don't need them by planning. Is this so neat and powerful technique that, for example, F. Sharp has a so called by blind operator? The previous example would look like this Enough shop. This coat can be read naturally because it goes straight forward. Unfortunately, we don't have such an operator building so shop. Whether we can do about that is to chain methods, methods. Chaining is a functional style architectural better, which has to be supported by types, since the programming language does not support by planning explicitly. 53. Extending IDisposable: a significant number of types building the BCL are disposable. What means they inherit from the I disposable interface. Let's look at an example right away. You have a par sur named data sparser. The sparser processes a file in ah see SV format like this. A line contains two parts timestamp and the actual value the data Parsa exposes two methods . The 1st 1 is the ST Ick factor method to construct the object and the 2nd 1 allows to get values from the parcel. The factor method is preferred in such a case. Since he drowns a potential a long running operation. It's a bet practice to cram a long grinding operations into constructors. If you want to learn more about the best practice of building a P I since the shop, I encourage you to take my course AP and see shop The best practices of design and implementation. So and the constructor is private here. Okay, then what? The crate from string method actually does. It does what it says. It takes the continent s a string and parses it. At first, it splits the content by the new lion D limiter. After that, it goes through the air a splitting lines by the call on dealing Inter, adding the parse data into the corresponding dictionary. The cold is pretty procedural and we will tweak it. Of course, just in a couple of minutes. The value method just retrieves the value from a dictionary taking a time stamp as an argument. Unfortunately, this method can return now in case there is no corresponding data. Now values are what ruins functional style. So we will talk about removing now's in a separate section. For now, we will leave these unfortunate fact s cities. Let's look at the client's code. The manager glass contains the process method, which tries to use the data parcel. He defines a reference at first. Then it uses the stream reader wrapped in the using statement to read the file and construct an instance off the data Parsa type. Finally, it reads a value. As you see this goal this procedure less well only Imagine that this gold was the only way to do what we need before C sharp three. Let's see how to make this gold better. Well, I would extract out the construction off the data. Parse er, let's do that great. That was a tiny improvement not related to the functional programming. To convert the construction process into functional code, we need to enable building off gold chains on the I disposable types. Look at what we actually do here will create a type data parcel by using another type stream reader. We map one type to another. Actually, both parts can be represented by corresponding function signatures. Let's create a type which perhaps the using statement and allows to convert one type to another. We need an extension which can be applied to a type which inherits from the I disposable. So I'll create the state. A class tour allowed an extension method. Now I should implement an extension left, which has to work with two different types, one of which is I disposable. I'll name this method using and declare to generics. The first function which creates the disposable type instance, is going to be represented by the fund coffee, tea disposable and the function, which converts one type to another, is going to be represented by fun cough T disposable entity result. We also need to declare that the tea disposable has to inherit from the I disposable, so we need to ride the wear clothes. The remaining part should compose the functions. We accept its arguments. Everything is simple. The factory funk is wrapped by using statement and the resulting disposable type we passed to the funk, which converts one type to another. Let's look at how we can use this function now. - Look at how nature of this flow looks. Yes, we didn't reduce the number of Flynt's, but that was not the goal. The goal was to enable cold chains building. The syntax is not so appealing as in F sharp, but this is the price we have to pay for the fact that C Sharp is primarily an object oriented language rather than functional. Do you see the last line where we passed the value to the right line method? We can remove even these call, inserting it in our flow off consecutive calls. You'll see the corresponding technique in a couple of minutes. This technique is very powerful when we extend everything and use all the functional techniques In conjunction, you'll see other techniques like errors handling in the functional style. Further, in the end, you often right up to seven calls, and that becomes much more readable and safe. The benefits become apparent. Let's look at how we can improve the method which parses the content. Luke, how great it looks, how it is expressive. Okay, that was a great exercise. 54. General Extensions: in this lecture, we're going to fulfill the empty spaces on the way of building coal chains everywhere we want. The first problem I want to talk about is the problem you've seen in the lecture about extending the I disposable interface. Let's look at the client's code, which used the data Parsa, FBI charities. I'm sure you remember that. I said. We can stick the right line. Call toe the cold chain. Right now, the right line call looks like an orphaned procedural call. The general problem here is that we often need to pass an intermediate result into a call and then be able to continue our cold chain. Imagine that we need to log some value right in the middle of the cold chain. That's a quite common task. How to do that. I'm sure you know how to achieve what we want when you to implement an extension to make this possible, And this extension is going to be quite simple. Let's great in U. C s file for implementing general extensions, and it's going to be public ST ick in terms of programming. We need a function in this case, which passes down an instance off the current type two in action and then the returns, that instance back without any changes made to it. Let's implement it. There is an agreement about the name off this commonly used function we call it T. It takes an action, which accepts an argument of type T. It just calls the actions passing the argument and then returns the instance on which the cold was made without any changes. As we said before, everything is pretty simple here. Let's use this function to remove the orphans. Procedure will call. Let's get back. Oh, look at how nice it is, by the way, we even can convert it into a group call. This is even shorter. Sometimes we need to convert one type to another. By the way, it also happens in the middle of the cold chain. Often we start to build a cold chain on one type, then convert that type and continue to build a culture in on another type. Actually, we implemented an extension with a similar functionality. That was the extension off thy disposable type. But that was a special case with inherited I disposable interface, for example, we might want to convert the string instance into daytime instance. Let's right, the General extension for the purpose. This function is pretty simple. It works with two types, converting one to another so the signature will be the following would we need to do is just to call the map funk. Passing the source instance, I noticed that I used the expression bodied members in tax. We can do this without that Syntex, but that Syntex isn't the spirit of functional programming. Now we can use this extension to convert any type to another. The mapper should be provided at the client's side. Let's go back and use it. How nice. By the way, do you remember one off our first extension methods? We extended the daytime to convert the well into a device format. Nothing stops us from continuing the cold chain. The power of this technique is a manse. Imagine how this code would look like in a procedural style. This code is readable like a well written prose. Let's look at another case where we need a general purpose extension method. Sometimes we need to tweak the valley, which flows down the cold chain, depending on some condition. Mathematicians referred to conditions as to the so called Braddock, it's treat these terms equally. So. Imagine that, actually, the process method takes the time stamp as an argument. And it also takes an argument which says, whether we need to convert the daytime value into UTC before converting it into a device compliant format. By the way, I already added these arguments. I'll just use here the time stamp and I want to convert the daytime well into UTC when convert UTC flag is true. Sounds like we need a general extension, which takes to fund delegates. Let's implement it. - I called this extension when, Since you have a predicated here, depending on which we either passed the value into the processing function or not. If the Braddock it returns to, we call the processor. Otherwise we returned the original instance. Let's apply this extension to our example. Actually, this is a very bad practice of converting one day time a value to another. But this is a different story. If you want to learn the best practices related to working with dates and times, take my course dating time. Fundamentals in the Net on Sequel server Look at how nice the cold chain looks like I absolutely love it. Let's convert it into procedural code and compared to pieces off cold, hear how it would look like in case of procedural programming. But, well, I'm not going to lie. If you're just starting to practise functional programming, then the cold chain we built my puzzle us well as the procedural piece of code, However, there is a huge difference. Functional style cold chains will be much more readable to you as soon as you get enough practice in functional programming. I can't say the same regarding the procedural cold. It will always be obscure, and the main idea off a piece of code will stay obscure until you read and understand all the procedural piece of code. Procedural code introduces too much semantical noise into code. Functional style reduces this problem down to almost zero. Let's improve another piece of code with the power of general extensions, which are now it's our disposal. By the way, we can write the so many general extension sense we want in. Then you'll end up with a library off infrastructural code, which enables functional style of programming. You will extend that library for sure because there are many overloads required to apply functional style everywhere we want. Okay, let's get to the next lecture and practice What we learned. Repetition is the mother of learning. 55. Extending StringBuilder: in this lecture, we're going to investigate one off cases from my own practice. Example. We're going toe work was modified and doesn't reflect the whole validation sequence implemented in the real world. However, the example is very close to the reality. Yes, I already said I developed a piece of software for point of service terminals which saw tickets for suburban trains. There was a case when a passenger could travel without a ticket because not all stations had ticket offices. In such a case, that passenger had to be able to approach a terminal at the arrival station and feel a special form. I don't want to dive deeper into why the Hackl. The things worked as they worked. Everything just worked this, I'm saying. So I needed to build a special report and then sanded by the network. Look at this code who have a pokal plain old CLR object here named Traveling for which store some data filled by a user. After that, we have a view model which declared traveling for as property and terminal info, which in the real world came from the upset ing's. When users done, he clicks on a button and the finish method fires up to create a report. Okay, We call the corresponding method off the report factor class In the real world, that method wasn't static, but it doesn't matter for our discussion. Look at the method we're going to re factor. The method is written in a completely procedural or imperative style math. It creates an instance of string builder, then append align with two calls, then validates the carding for end in case of true appends. One specific line. Otherwise it depends another line. After that it depends. Another one line with two calls. And then it goes through the least of terminal data, upending that data in a specific format. Looks like hell off course. I intentionally made this example look so bad we can make better by the means off object oriented programming. However functional style would be better. Anyway, let's start to reflector this piece of code right away. At first, we need to remove to line way offending a formatted line. Let's do this with the power of extensions. - I created a separate state of glass for holding extensions off the string builder type. The extension I created takes two arguments the 1st 1 is the string and the 2nd 1 for the string arguments. Everything is pretty simple and doesn't differ from what we did before. Let's apply this to simplify our code. I'll get back and replace old a pen format and depend line goals to our new extension. - Great many alliance of cold have gone the call to the validate method and the corresponding logic resembles what we did with Wen Method. In this case, we need to roll out an overloaded version off that extension to be able to pass the handler of the failure or negative path. - Great . Let's get back and improve our code. Great. Finally, we need to remove the procedural loop. For that, we need to implement one more extension. - This extension is a little bit tricker. Sometimes you can get confused by the aggregate linke method. If you want to learn more about link, you take a corresponding course on you to meet. I'll get back and apply the newly created extension. - Finally , we can just call the to string method, returning the result who look at how nice this piece of code looks like. It is succeed and well readable. It is a pleasure to read such gold. One would say that we could avoid creating the upend formatted line extension and he would be right before C Sharp seeks. We could replace to calls by one called to upend line, injecting the string format inside. Look at it looks very ugly. Before C Sharp seeks, I would encourage you to rely on the extension method. After C Sharp six was introduced, I would agree that we could use the string interpolation feature instead of the extension method. Look at it looks beautiful. Noticed that string interpolation is also a feature related to functional programming. I decided to implement an extension method just to practice a little bit. Nothing more. I hope you enjoyed these sessions off, re factoring and learn many interesting and useful tricks. 56. Primitive Obsession Abusing Extension Methods: I already mentioned the primitive obsession smell. However, I would talk about the smell once again taking into account extension methods we discussed and applied in this section widely, the section shows how powerful method extensions can be. However literally any good feature can be abused with the feature of extension methods is not an exception from the rule. But before demonstrating you an example where extension methods actually to know. But practice, Let me tell you a short story. There is a widespread opinion that decimal type is money by the way, we even at the M Asaf ICS two decimal values. However, there is a tiny but extremely important difference between being money and being a tool for representing money. So decimal is not money decimal was invented for representing them. Let me explain in more depth the problem off representing money. In the rest of this lecture, I'm going to talk about money type as an obstruction instead of using decimal type for presenting money values. In the last project I have been participating in, we relied on the decimal and integer types for a long time. From the beginning, we knew that using primitive types for values off that kind is an anti pattern, but we stubbornly have been using them. This will loan anti pattern is called primitive Obsession, representing I P Address as a string or representing zip code. There's a string are quite good examples off these anti pattern. In short, zip code email i p address are in love complex concepts, which have to be represented by high level classes that encapsulate rules protecting in variants, which belonged to the implementation off a complex concept. If you represent emails using strings, then anyone can pass any string they want. It's an email mayna. Rules can be encapsulated inside the class such a zip code, for example. It can contain the mapping between codes and regions or something else representing zip codes by strings. You'll eventually see that all the logic related to ZIP codes is spread over the code base . So let's get back to the problem of representing money values in the US There are scents and dollars in the Russian Federation rubles and Coptics, while ruble equals 100 coptics. So our System Inter operated with an external system which performed all its calculations in Coptics, represented as integers it required topics as the input and return Coptics as the output if we wanted to pass in two rubles and 50 topics than we passed in the following variable, and we haven't seen any problems up to a certain time. But those coptics represented in in 32 started to spread throughout the whole system. In many cases, we've had to convert them into decimal type to correctly display the value on the screen. You definitely don't want to show users 250 car picks. You want to show two rubles, 50 car picks. In other cases when we handled users input off money values, we've had to convert them into complex in order to pass it'll into that external system. Eventually we found ourselves in writing the following function these function except toe arguments and have to answer other any mismatches between counters dispensing event arcs contained for integers that represent money values expressed in complex. As you can see, this go is very smelly. This is actually a ball of mud everywhere you have to elicit What are you working with right now with topics or rubles? Then you have to convert them in tow. Either Coptics or rubles, depending on the case, and only after that you can compare them from converting topics two rubles and vice versa. We wrote to extension methods called cop to Rubio and group to cop. Grating extension methods on primitive types is the first sign of the disease. So we ended up converting money values everywhere in our code base, even if you manage to avoid conversions in your domain logic, such conversions with last extension methods, will stand the boundaries off your application. You always have to be sure that you work with in a property type with an appropriate value stored in the type without riel protection. In the end, we decided to solve the problem by introducing money structure. It's a form of value object design pattern. Let's look at the money struck. This particular structure is made specifically for Russian currency. Imagine what will happen if you need to work with different currencies. How the hell Willy Hello? Different currencies with different exchange rates, which, by the way, change frequently. Decimal is not enough. In such cases, you'd need something like this money structure or maybe a class just more sophisticated. The idea is that you need some kind of abstract entity to represent a complex concept. This is the only way to go. So these money structure implements like Willie to compare, and I comparable to simplify comparisons on the client side. It defines the private constructor that takes decimal. The only way to get the money instance is to use either from Coptics or from rubles maths, passing either Coptics as long or rubles as decimal. In case your money is suited for a specific currency, that's a good idea. And here's why. Imagine that we made a construct republic but then declined Can ride the following code. What is that? $200 or 200 cents? This is also the reason why it is bad to allow implicit casts. It is bad in both cases, either. It's allowed to implicitly convert longer decimal into money. Really? Will you be sure that the expression money M equals 200 m does mean that it's $200? Maybe someone just put AM in order to compile it, but actually wanted to initialize it by $2. Consider the following to perform, add and subtract operations. I override the corresponding operators. The conclusion is that decimal is a good time. However, you should not examine the anti pattern called primitive obsession. Rely on an abstraction instead. Otherwise, you will spend hours to effect er, the mess you brought to a project. It's also extremely easy to introduce box relying on primitive types. Remember, primitive types cannot reflect conceptions. Money is the concept. Decimal is close, but very often not enough. Don't try to cure any disease by the power of extension methods. Any tool should be applied where appropriate, don't apply to just because it doesn't feed from the first sight. 57. Builder Design Pattern: I want to show you a builder pattern, which is related to mutability and specifically suited for building objects and composed them in a functional way. Actually, the overall idea off the builder pattern is that changes made to the state reflect in newly created objects. Let's look again at a simple classic example where the builder pattern is simplified. Here we have a class named person. It exposes three read only properties age, name and phones, the classes completely immutable. But this is another topic to simplify the process of building an instance off this type, we expose methods with name with age and with phones each of these methods to recreate the instance through the constructor coping properties, which has been already set and passing down the accepted argument. This technique provides the so called fluent A P I, which is very neat at the client's side. Look at how can we use such an object? He would create an instance of the person type passing the novel at this stage off construction if we need to update the instance later, adding the name we can harness the fluent a die, calling their with name method very cool And by the way, if we need to reset the age, for example, then we can build a chain of calls like this. For example, looks very cool and super readable. I love frameworks, which provide fluent AP. I were possible, since that kind off a prize are very simple and easy to understand. Maybe you don't see so many benefits right here in this example, though I see. If so, let's look at another case. Let's say we have a phone service. Let's say we have a phone service class which, except three related service into faces called High Connection I GPS and I Speed Sensor. This example is from my practice. The only difference is that classes and interfaces a renamed. I mean that I worked with same design with same structure. We very often need to write a high level object which interacts with several services. We have a method named number of Steps Met, which checks that the number of steps made by the phones holder meet the required number of steps per day. The code is, of course, synthetic here, but it's very similar to the real world scenarios. At first we connect to some kind of service. Then we get from Japan as the number of steps and perform some business logic. Logically, we need to be able to test this method somehow. I mean to write the union test. We need to replace the GPS service by a mark object, which is under our control we needed because the logic depends on the value returned from the GPS service. Imagine that the phone service has many methods with logic that we need to cover by unit tests. Thus, we off course will replace not only repair service, but the other as well. At first, let's look at the bed way off writing unit tests. Here is the test, which checks that the number of steps met returns Matt in case 5000 steps were made to construct the full serves. With GPS under our control, we need to create a mark object. I named it Jubeir smoke. It's a very simple mark which allows to set the number of steps. This number of steps will be returned in the function under test. Let's get back right after creating the mark, we grade the fall service, passing the connection as a stub which does nothing are mark object. And now, as the I speed sensor. After that, we call the method on the test and assert the result. Usually we don't want to see the dependencies which are not required in this case. I don't like that we pollute the test by the information that we passed the connection. And now as thy speed sensor, when the number off unit tests grow, you end up with creating the following methods here are they. We create the get with connection to hide all the dependencies except the eye connection. Get with GPS and connection and get with GPS and connection and censor who also may want to create, get with GPS method, get with sensor method or just rely on the method which accepts all the possible arguments . What doesn't make a difference to the original way of constructing the system under test? I'm sure you see how ugly this is. And the first way of straightforward creation of the system under test is actually better. However, it doesn't mean that we can do nothing about this problem. We can simplify the building process, applying the builder bathroom. In this case, we're going to create a separate builder, rather than adding specific methods to the phone service time. At first, I'll name the class almost always named the builders. We need to store the dependencies, so I'm going to create the corresponding feels. Now we can use the same technique to allow fluently construct the object These three methods allowed to replace each of the dependencies. However, as you might notice, we returned the phone service builder, but we need to return the phone service. That's why we also should add the build method. The building method is a command to construct the object when we're assured that everything is configured as we want. Now let's write a good unit test. At first we need to configure the mark object. Let's do this now. We can construct the system under test. Look at how nice this looks like. We don't need anything else. All the possible variations of dependencies are covered. Just call those with methods, which you need to and finally build the object. Very nice. It's definitely better than what we've done before. The maintain ability off such a test is much higher. Remember this technique? Finally, we call the method under test and verify the outcome. Let's run the test and ensure that everything works as expected. Yes, the test passes Nice. We've done a great job. 58. Errors and Functional Programming: exceptions contradict with the functional style of programming. The thing is that functions from the functional programming paradigm point off, you have to be represented as mathematical functions. What it means is that a function should produce the same result for the same input, and they should not produce any side effects. Exceptions are side effects. By their nature. They cannot be expressed in the method signature. Because of that, developers have to drill down the call stack in order to understand possible outcomes from a particular method. Consider the following example. When you stumble upon such code, you start to ask yourself whether this piece of code contains a bag or not. Why the transfer money method does not wrap a call to the validate payment method in to try catch block. In order to understand it, you have to read the content off the validate payment method. We can conclude that exceptions hide the possible bad outcome off the methods. Call the fail er off. Any validation method belongs to the class off recoverable user errors. It means that it is exactly the case when we need to get rid of exceptions in order to get rid off exceptions, we need to include them into the function signatures. In some cases, we need to include the reason of feller so we can't rely on a bullets like anyway, Out parameters often lead to unreadable dirty code. Thus we will introduce the result glass. Let's look at how it looks like. Actually, we have to result glasses here, General one and Result Off T, which contains the resulting object. Let's look at the General one. The result contains three properties is success Bolan Flag, which returns true in the case of successful result, often operation and otherwise false. The air property of type string contains the description off a failure and his failure is introduced for the sake of convenience. Let's look at the constructor. The constructor is protected. What dip? Rick Gates. That explicit creation off result Object a little bit further. You can see a bunch off state recreationally. Methods fail fail of tea success and successive T methods with generics are used for the creation off. A result object with a stored value inside. The result Off T class just extensive. The result class and brings the T value property for storing a result value. Okay, before looking at how to use the result. Glass. Let's take a step back and look at the concept off pipe lining. 59. Handling Errors by Methods Chaining: by planning is a technique which allows and out off one function to be passed to the next one. This allows organizing the natural flow of data. At first, let's consider a counter example. Consider the next code snippet. The reading order off this coat is reverted from the human point of view because in order to understand the meaning of this code, you have to read it from the innermost statement to the outermost. Sometimes you can find yourself writing such cold with foreign five levels off nasty. Why would write code like this? This is because we don't want to introduce unimportant intermediate variables like in the following example. The previous gold sample is rewritten here with intermediate variables. We don't like such cold as well as the previous one we have here meaningless variables. We actually don't need them by planning. Is this so neat and powerful technique that, for example, F. Sharp has a so called by blind operator? The previous example would look like this Enough shop. This coat can be read naturally because it goes straight forward. Unfortunately, we don't have such an operator building so shop. Whether we can do about that is to chain methods. Methods. Chaining is a functional style architectural better, which has to be supported by types, since the programming language does not support by planning explicitly link you was designed bearing in mind functional concepts like by planning. That's why you can chain methods like Ranch, where ski P two least and so on. Another example. Off methods. Chaining without in Q is the string builder, which was developed in such a way that you can change depending methods. Here is an example. This is possible because a pant Abend line and depend format methods return updated string builder object instance. That's why you can change these methods. Let's look at how we can chain methods on the result glass. The same approach we used in our result glass. The success and failure methods return a result instance. In order to organize the control flow, we also need to add extension methods. Look at the extension methods we need. We need to manage the control flow in the case off success and failure, the on success extension except the funk delegate, which in its turn returns a result. Instance. Let's look at an example off using these extensions we have a student glass which exposes to methods which can fail so they return result the result example. Class uses the student class in the process. Student method. Look at the content of this method we return. Here is the result off a sequence off operations. Firstly, we tried to in the role a student if the operation failed, we look some information to the console and returned from the method the result of the enroll method. If a girl finished successfully, then we try to pay a grant for the student. If this operation fails, we lock some information to the console and return the result off the pay grant operation. If the big grand operation finishes successfully, then we returned a successful result from the process student method. Notice that this is a flat method with a cyclo Matic complexity off one since there are no any if statements, the functional approach is very powerful. Just try to use the Result class for handling recoverable user errors and extend existing BCL classes with extension methods when possible. Very often, you can drastically simplify your code based by applying functional principles both to the overall design off your application and handling off errors. Look at another example off her. Factoring made by using the result moment. Here, you can see a horrible method polluted with trackage blocks, which spans more than 40 lines. It can vary factored into simple method by using the result moment. Look at the result of such a factoring wow. These methods spends just 11 lines. This is a significant accomplishment. This method is much simpler than the previous one. To sum up, let's consider a bunch off method signatures. If you rely on the result glass and functional approach, then you should explicitly state within your team. The following commands which return void should not fail ever commands which returned. A result may fail, and a cooler has to deal with it. Queries which returned directly. The object should not fail. They always should return an instance off the type, they declared as the return type queries which returned. The result Off T may fail and a cooler has to deal with it. 60. Functional Programming Extendibility and Immutability Conclusion: congratulations. You reached the end of the section. That was an interesting section full of functional programming techniques. Let's recap what he learned. Functional programming helps to minimize the code base. Functional style, in the end, leads to the more understandable and shorter code it leads to constructing. More compose herbal components, which have very high res ability. Mutability helps to remove side effects. Making the code base more reliable in mutability makes functionality protected from multi threaded access in mutability is especially important for structures. Mutable structures are extremely dangerous because of their nature off copying by value. Mutability removes the temporal coupling between functions. It makes code more testable and easier to use that you learned that by blinding looks more natural enough sharp rather than in C shop. This is an unfortunate thing, which result in a more clunky syntax into the shop. When we try to bring functional programming into play, this is a price we have to pay. You learned that the I disposable interface is easily extendable as well as any other interfaces and can be used to build the cold chains. You learned the concrete example of extending the stream reader type, which inherits from the I disposable. Any conversions passes off arguments, map ings and other mechanisms off managing the control flow are possible in functional programming into shop. Thanks to limitless extend ability, feature off the shop. Built any general purpose extensions unit to build call chains. Don't hesitate and you'll be good to go further. You learned Aerial World case of extending the string builder Do not abuse extension method since it can lead to the primitive obsession smell. You saw the problem on the example off using decimals instead of money. Abstraction. Builder designed pattern helps to build effluent. A p I for need constructing process often object and you learned that we can handle errors in the functional style by using the result moment. What makes functions honest? I hope you enjoyed this section we covered almost told important aspects we face with on the everyday basis going functional way 61. DI Related Anti Patterns & Refactorings Outline: Hi, this is engineers spark. And in this section you learn about the I related anti patterns Andrew, factoring things there always entire patters. Along with the best practice. Best practices often are the cure for anti patterns that cause significant harm. Mark Semen outlines the following anti patterns control freak, bastard injection constrained construction. And so this locator We're going to learn about these and type entrance and we will add at least one in type pattern called constructor over injection. We will try to avoid dogmas learning all the beautiful self dependence injection Ambien Context is a dangerous batter that has to be applied with care, and we will look into this problem as well. The facade service is one of the ways to avoid constructor over injection and you learn This s well along the way. You learn what is wrong with hidden dependencies caused by an appropriate application off this service locator designed pattern. Never similar topic is the temporal coupling caused by a lack off encapsulation that can be cured by playing the constructor injection. A start injection and type pattern is very similar to regular property injection, and you learn the difference between them separately, we will look at the problem off cycling, dependencies and how to break the cycle by applying the factor of better. Okay, then enough words. Let's start with the first anti pendant called Control freak. 62. Control Freak: Let's start with the most others anti pattern called control freak, which is the absolute anti part off dependence injection. Any explicit creation, often unstable or volatile. The penalty is an example of a cultural freak anti pattern. Look at this example here. Have a view model with a math had named perform payment. It accepts the enumeration named payment method and, ah, the amount of money to be withdrawn depending on the payment method, the perform payment, math, it grates. Corresponding object responsible for processing the payment. I've seen such gold several times in my career. This is a classic violation off Diaby to fix the day p violation that we could do the following. We can just entirely remove this. Which case performing this re factoring. We move their responsibility to create the I payment method instance to the client so the client would be look like this. And could Noel creative? Your model seems to know I have the instance of the payment method and pass it. Oh, sorry, this is not in the constructor. Here's how it Klein could look like, but we can go further to simplify client's life. Now clients have to think of the creation logic off the I payment method. This case is the classic one, which demonstrates how we can apply the dependence injection along with abstract factory designed better. The logical gration in this case should be encapsulated in a separate class, abstract factory or factor method is ideal. Well, we need to inject a dependency the type off, which is determined in the round time. In this case, the Argument off payment method and admiration type is determined in the round time. Most likely depends on the choices made by a user on the U I. Let's switch to the slights. Here is a diagram that reflects the abstract factory design pattern. The process of creation is abstracted way by an interface or an abstract glass. In our simple case, we can rely on the interface. This diagram reflects more complex in area. We will implement abstract factoring a simpler way. This diagram shows that there is an abstract factor, and to concrete factories named shape factor and color factory concrete factories create concrete types. That's sort of factor, our code example. Relying on the idea off the abstract factory design pattern, I'll switch back to the visual studio and let's introduce and factory interface public interface. I'll call it I Payment Method Factory and it will contain a single method that returns the I payment method interface. There's a mass it I'll name greed and it accepts the payment method in admiration. And we have to implement at least one implementation off the payment method factory and I'll call it payment at the factory and this method will encapsulate this logic. Now our of your model can request the I payment method factory in It's constructor done Now, the clients code will just pass the implementation of the payment method factory and ah, clients don't have to think about the process off creation off the I payment method since it is now encapsulated in the implementation off the I payment method factory. Now a core can just pass the factor implementer without thinking too much. This is how we can overcome such problems. Blind die with abstract factory 63. Hidden Dependencies with Service Locator: Do you remember the service Locator designed battery? Let's talk about the consequences off. Applying this battery, I will remind you the example we've seen before. Here it is what the problem is with this gold. Let's talk about one of the benefits of the encapsulation is the ability to obstruct away all the implementation details from a color a color doesn't need and actually doesn't want to understand the internal details of your object. So we have a contract for interaction with the object, which is expressed by it's a P I. What is the contract off using the order process? Er, class? The only thing we can say is that it requires from a color to have an instance off the order type of hand without an order. Instance. A color can't call the process method. What will happen if someone just rise the following code? This coat compels without any errors, but it will fail in the run time. Why? Because the rial contract off the A. P I comprises of the following an instance off the order type is required. An instance off. I order Validator has to be resolved by using some kind of global stated bus or a nice sea container and an instance of the I order shipper has to be resolved by using some kind of global stated bus or in icy container. The less to requirements are not visible and not discoverable at compile time. As a Kerala re, the encapsulation is broken, since the preconditions in the form of required dependencies are hidden from the side off a color. The pattern which is used here, called Service Locator, the service locator becomes an anti pattern when it is used in the business logic here and there in the code base. The service locator is not an anti pattern by its own until it is abused by using it in inappropriate places in the code base. It's okay to use the service locator in the infrastructural code in the infrastructural code, such as the root off your application, where all the air sea container settings being set. The service locator does not incur any design damage. Okay, so how to fix the problem with the code we have discussed? Well, pretty simple. We just need to make the dependence is visible for a collar. Thus we will harness the power of a compiler to check if all the dependence is are actually there before calling the method. So the improved version I looked like this. Now we explicitly require all the dependence is needed for the internal logic. Sometimes this works fine, but what if the I order process er interface defines the signature off the process method as in the following snippet? In such a case, the most powerful thing we can do is to force a color to pass the required dependencies through the constructor. Here. We just require all the dependencies right in the constructor, so a color can't create an invalid object in the constructor, we will perform all the necessity of validation off the arguments. Okay, In the short version, the public ap, I looks like this now to sum up, I would say that you must think thrice before hiding any dependencies since their preconditions for using the a p I. Okay, we had a look at the problem of hidden dependencies. Always consider the option to make all the dependencies visible for the collar. Except the case when the object can resolve all its dependencies by its own. For sure 64. Temporal Coupling and Constructor Injection: temporal coupling between members is a well known smell, which means that there is a hidden interconnection between two members of an FBI, which requires the right sequence off calls made by a color. Let's look at the problem in practice. Very often, developers introduced temporal coupling by exposing a separate initialization method, which has to be called before using the object mark Semen provides the following example. There is a class in the BCL named endpoint address builder. This is a factory for producing new endpoint addresses with specific property values. Consider the falling use case for the glass at the end point address Builder is designed in a way that the second call will fail at runtime because for using this builder, you have to at least provide a your eye so the following code will work fine. Yes, you can see there is a temporal coupling between setting the your eye property and a call to the two endpoints address method. In this case of the A, P, I developers could eliminate this kind of temporal coupling by requiring your eye in the constructor. Consider the following example Now an attempt to create empty endpoint address builder will fail at compile time. So by this simple way we can eliminate the temporal coupling between setting a property and call to a method which depends on the property value. Remember, Always try to make invalid states unrepresented ble. 65. Constructor Over Injection: when we apply constructor injection for all the dependencies, we sometimes end up with convoluted constructors in case of complex objects. Consider a WBF application, which in almost every view model requires I haven't aggregator I progress I prom creator dependencies to reveal the meaning off the two. Later in the faces, I will say that I progress. Implementation should provide the functionality off, accepting a chunk off long running code and showing a view with a progress bar. Their prom creator provides the ability to open well, Brahms. Now imagine that there are some of your models which require, in addition to or maybe even three dependencies for creating an instance off a model. This is how, if you model might look like with so many dependence is five arguments. What a mess. There is too much noise in the constructor declaration. Just to dependence is actually carry useful information from the viewpoint off a really business value. These are I payment system and I rules validator. The other dependencies are utility ones, infrastructural, so to speak. In this case, there is some room for dependency hiding approach. In my opinion, if we use, say, math framework for dependency injection, then we could do the following. We moved dependencies out of the constructor to the Fields Declaration and mark them by the attribute import. Despite of that, we don't go for the IOC container directly. We still hide dependencies as it was an example we've seen in the lecture about hidden dependencies. Nothing really changed. Why I think this cold is not so bad. Well, well, several major reasons at first. Few models are not business entities there just chunks of blue code. No one cares off. There's dependence is too much view. Models are not public AP ice, and they're not reusable. In most cases. Because of two previous statements, it may become just in agreement between team members that you models have those utility dependencies. And that's it. These utility dependencies are declared, is protected. What allows us in tests to create a view model class, which inherits from the payment of your model and then replace those dependencies by Marx? Because we have access to those fields so we don't lose the opportunity toe cover payment model by unit tests. It was an accessory marks example where service locator is used, tow wire up their sea container in unit test projects in order to marker stop those dependencies, and such a practice could become a pain for unit testing process. As I've always said, there are no single right answers for single statements, which are always true. Generally speaking, we should avoid service locator because it breaks encapsulation, Esmark said in his article. Before using Service Locator. Consider the potential harm it can bring to a system. If you are sure that implicit dependencies resolving is a relevant for clients for your team, folks. And there is no potential damage for a system and go on a very important ideas. That service Locator doesn't incur any harm if used in infrastructural parts of the code base. For example, in the Bootstrap er, there are two other possible or factoring to eliminate the constructor over injection disease. Let's look at them 66. Ambient Context: another way is to use the Ambien context for such utility dependencies. Ambien context can be used exactly when we need to provide a ST ick. Access to an instance often object for many classes in the system. If literally 100 classes depend on the same type, you shouldn't pass the types instances toe all of them. In case there are two such types on which those 100 classes depend upon. You need to pass to dependencies to their constructors. If they have other significant dependencies, that would be ridiculous. You'd end up with very complex constructors that require 345 and more arguments. In such cases, I would recommend you stick with the ambient context designed pattern. So here's a simple implementation of this pattern. Looks like a class with two public properties, and that's right. Ambien Context is extremely simple. We can use this pattern with hundreds off view models in a desktop application, require instances off utility dependence is like I progress. I haven't aggregator, and I prompt creator, which are responsible for different utility tasks. You've seen a super simple version of of your model that takes many arguments in the previous lecture but the skeleton is from a real project in this case of your models. Just used the dialogue instance for working with Dialects Unit that's written for testing of your models, just replaced with the dialect property to a mark object. So this pattern supports unit testing and allows to avoid cramming only infrastructural stuff into hundreds of constructors. I would rename the spatter less simple aspect, since it's almost always used for providing a global access to an instance off a tap which implements some aspect of the system, like logging security or something like that dot not BCL also used this pattern in certain cases like synchronization, context, threat, current thread, thread current principle. Http context that current are the most well known example self implemented Ambien Context designed, pattern off course. This pattern is not flawless. The main flow of this pattern is that glasses which depend on the type represented by this pattern, hide this fact. We can see that a certain type depends on the type, which is accessed via ST ick property. This nature leads to a smile called hidden dependencies, which you've seen previously. If someone uses a class which depends on the type that is accessed via stated property and that someone forget to set that ST Ick instance properly, Then some kind off unfortunate consequences off course might be expected were likely an exceptional the throne like little reference exception. Unfortunately, there is no silver bullet to solve such design problems. It's always a trade off whether you should stick with Ambien context or dependencies exposed in properties or explicitly required the palaces where constructor is up to you, so apply this pattern very carefully. 67. Facade Service: Yes, Mark Simmons said. Constructor injection makes SRP violations glaringly obvious. Very often more than three parameters indicate the SRP violation logically, if on object takes 10 parameters than likely takes too much responsibility. This is especially most likely in case those older dependencies are business related. In other words, they're not infrastructural. Mark Semen provides the following example that it was straight such a case. Here's a constructor of a type that takes five business logic related dependencies, and here is the implementation of this class. In this case, it's apparent that the collect method relies on three dependencies I accounts receivable, irate exchange and I user context, a smart seaman says. In this case, everything is pretty obvious because these three dependencies are already encapsulated in a single private method. In the real production code, you may need to perform a serious off internal re factoring before pattern starts to emerge , and you can extract Ellen to face that segregates several dependencies. So to fix the problem, we can extract the I order collector into face with the collect method. The implementer will take three dependencies, those on which is the collect method depends now. The initial class can request the i order collector its constructor. Here is how we created the order processor before a factory. And here is how we created after their factory. And what is the difference, you might ask? The only thing we accomplished is that we introduced another additional level off indirection, making our design even more complex. However, this is not true. The benefits are quite significant in this case. Aggregated service in capsule eights on the business logic related to three dependence is in case business logic grows. It can be implemented in the single place in thin Julie Created order Collector class. If these three dependencies go separately on their own, as it was before our factory, the business logic will be spread over does and so different glasses. This is obvious. Good, bad. So the primary goal here is to adhere to the SRB. This riff factoring does not eliminate dependence is directly there, just get encapsulated properly 68. Property Injection vs Bastard Injection: as we previously discussed, we can inject dependencies. Why regular properties instead of constructors before looking at property injection, look at what is manned by the turn by start injection. Here's a simple example. We have a costumer class here, which depends on the I logger, a developer of this class exposed to constructors. The default one allows to create a customer instance without passing an instance of the I a logger explicitly that could be done by a developer with intention to allow easier creation off the customer. Instance, the second constructor was exposed for marking the I logger in unit tests. Regular loggers work with a file system or a network, and that's why they should be replaced by a mark, which most likely does nothing. Instead of writing toe files or sending bites via network. However, this is a classic example of the bus start injection. This design is not extremely bad unless the instance passed by default belongs to another assembly. If that's the case and in case of fire lager, I would say that most likely in the real world, dialogue or implementation would indeed reciting another assembly. The customer class depends on that assembly which contains the I longer implementation. It's bad thing, especially if we really can avoid excessive dependencies on the binary level. Why the hell other applications that want to use the assembling which customer recites I need to reference the assembly in which is the implementation off the I luxury side. In other words, such design forces tight coupling between modules. This entire pattern can be fixed by removing the default constructor. And actually, if this dependence is not required for preserving the encapsulation, it can be exposed us A. Property. We can easily inject dependencies into properties manually s well, it's y d I containers off course. If the dependency is must have and the object cannot work properly without it, then this dependency should be requested by a constructor. Otherwise the encapsulation will be broken. It's an example of property injection in dotnet framer. I can give an example from WTF dependency object exposes the data context. Property dependency object can work properly without the data context being set. However, the caller can set it easily and dependency object will use it for wiring up the bindings. An alternative for using the property injection might be the AM band context designed better consider it before applying the property injection. So if the default constructor passes a default implementation off the dependency and that implementation re sites outside of the current assembly, then this is a bust ARD injection avoided either by applying the property injection or ambient context. 69. Cyclic Dependencies: Sigh, click or circular Dependencies is one of the strong smells in the application design. The cycle a cures when an implementation requires another dependency whose implementation requires the first abstraction. Such a dependency graph cannot be resolved automatically. Here's a diagram that demonstrates the problem on this diagram. You can see that vehicle is an interface car is one of the implementations of that interface car depends on the I car management system into face, and a car management system is the implementation of that interface, and that implementation on its own depends on the I vehicle interface. If you try to resolve this graph of dependence is in your mind, you'll do it forever since it's circled almost always, such cases are indications that something is wrong in your design. This circle has to be broken. This is an example of the level of source code. I also like the example of circle or dependencies at the binary level. Here's a classic example of extremely harmful design caused by circle or dependencies. In real life, you might see the following code written by junior programmers customer. He's in an entity from the domain layer, whereas customer Dow is from data excess layer. These glasses reference each other customer needs the customer dal and customer down its customer. There are several ways off overcoming the problem off cycling dependencies. The 1st 1 is to invert the dependency which causes that cycle. For example, if class A references Class B and especially if it calls on it, only avoid methods, then you can break the cycle by introducing the events in the class A Class B subscribes to those events and invoke its corresponding methods. This is a very simple inversion by events or callbacks in essence events or so called callbacks in C plus plus and other languages is one of the simplest ways to build frameworks averting the dependencies. We discussed it in the first section. Another way is to never the dependencies. By introducing an interface or another level off in direction, I want to show you how to apply simple abstract factory implemented s interface. In this case, let's look in code at the problem shown in the diagram. Here we have the vehicle interface and to inheritors of that interface car and truck. Both Gagarin truck request I car management system in their constructors, the car management system is the only one implementation of that interface, which in its turn requires I vehicle. I mean, it's constructor. Apparently, we have a cycle here to prove that we can't automatically resolve the I vehicle interface. Let's use our simple RC container we built in the second section. Despite simple I season a ive implementation it faces. In this case, the same problem is a full fledged icy container. I am commanded this chunk of gold. I register here the i vehicle and I want to create the car to resolve that interface. And I also registered the I car management system, resolving it by corresponding implementation. After that, I want to call the resolve method passing the vehicle interface. Okay, lets around the application and see what will happen. Stuck overflow exception Get raised. The RC container cannot resolve cycling dependencies. It gets into the in finite loop, trying to resolve them. To defeat the problem. We need to break that cycle somehow. Taking into account er there are several implementations off the A vehicle interface. It might be useful to abstract away the creation of the ethical implementation, since car management system can work with any of those implementations. Let's do this by introducing an abstract factory. At first I will create an interface, which I'll call the I vehicle factory. And this interface will contain a single method that returns the I vehicle interface. And it accepts the icon management system. Apparently, we have to implement and implementation of this interface. And let's great to implementations the car, factory and truck factory, and it will just return the new instance, return your car, passing the system argument and the same way I'll implemented e the truck factory. You know, just return them you truck. Of course, we also need to implement the car management system since now it will, except that I vehicle factoring in it's constructor and our create constructor. And except here, the I equal factory Great Nikhil Factor and three Terry down the field. Oh, no. We actually can just use the factor here inside the construct her like of this. Just create the implementer off the A vehicle interface Ride here great and implement around vehicle of our this you field start and check. So systems that square the vehicle, get state and write some information to the console. Look sorry, Right? Left right line. You got sick, right? Fine. Checking the state max Speed is state dark Max Speed and the motile look Sorry. And the motile is stayed That motile That's great. And we also can make it read only believe Yes. So here ago the cycle is broken. Let's check if everything is fine and use our privacy container once again. Uh, come learn it out and I'll come in this great So I registered the A vehicle by the car implementation as well as I did previously. However, we can ask the user whether he wants to create car truck and then said their sea container up accordingly for simplicity let's do this explicitly and map the i vehicle to the car implementation. Then I register their ay Carmela jewel system and resolved by the riff factored version off the car management system class which requires the i vehicle factory in it's constructor end off course. We need to map the ethical factory to some implementation of that interface. And in this case, I map the vehicle factor to the car factory. So finally I'll go there result method, we resolve their vehicle interface and then we try to start the engine now let's run our application to check. If it works fine and we see that out Produced by the car class Discovering cycling dependencies, you must stop and think carefully how to break the cycle. Whether this cycle appears at the source code or binary level, cycling dependencies are extremely harmful, so the first thing you have to do is to analyze why that cycle appears and then think about the way of breaking that cycle. 70. DI Related Anti Patterns & Refactorings Conclusion: Congratulations. You've reached the end of the section. Let's brief here a cap. What you learned in this section control freak Anti pattern is the opposite to dependents. Injection control Freak means that an object on its own create all of its dependencies service, like Gator used within objects that encapsulate business. Logic is an anti pattern. Seriously, Gator is okay to use within the infrastructural code like that bootstrap er about which you learn a little bit later. Beware of temporal coupling that arise when you first glance go to call some kind off initialization method. After constructor, it creates temporal coupling between construction and initialization. Beware of constructor over injection. When an object requires more than three dependencies, then this is a sign off SRP violation. Most likely, you can extract an object that encapsulate some business logic that is related to some of those. Dependence is ambient. Context is a very helpful design pattern for using dependencies that are common for a significant number off systems components. This is especially true regarding service components like logging or security checking. However, MBN context hides the fact that an object is some external dependencies. Seems they're not expressed in it's constructor facade service is helpful. Better that is intended to aggregate dependencies that travel together throughout the system. Beware off exposing two constructors, one of which accepts no arguments, and another one requires them. This is a smell of bastard injection. Sometimes it can be helpful to apply property injection to avoid exposing beautiful constructor. In other option used to apply the Ambien context, break them by introducing levels, often direction, applying inversion of control. 71. Clean Unit Tests Outline: Hi. This is a lie. ISAF, often of a K engineer spark from engineer spot dot com. And in this section, we're going to talk about unit testing best practices. In this section. You learn how Singleton's and stated classes harm the union testing. You learn about the problems related to extracting into faces just for the sake of dependence injection. How much dust coverage is enough? You learn about the problem of testing trivial code and what it really means. They roll off a single concern, testing in a single unit test and you learn many different small best practices. Let's kick off the module by talking about Singleton's and stated classes. 72. Singletons and Static Classes: For those who are unaware of what Singleton is, Singleton is a creation all design pattern, which allows defining an object which can be created only once. So in the program, there can be only one instance off such an object. That's why the design pattern, which enforces this restriction, is called Singleton. State of Glasses are somewhat similar to Singleton's, but they're far from being the same. Though they induce similar hard to unit testing, you'll see this shortly. This code uses the M S test framework. We've seen how to use any unit for defining method, which will be executed before any other unit tests in the assembly in there must test. You can do it with the assembly initialize attribute. It actually doesn't matter. What matters is that such initialization is most often are the sign of problems. This method calls some method with an interesting name, innit config and you. I context. With this method, initialize is some kind of configuration and marks a your thread with a slick trick. Our interest lies in the configuration class. The first line initialize is a configuration class which is used everywhere in the code base via stated property in the state of app glass. Because of that, you can just easily right any unit tests for the code base, which relies on that configuration. You also can't market easily, since the code base uses that configuration directly via stated property. Thus stated, core global dependencies are harmful to unit testing. Such stated dependencies lead to a very complicated stage off, setting up all the static or global dependencies to a correct state. Before executing unit tests, I intentionally showed you a real difficult case from a real code base. You can consider the same problem with the Tor example. Here it is. Here's the simplified version with dependencies implemented as Singleton's. There are several implementations off the singleton design pattern, and each of them has some peculiarities. I don't want to dig this topic deeper, since it's irrelevant or discussion, I'll just use one of the possible implementations. Consider a synthetic but very close to reality example. Here's credit card class with a charge method, the intention of which is obvious from its name. This method depends on global state heavily. Firstly, it tries to validate a card, then gets a customer, validates a customer and calls the charge method. In the end, all the operations are called on Singleton's Let's look at one of the Singleton's no sense to look at them all since they're implemented. Similarly, for example, look at the credit card processor. The singleton itself is not stated, but you can create it. Since the constructor is private. The only way you can use this Singleton is via the state IQ instance property, which grades the object if it was not created. The problem is that this glass requires some initialization. It exposes the set connection method in reality, who most likely had to pass some arguments to eat. If you try to call, validate or charge before setting up the connection, you'll get the exception in this particular toy example. We could solve the problem by automatically wire up the object right after the creation. But again, this is a tour example. In the real world, most likely we would have to expose a separate initialization method like this set connection in the real world application. All these Singleton's most likely would be initialized somewhere in the main method, like here and now I want to ask you, How the hell are you going to test the charge method. At first, you need to pollute your tests by some horrible preliminary initialization. Without it, tests will not work. Secondly, how the hell are you going to manage the dependencies? You can try to write some test doubles and you'll soon realize that this is hardest hell if possible at all, without involving some kind of dark magic. What is the reason off such a horrible situation? Off course. The primary reason is a poor design. This design is untested herbal, the charge method and the created card glass. They hide the fact that they depend on three entities. This design should be completely rewritten. All the dependencies should be visible from the outside world. Previously, I showed you the technique which enables a constructor injection. So I'm not going to repeat the same exercise you can do. It is your homework. So why Singleton's are bad? They're generally used as a global instance. Why is that so bad? Because you hide the dependencies of your application in your code instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. They violate the single responsibility principle by virtue of the fact that they control their own creation and life cycle, they inherently cause code to be tightly coupled. This makes faking them out under test rather difficult. In many cases, they carry state around for the lifetime of the application. Another heat to testing. Since you can end up with a situation where tests need to be ordered, which is a big no no for unit tests. Why? Because each unit tests should be independent from the other. 73. Too Many Interaces: one of the primary science off the markets approach is having interfaces with a single implementation. I want to share with you some very important thoughts regarding this problem. I am inclined to treat the case when you have only one implementation off a given interface . That's a code smell. I'll try to explain why Esmark Seaman said in his block programming to an interface doesn't guarantee that we're coding against an abstraction into faces are not abstractions. Why not? It will see why in a minute here, I want to say that such interesting questions I discuss in detail in the course a p i n c. Shop. The best practices of design and implementation interfaces are not abstractions. And here's why, when you use the extract into face reflected all feature in visual studio, even if you don't extract every member. The resulting interface is shallow because it doesn't recursive Lee extract into faces from the concrete types exposed by the extracted members. An example I've seen more than once involves extracting and interface from a link you to sequel or drink. You turn to this context in order to define a repository interface. It's an example. Here's into face extracted from a very simple in Q two entities Context At first glance, this may look useful, but it's not. Even though it's an interface, it's still tightly coupled to specific object context. Not only does objects set off T reference the entity framework, but the posting class is defined by a very specific photo generated entity context. The interface may give you the impression off working against loosely coupled code, but you can't easily if it all implement a different I posting context with a radically different data X technology. You will be stuck with this particular posting context. Another way we can create problems for ourselves is when our interfaces leak. Implementation details. A good example can be found in the System rapper project that provides extracted into faces for various BCL types. Such a system dot io dot file Info Why developers meet such libraries as the system rapper . Here's the use case. A developer, right? Some kind of application which needs to read the file, parse it, using some kind of specific format updated in that format and remove them. In this particular case, we have a class named quotation processor. It except a file path in the constructor, and it exposes two methods. The first method. Get amount, converts one currency into another. The logic doesn't matter. This method reads the file. It parses it and returns the results of calculation. Otherwise it returns minus one. The second method at Quotation also reads the file. If there are any records, we take the last one parse it and then we're four months a new record and finally added, If there are no records, we form a new record with I D equal toe one. This is a little bit silicon example, but imagine that everything is much more complex in the real world. Examples. So how a developer who rolled this class solved the problem. The developer rolled out a class which is responsible for everything it can read the file, it parses it and process it. Afterwards, that developer starts to think, How the hell am I going to test it? And if you look more carefully, you'll immediately understand that there is no way to write unit tests for this implementation. All the functions depend on the file class, and they directly operate on the disk. That's how System rapper comes into play ride. I'll add the System rapper library to my project, and my class will require that I file interface in the constructor so I could market and write unit tests. The thing is that the logic of that programmer is flawed. Always try to find the roots of the problem. The reason why the developer experienced difficulties with the unit testing is not related to the fact that the application needed toe work with the file system. No, the reason is that the single responsibility principle was violated and principles of functional design over totally ignored. That programmer, instead of bringing useless marking libraries, could separate the responsibility off reading and writing to a file from the business logic off formatting and passing. After that, he could easily right unit tests for business logic and right integration tests for the class, which Inter operates with the file system. No need in any marks how to do that. Look at the example of fear factoring, I'll show you a quick example of for factoring 74. Reducing Interfaces: First of all, it's apparent for me that there is a smell called primitive Obsession is hiding. The thing is that the record with parts has its own structure, which consists of four parts I D currency pair rate and stamp. So I'll allowed a class named the Record with Rid on the Properties. - Now I want to implement a file manager which will be responsible for formatting and all the logic. It will implement the Ed quotation method. I also created the action in admiration and Fi election structure to separate logic from IO operations. In the method, we have the pure logic which forms the record and tells the client what to do with the record. Now I want to implement the persisting file class file per sister takes the file path, get all records, reach the file and parses of I record glass, the apply action method performance in action. Depending on a case, it adds a record Great new file or remove the file. The last entity I want to implement is the Quotation service. This will be an orchestrator I exposed just for the sake of demonstration on Lee. One method at quotation. This method just delegates the responsibilities to appropriate objects. Now, look, we don't need any marks. The quotation service and file manager we're going to cover by two or three integration tests. All the business logic related to passing and forming the records can easily be covered by unit tests. Let's write a couple of units lists. Here's the test I can write for the parsing string method. We also can write a test for the Ed quotation method of the file manager class. You can write it on your own. Treated as a homework. You can Donald the Source files and write a couple off unit tests on your own. In the next lecture, you learn how much discovered is enough. 75. Testing Trivial Code: the problem off testing Trivial code is related toe test driven design heavily, though it can be discussed without did it involved. The question is, should we write test for trivial properties with aimed togethers and centers or any equally trivial methods? And there are some different opinions even regarding this question, Robert Martin, a k Uncle Bob, initiated the most notable discussion, which was continued by Mark Semen in Shirt, the meaning Off the Uncle Bob's article regarding travel called Testing. Part of it can be distilled down to the following statements. Don't write tests for getters and setters. Those getters and centers will be indirectly tested by the tests off the other methods, so there is no point in testing them directly. Don't write tests for one line functions for functions that are obviously tree ville again , they will be tested indirectly. Uncle Bob states that TDD practices are not dogmas and off course he's right. Though his statements still required for the investigation, Mark Semen disagreed with Uncle Bob, saying that there are some problems related to uncle. Both statements they confused, cause and effect. Three Ville code may not stay tree ville, and it's horrible advice for beginners. The first question which comes to mind is how the hell properties and methods came into play without the failing test. TDD implies that we can't write code without having a failing test. Another concern is that very often practicing TDD. You don't know how much difficult the implementation will be. Another concern is that it might happen that, at this particular moment, a certain property street bill. But can you be sure that it will not be changed after a week, becoming a calculated property with its own logic of calculation, which obviously should be tested? In my opinion, it's hard to give a universal advice, which fits any possible cases. In my opinion, this problem belongs to one off many fundamental engineering problems which don't have easy answers. You must turn on your brain and deeply think about what you need and what you don't. What benefits do you see and what disadvantages you anticipate. Welcome to engineering. In the next lecture, you learn what test single concern rule means 76. The Rule of Testing a Single Concern: you might hear the rule off a single assert protest, which literally states that you can write one and only one assertion in the unit test. This confuses beginners very much, since we very often find ourselves writing, multiple asserts, and we understand that we actually need to ride them in a single test. Let's clarify the rule off a single assertion. Here you can see the method which tests the properties off a glass money. I'm not going to show you the implementation, since it's irrelevant to our discussion. I'll just notice that this money class is suited for Russian currency, and it exposes two properties called a mountain kopecks and amount in rubles. In the US there are dollars and cents. We have rubles and coptics Accordingly. These tests creates the money object passing in a different amount off money expressed in Coptics and then verifies that properties return correct values. This test can be significantly simplified, but the idea is to show you that every time I create a new object, I have two assertions that check very close properties. It would be insane to create hundreds off unit test to test so close a P I members. The very important thing is that these assertions test very close things. They test the same concern, so the correct rule should sound us right. On the one logical assertion. It means that if several assertions share the same logical intention, they can be treated as a single logical assertion. And this is totally fine. Here's another example, which demonstrates a good example of multiple assertions these methods checks if several properties return correct values. In the case of the default configuration, it would be silly to create for different unit tests. If you write assertions for completely unrelated members by logic, then you violate the rule of a single assertion. And in such a case, you need to roll out separate unit tests. One assert protest really means test one aspect or behavior image test and communicated clearly in your test name. It doesn't literally mean that one test should have only one asserts statement in it, just one aspect or behavior. In one test and related aspect, behavior can be tested in another test. Sometimes we need more than one asserts statement toe assert one aspect or behavior, and it helps to add those assert statements in the test for better communication. In the next lecture, you learn much more on best practices off union testing 77. More on Best Practices: Yes, we discussed in the lecture about guarantees provided by unit tests. No matter how many unit tests you have or how they're organized in the solution Explorer, they're not more than just needless baggage. If you can trust them, maintain them or read them, according to Roy Oshiro, that tests that you write should have a least three properties that together make them good trustworthiness. Developers will want to run trustworthy tests, and do you accept the test results with confidence? Trustworthy tests don't have bugs, and they test the right things. Maintain ability on maintainable Tests are nightmares because they can ruin project schedules or they may be sidelined. When the project is put on a more aggressive schedule. Developers will simply stop maintaining and fixing tests that take too long to change or that need to change very often on very minor production code changes irritability. This means not to just being able to read a test, but also figuring out the problem. If the test seems to be wrong without readability, the other two pillars full pretty quickly. Maintaining tests becomes harder and you can trust them anymore because you don't understand them. I'm going to create a separate course dedicated to best practices off union tests implementation. I want to keep my video courses short and concise, so I'll just only briefly mention some of the most important best practices. Avoid control flow operators strive to write unit tests that don't contain any switch if or else statements as well as any for each four or while Loops. Having control flow operators in a unit test is a smell, which shows that your unit test is too complex and most likely you need to reflector it into two or more tests. If you really need a loop, it should be encapsulated by some appropriate abstraction with a beautiful name, which explicitly reflects the intention or full the difficult stuff with hidden loops. Avoid the application. A sell rating said unit Tests are full fledged citizens off your code base. Developers avoid duplication in the production code base solving to do the same in unit tests. If you have some kind off repetitive logic, like setting up the salt in the same way in every test than consider writing and method decorated by a set up attribute provided by unit testing framework, use any slicker factoring techniques toe got the excessive code. Don't set up. There's doubles in the set up method. Please don't arranged as doubles in a set up method. Doing so will make it hard to read and made him the tests. My preference is to have each test create its own marks and stops by calling helper methods within the test so that the rear off the test knows exactly what's going on without needing to jump from test to set up. To understand the full picture, avoid order tests. There is one feature which is seemingly supported by any unit testing framework, which we haven't discussed and which I wouldn't recommend to use ever. It is Gold order tests. The meaning of this feature is pretty obvious from its name. It allows to run unit tests in a specific order. Why our order tests bad. Generally speaking, the thing is that any specific order creates the so called temporal coupling between unit tests. Temporal coupling is a well known smell, which you can face in a production called very often. In short, there is a temporal coupling between two functions. If the higher logic can change the order off their invocation thus ruining the business logic leading to embark. Actually, temporal coupling may look different in code, so if you change the order, tests will fail. Most likely every time you add a new test to a particular order, you need to think about when the test you want to add should run after test a or to beat or after just see and before deep. Another problem is that order tests are slower than a new ordered, since order tests cannot be run in parallel off course they can. They're ordered. Here is one of the eligible cases when you may want to rely on order tests. Previously, I worked with devices a lot at my work. I needed to write some tests for a device. That device couldn't process requests in parallel, so the parallel execution was impossible in the first place. Also, I needed to test the correctness off processing sequences of operations, so the necessity to right order tests was imposed by requirements off a project. Nothing else I could have done and by the way, noticed that in my case I wrote integration tests, not unit tests, since though tests interacted with that device directly, I'm not aware of any riel cases when you absolutely need to, right order the unit tests. But everything is possible, so I will not stay that there are no cases illegible for writing or the unit tests. Just consider that order tests are hard to maintain and always think twice before relying on the feature. Off order tests over specification, sometimes especially beginners, full into the trap off over specification. Here are other ways to ride over specified unit tests a certain purely internal state in an object under test. They use more than one mark in a single test. Use both stubs and marks in a single test. Asserts specific all orders or exact string matches when it's not required. Let's briefing discuss these points. First of all, the first smell is related to another problem. When the internal state is at all visible to clients. This violates the encapsulation. Tests should not dig the internals of the system under test that they should test the visible A P I the second point using more than one mark in a single test. It's sometimes hard to avoid, but you should strive to, even if you need more than one mark. Usually the true unit test will set up only one of them. Other marks will behave themselves tentative regarding any calls. In a test where you test only one thing, which is, however, commanding right tests, there should be no more than one mark object. All other test doubles will act a Stubbs having more than one mark. Protest usually means you are testing more than one thing, and this can lead to complicated or brittle tests. The third point concerns mixing stubs and marks in a single test. This is also not always possible to avoid, but it's better to set up only one type of test doubles. Otherwise, a test would test too much in one around. Consider separating attest into two or more tests. The fourth point is my favorite one I saw so many times tests that should test a specific returning value. But in addition, developers start to write assertions on Mark's verifying the sequence of calls arguments. Well, actually, this test should not bother buy all this stuff. The recipe is to separate interaction tests from tests that verify returning values and changes of state tried to achieve independency and isolation tests should not be dependent on each other. Put that in your pipe and smoke it. Often tests share some kind of object instance. In such cases, always rely on cleanup features off the testing framework in a new testing framework. As you've seen, you can write cleaning functions, decorating them by the following attributes. Tear down or one time to her down. Remember that a unit test runner can run unit tests in any order it likes. In the next lecture, you'll learn how to easily generate unit test names to save much time. 78. Clean Unit Tests Conclusion: congratulations. You've finished the course. That was a long and interesting journey in this section. You learned you learned that Singleton's and stated classes make impossible to write unit tests for the code, which is dependent on them. It's hard to replace stated dependence is you learned that into faces are not abstractions . It's a smell to have a single implementation often interface. You learned that testing trivial code might appear a useless undertaking. However, the things are not so simple. Trivial code sometimes transforms into something more complex. You learned that testing a single concern within a single unit test doesn't mean that you should avoid writing multiple calls to assertion methods. It means you should test only one logical unit in one unit test, and you also learn many small unit testing best practices that should be applied on the everyday basis 79. Clean Code and TDD Outline: Hi. This is Injurious Park from injury or spark that come. And in this section you learn what is D d d and why we need it. What does red green red factor mean? You learn about the three laws of test driven development. You'll see how to implement converting off Roman numerals to Ram Inn, what is continues testing and how to implement a tick tack toy game using has dream and development. In the next lecture, we will start with the basics. You learn what TDD means. In essence, let's get started. 80. What is TDD: There's driven development, which is also called Test First Development is the approach off. Writing tests head over the production code, so tests drive the production code, not vice versa. As usual, the goal is to keep the design well structured and modular to enable writing off valuable unit tests. That's why sometimes developers refer to t d D not as to test driven development, but as to has driven design. Because tests for the shape off the production code before TDD was introduced, developers just rode the functional code. And when all the pieces were put and interconnections between them are set up, developers started to think about writing unit tests going this way. Very often, developers face the problems with writing unit tests, since the design of the functional code is not suited for unit testing, no proper abstractions, no Sheen's for injecting the dependencies and so on. Unit tests are specifications off what the code should do. When developers right unit tests in the first place, they implement Onley that production code, which satisfies the unit tests. Otherwise, developers tend to ride generalized and thus more complex code. Developers also tend toe gold plating de de de helped tow. Avoid all these problems when you write unit test first, you can't avoid thinking about how to make the production code design testable, since in the first place you need to make the already written unit tests. Bass following two D D practices, developers achieve more even gauge of progress between testing and coding. Obviously, it automatically provides at least about 70% off test coverage. Here are some a very popular misconceptions related to TDD writing tests. First, you double your efforts. Well, I even don't know where this misconception came from. You'll write unit tests anyway, so why not to write them at first? And we're in the case that the doubling off efforts, the fact is that TDD reduces production box density by 40 to 80% without tests and even adding tests after you implement production code, many more bugs get into production, and everybody that gets into production doesn't simply waste developer time. It hurts the company's brand and quality reputation. It wastes enormous resources in customer suffered costs. Maybe you just don't want to write unit tests at all, then you're not one of us. Sorry. That's all I can say if you want to write software of poor quality, Go on. And don't forget to request a refund to get your money spent on this course back. I don't want to see such students enrolled in my course. You can't write tests until you know the design and you can't know the design until you implemented the code. Developers who have not developed the test first TDD discipline, often charging to the implementation off the code before they know what they pay. I will look like they start implementing code before they have even designed the function signature. This is the opposite off TDD that the point of TDD is that it forces you to have a direction in mind before you start charging into the fray, and having a direction in mind leads to better designs. You have to write old tests before you start the code 100% design up front is a myth. In every type of engineering. The design is exploration, Cherie. We try things out, throw them away, try different things until we reach something that we like now. True, if you wrote every test up from before you wrote a line off implementation code that would hinder the exploration process. But that's not how successful TDD works instead, right? One test. Watch it fail, implement the code, watch the test pass and repeat. In the next lecture, you learn what a red green re factoring means. 81. Red Green Refactor: The main technique off TDD is called Red Greener. Factoring Red Green. Red Factor are short names off three repeatable steps. Imagine that we need to implement a calculator, which adds to numbers. The first step we need to make is to write a union test so we can write the following unit test. Now. If you build a solution, you'll get compilation errors. Since we haven't implemented this AP I yet, let's generate all the code. I'm generating the code with help off such a powerful tool as very sharper productivity. Tools like Re Sharper significantly enhanced the TDD experience with extremely powerful features of generating code navigation, smart quick fixes and other. Okay, let's run a unit test and it fails. Now we are in the red phase. At the second step, we need to ride the production code and turn the unit test green. Now let's run the unit test and it passes great at the third face, we need to look both in the production cold and testing code carefully. If anything requires re factoring, we need to perform a factoring. Since we're having, for example, we don't need anything yet. The only thing I can do here is to just move the generated code to the appropriate place. So this is the whole reflecting we did here. So we get back to the first step, we need to write the next unit test, but I'm not going to do this. So you should repeat these simple three steps until a feature or a use case is implemented . These simple three steps technique is the core technique off TDD. 82. Three Laws of TDD: s you have seen previously D d d implies that we write tests before the actual implementation off a particular feature. However, this is only the tip of the iceberg. There are three very important loss of test driven development here. They are never right, even a lile off production code. Before writing a failing test. Write a minimal test, which is enough to see the failure. Don't write excessive code and don't write production code more than enough to pass the failing test. These three simple laws determine how TDD cycle should work. Each cycle takes no more than a couple of minutes. Usually, these loss allow us to cover almost 100% of code base. Following the TDD techniques, you'll end up with a huge test suite, which is closer in its size to the size of the production code. Of course, it may cause significant problems with maintenance. Just imagine if the code base consists of two million lines of code run. In case off consistent applying off TDD, you end up with four million lines off gold, which have to be maintained. That's why it's so important to treat unit tests with respect. Let's talk about this further 83. Reading Roman Numerals: Another practical case is to implement bar sing off Roman numerals. Let's recall how we count in Roman numerals. I'll just provide a couple of quotes from Wikipedia. The numeric system, represented by Roman numerals, originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the late middle ages. Numbers in this system are represented by combinations off letters from the late in alphabet. The Roman numerals s used today are based on seven symbols. I ve Axtel, C, D and M And there is one particular team. The original pattern for Roman numerals used the symbols I, V and X as simple tally marks each marker for one. I added a unit value up to five V and was then added to V to make the numbers from 6 to 9. So the numerals for four I and nine z i I I proved problematic. Among other things, they're easily confused with I I end v i i three and eight and they were generally replaced with ivy or one less than five and I x or one less than 10. And this feature off Roman numerals is gold subtracted notation. I believe we will have to deal with this case. In short, let's implement the parsing algorithm we need to implement a function which takes a Roman numeral SS string argument, parses it and returns a regular Arabic number. I'll start from a simple test which verifies the result in case off passing the I. Lazar. The result should be equal to one. I'll called the function under test bars and create the class named Roman. The parsing method returns integer and accepts a stream, and I'll fake the results right now returning zero I'll around the test. It should fail and it fails. Indeed, I'll adjust the unit a session window in just a second. Let's triangulate and other simple test case is tow bars the V. Latter? Let's said a test case. Let's run the test and it fails. For now, I'll just continue faking until I see the nature of duplication. If Roman equals V, I'll return five. Let's run the test. It's your best. It passes and I'll repeat their TDD cycle with the latter X expecting 10 s. A result it fails. E for a woman equals X returned town. Let's around the test. Everything is fine. now it's style to re factor. I'll use the test case attributes to clean up the test room. Great. The bar's method takes expected in the Roman interference string. There is only one assertion. Iran. We didn't break anything. Everything is fine and re factoring full. The off the parsing method is office. What? The method, as is that it just maps letters to certain digits. We have a special collection for such cases named Dictionary, which can contain a key and the value so IRA factor the implementation in way that that we will use a dictionary and I just I'll just return the result from the map taking the value by key, and I'll remove the remainder. Let's make the dictionary static and let's run the test. Great. They're factoring. Was successful. We didn't break anything that's good. And other case concerns composed values. Let's try to parse the I string expecting, too. As a result, off Farsi well around the test, it fret fails to implement this. Obviously, we need to either eight over the letters and some of them up. Let's implement it. I'll run the four loop through the Roman string, just adding the letters taking off course, taking the values from the map, initialize it my zero and return the result. In the end, let's run the test. The test passes. That's great. I hope you remember about the special case, which concerns a special notation called subtracted. Let's verify that our current implementation doesn't take into account that special case. For that. I passed the I ve string, expecting four as a result. Run the test and it fails. I expected that we need to implement this somehow. Do you remember how we pronounce four in the Roman style? I'll remind you. We call it one less than five. So what we have to do is to shack inside the loop. If the letter last two letters compose a subtracted notation and in that case, just subtract instead of summing up, Let's do this. So if we have to last letters in subjective notation, I'll subtract. They valued taken from the map, okay? And I'll around the test and it works. Very nice. I'll check some other cases. Everything works fine. Yeah, 99 will be better. Let's verify we have nine. Yes, ever. It's everything passes, and finally, I would also re factor the condition which detects the subtracted case into a separate, well named method. Let's do this. I'll take this condition and extract him well named method alcohol. It is subjective what him would a massive with parameters. I'll fix it manually, I think. Yeah, I'll fix it manually. We just need to pass the last two letters. Maybe there is a better way of free factoring with the re sharper. Maybe I'm just not aware off. And of course, we need to re rannell the test and a little the test pass. That's great. These is how we can implement parsing off Roland numerals using that TDD style. 84. TicTacToe: Let's continue to practice TDD. We move from the simplest examples toward more complex ones. In this session, I'm going to implement the tick tack toe a game with three rows and three columns as tendered won. This game is simple but requires much more tasks rather than in case of parsing the Roman numerals. I need to explain the rules quickly. Since I have students enrolled in my courses from more than 100 countries all over the world, some students from the exotic countries may be unaware of the Tick Tector game. Okay, let's get to the Rose detector. Also known us knots and crosses or access, and those is a paper and pencil game for two players. Ex Endo, who take turns marking the spaces in a three by three greed. The player who succeeds in placing three of their marks in a horizontal vertical or diagonal row wins the game. The example of a game you see on the slide demonstrates how the ex player wins. Placing three crosses in the third row. I installed and crunch as the most popular, too, for running continues testing. You'll see how in crunch intelligently rounds tests automatically when either the test or the code under the test has been changed, so and crunch is smart in that way, this helps to reduce the frictions caused by hundreds off clicks to run the tests before starting to write tests. We need to think a little bit and build a plan. We want to build a class which provides some A P I to rule the game. I think we will need to count moves to rule the state of squares, setting crosses and knots, determined the state of the game. And who is the winner and basically, that's all. Let's start with a simple test when the game has not been started yet the number of moves should should be equal to zero. All right, a test is going to be bubbling. Grew it great game. We have zero moves and I'll start with assertion right away, and I am going to verify the moves counter property. I think I'll name it moves counter. Okay, let's generate the code. It's going to be off type game equals new game and I will generate the property. It's going to be of type into your and I'll change the center to private and the test passes and crunch says that it passes. We don't need to do here anything. Let's prove that the implementation is wrong by writing. And now the test case. Well, that's right. Another test. It's going to verify that. Well, we make a move, the counter shifts, so I'll name it. Make move counter shifts. And now I can start just with grating and game. Seems we already have the moves counter property. Uh oh. Make a call to make a move. Depressing one. This function doesn't exist yet. Bertel, right? The assertion right away. Expect one as a result. Off calling the moves counter property well, generate the method and eat will take the integer called index For now, it is failing. Oh, ride the obvious implementation. Here I'll increment the moves counter and all the tests. Bass, That's great. I believe we should be able to make moves making a move. I want to pass an indexed off the square. So in Texas, from 1 to 9 are valid. I'll start from a degenerative case, making a move, passing Ellen Valid Index. So I'll write the following test. I'll name it. Make sorry. Make invented move Throws exception. Maybe it would be better to point out the concrete type off. The exception we're expecting to the throne. Okay, assert throws. I expect the argument about French exception to the throne, and I'll pass the limbed expression here. I'll just create the game instance and call the game. Make move, passing an invalid index and the test fails to satisfy the test. We just need to write a guard close. Let's do this right here. If Index he's less than one or index is greater than nine with, then please throw new in inviolate operate. No, no argument Argument. Out of range exception and tests pass great. The TDD processes now semi automated I like the and Crunch Tool. Another obvious invalid cases to make move at the same square twice. Let's write a test. Proving implementations is wrong. So I led in the test case. Yeah, let's scope and based it. I'll name it. Move on the same square throws exception, but we're expecting here in invalid operation Exception and let's make a move twice in the first square and the test fails to defend the code. We need to introduce a board with nine squares where we can store the current game state. The current state off square can be unset cross and zero. This is also breathing office. Let's do that. So at first tile, let's move the game in tow. A separate folder. I don't like to create too many classes through the single file. I'll create a folder and I'll name a tick tack tour in the reality off course the production classes would recite in separate assemblies. I just do this just for the sake of simplicity. And let's move the game class there by re factoring through every shopper moved to folder and yes, yes, to the tick tack Toe a folder. Please move it. Yes, three tests best. The last one doesn't. Okay, let's go there and and Ed and at a class. Actually, it's going to be in in, um, I'll name it. State. Let's change it to public in them and eat will contain Cross zero or not. I'll leave zero and on set. Let's get to the game class and define the ray off state. Oops! Oh, name and board. They're on nine squares, so we need to write another guard close. So if I'll write a function here gets state messing index is not equal to state on set. They'll please throw and invented operation exception yet and close generate the state method. It returns the enumeration and takes the index and return the state from index minus one. And I believe that we need to initialize of this. The board off states all the squares to on set the movement the same square He's failing steel. What are we doing wrong? Oh, yes, I know what we're doing. Wrong off course. Making a move. We need to change the state Change the state off the field where we put crosses or not So let's set the state The logic is pretty simple here you've moves counter the remainder off division by two equals 20 Then we're going to set the cross. Otherwise zero Yes, all the tests pass. I hope everything is clear. I don't do anything complex here. Let's ensure that well, we make a move. A corresponding square gets field by either across or zero. We satisfy the previous task. But actually we don't verify that square gets field by either across or easier. Let's write another test. Let's get back to tests and write another one. It's going to be a public void and I'll name it. Making moves set Stayed. Sorry said. I stayed correctly. We'll create the game and I'll make several moves. Make 1234 234 And I'll assert with the States. I expect across to be pulled on the first field. Get state from the first index. 234 234 Likes expect here. Zero Expect here across. And I expect here a zero once again, and we need to generate the get state method. We Actually, it was just private. We have already reading this math at who? Yeah, that's pretty interesting. And all the tests past Look at that. Oh, how nice. I didn't expect that. I see that we have duplication here. I would re factor four calls These four calls to make move method. I would write private method make moves which takes game instance and a sequence off parameters. No fainted your time and I'll around for H loop here didn't exist of our index game. Make move, index. And now I can just make moves here, passing game and and passing the indexes Oh, actually, I can do this without writing the your reign. That's great. Everything passes. By the way. There is a simple case which I forgot to cover. The initial state off a square should be equal to unset. Let's prove that the implementation is incorrect. Or maybe correct. I don't know if you feel let's write another test. I'll write it here. Okay, I'll name it. Create board. By the way, maybe we are going to maybe whom I'm thinking off. Just adding these assertion right here. Maybe it's good. Maybe it's it's simple to rename this test create game game he's is in is incorrect state. Okay, game isn't correct. State finding name. Okay. Sounds like it is incorrect state. And add the assertion. We expect this state of set Oh, from the get state passing index one. And the test passes. Oh, yes. This is because this is because who we try to fix that test and went wrong? Way and initialized. There. A Yep. Yep. So we're already satisfied this test. Okay. Okay, That's fine. Nothing bad happened. So what are we going to do next? I feel like that The final step is to determine a winner, and generally we have three test cases. A winning line goes horizontally, vertically and diagonally. Let's ride a test. Well, that's right, By the way, these four assertions also can be affected. I'm knowing I'm not going to do this. Let's write another test. I'll call it Get winner Zeros. Ween vertically. Returns, returns. Zeros. Yeah, that will be of the value, often in admiration. I'll start from this assertion because we don't have that ap I yet. So this is going to be in the new variation winner Zeros, and it's going to be a method named Get Weiner. I guess at least it sounds logical. Let's create the game and the sequence to five and eight zeros. Zero should win and let's make a sequence of moves. Passing the game soul Cross it. One zero to three is going to be across. Five is going to be 07 is going to be across eight is going to be a zero. Let's generate while the stuff was generated. The winner. Yes, it's going to be in in groups. It's going to be an enumeration. It will contain zeros. I think it will contain crosses and it will contain Draw and game. He's and finished, though I'm not sure yet drawn. It will contain Draw, for sure, but I'm not sure about. The game is unfinished. Let's remove it for now. So let's generate the get winner method. It should return the enumeration. Now we need to write an actual implementation. I could run sleek loops to go through an array detecting, winning, winning lines, but I think I'll go the easier way. I'll just pass to a scanning math at all. The possible winning come by nations. Yes, let's do this. I'll create another method. I'll just get there there within that method. Winning combinations in triplets. So 36 line. 123 456 79 789 and two, Diagonals. 15 nine 357 It was generally the method. Oh, my goodness. Oh, my goodness. Uh uh Oh. Or a factory to Okay, the Rams argument. Yeah, it's much better. So I'll around in a loop through indexes incriminating. I buy three. Let's determine that. Are same signs in the next three Plett in Texas Story sore indexes in Texas? Uh, I plus one. All right. Lost to They're the same then that's determined was the winner. If State is not equal to onset, then we can return the winner using the Turn Eri operator. Otherwise, return zeros finally return draw. And, of course, we need to implement our same method, which takes a to be and see. We need to check if there this same there stayed the same. No get state equals and get state equals state. See? Yes, and the tests are passing. That's good. Another case concerns the diagonal winning combination. Let's add a corresponding test case. Maybe it will be satisfied automatically. I'm not sure I believe it should pass. Let's a very fire. This across is Ween. Your ankle returns? Crosses? Yes, the combination off 15 and nine should win the game. Run for five, say to end nine and crosses should wean. And indeed, the testes passing. Okay, the get winner method should yes, to get in your math. It should also understand when the game is unfinished. Let's right. The test that covers this case get winner game. He's on finished returns. Well, game is unfinished. Unfinished. Let's make some moves. I'll pass game. We're to four. Several lose the game is unfinished. Real. Each should bound, finished and let's assert that get winner returns. Yes, game is on Finished. I was right about the state game yet winner and the test fails off course it fails. It should fail. That's good. So we need to implement the corresponding BA hair. So let's go to Let's go to the get winner method and yes, we can. We can satisfy the test by the following condition. If moves counter last so than nine van, the return game is unfinished. Yes, that's right. The testes passing. I feel like we covered all the test cases. That's good. If you find any interesting test cases here, let me know about that on the discussion board or writing me a private message. I could forget something. So this is going to be your homework. Okay, let's try it. Declines code at first. I'll create a separate console application Console application? Yes, I'll name it Teak Tech two game and let's let's around these application. Let's play a game. Let's try to win her result liberal tickly and diagonally. I'll set This project has start up and run. I hope that the printable state will be fine. Let's looted. So let's try to play a game one to three. Yeah, crosses win. Let's wean vertically. 12 three, 56 eight Zeros, Ween and let's wean diagonally. 12 claws. Six nine Crosses win, and we can test the draw. By the way, let's test the draw when. Two three, five for seven eight, 96 year and the result is draw. Everything works as expected. Let's look at the test coverage. Mataric. Look at it, the tick tack toe game. He's covered by tests for almost 100%. Do you imagine how reliable our code is? We can trust our tests and cold. If someone introduces changes which break and a task, we will see that and start to investigate the problem. That was a great programming session. Let's move further 85. Continuous Testing: Muller and programmers like Practice, which names start from the work continues, for example, continues. Integration continues, deployment continues testing. Why not? Continuous integration is about automated building off the whole project on the server, triggered by some events like chicken off some cold into the source control continues. Deployment is about automating deployment as a continuation off the successful build. All these practices are intended to save the tile of developers. Well, we follow these practices. We don't forget to do what we have to, and we have to keep the project in a state. When these continues, practices are possible to have and run continues. Testing is up not so complex from the perspective off, setting up all the things continues. Integration s well as deployment requires from us. An enormous amount off efforts continues. Testing is much easier to set up and leave with. Everything you need is to choose a tool which provides this feature turning on and reap the benefits. One important note is that these tools require modern, powerful processors and a lot off memory. I doubt it's possible to use these tools on slow computers. So what is continuous testing? You had to notice that we're on the tests all the time. Air test has been changed. We need to run it. A chunk of code has been changed. We need to run all the corresponding tests. By the way, if we're on Onley, put off the whole test suite. We have some chance to forget about certain tests, and that can lead to unfortunate consequences. We could think that the implementation is correct until running the whole test suite. This extends the feedback, beard and, of course, damages. The effectiveness of the workflow continues. Testing tools are smart enough to detect changes both in tests and the production code and run all the tests related to changes Absolutely automatically, I would say that we have three major continues testing tools. The 1st 1 is an crunch Live unit testing in Enterprise Visual Studio 2017 continues testing in very sharper and Crunch is a leader. It's a very mature tool, and it's paid. I attached a link to and crunch check it out. You will discover that L Crunch also provides some code metrics and some other features. Live unit testing is available only in the enterprise version of Visual Studio Re shopping by itself doesn't support continues testing. Actually, there is a separate two called dot cover and it is paid. You can either purchase it separately or use it as a part off the re sharper ultimate package I installed and crunch to demonstrate you how continues testing works. Let's move to an interesting session where we will implement the ticktock, tore a game following TDD and relying on the continues testing provided by the end crunch tool. 86. Clean Code and TDD Conclusion: Hi. This is injurious bark from injuries Plugged it. Congratulations. You've reached the end of the section and in this section you learned what is to D D and why we need it. It helps to drive the pie from the client's point off you. It helps to write more reliable code. The main TDD cycle is called the Red Green Red Factor. What means writing a failing test? Fixing the production code under factoring the production code three lows off Dez Drew in development. You watched how to implement converting off Roman numerals to Robin, you learned that continues Testing is quite helpful since introduces the main TDD cycle. It makes it shorter in time and you watched how to implement a tick tack toe a game using TD D.