Presentation on theme: "Design Principles & Patterns"— Presentation transcript:
1 Design Principles & Patterns Some of my favorite patterns, practices, and other stuff.
2 About Some established design principles Some patterns Some ideas Concepts that don’t specify implementationSome patternsWays to write software that have been proven successfulSome ideasMost of the individual patterns or principles are simple. Using them in a complex environment is not.
3 Choosing Patterns Don’t implement a pattern for patterns’ sake Implement patterns to solve problemsUnderstand the trade offsDon’t be dogmaticFind what works best for your team.
4 SOLID An acronym for design principles introduced by Robert C. Martin S: Single Responsibility Principle (SRP)O: Open-Closed Principle (OCP)L: Liskov Substitution Principle (LSP)I: Interface Segregation Principle (ISP)D: Dependency Inversion Principle (DIP)
5 SOLID SOLID Motivational Posters, by Derick Bailey These principles lead toward dev of systems that are easy to maintain and extend over time.Bob Martin:“Poor dependency management leads to code that is hard to change, fragile, and non-reusable.”“On the other hand, when dependencies are well managed, the code remains flexible, robust, and reusable.”
7 Single Responsibility Principle A class should have one, and only one, reason to change.A class should have only a single responsibilityi.e. only one potential change in the software's specification should be able to affect the specification of the classEasier to test, read, and maintainLess side effectsSeparation of ConcernsNaming gets tricky
9 Open/Closed Principle Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.You should be able to extend a classes behavior, without modifying it.You should be able to add new features without changing a classes existing behavior.
11 Liskov Substitution Principle Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.Derived classes must be substitutable for their base classes.Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.“Is a” vs “Is substitutable for”
13 Interface Segregation Principle Clients should not be forced to depend upon interfaces that they don’t use.Make fine grained interfaces that are client specific.Many client-specific interfaces are better than one general-purpose interface.Makes it easy for the client
15 Dependency Inversion Principle High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstraction should not depend on details. Details should depend on abstractions.A class should not use a dependency directly, it should use an abstraction or interface.And the dependency should be based on the same abstractionThis puts the abstraction in the middle.Depend on abstractions, not concrete implementations (use Interfaces or base classes)
16 Dependency Inversion Principle Depend upon Abstractions. Do not depend upon concretionsDependency injection is one method of following this principle.DI is about how one object acquires a dependency. When a dependency is provided externally, then the system is using DI. IoC is about who initiates the call. If your code initiates a call, it is not IoC, if the container/system/library calls back into code that you provided it, is it IoC.DIP, on the other hand, is about the level of the abstraction in the messages sent from your code to the thing it is calling. To be sure, using DI or IoC with DIP tends to be more expressive, powerful and domain-aligned, but they are about different dimensions, or forces, in an overall problem. DI is about wiring, IoC is about direction, and DIP is about shape.
19 YAGNI You Ain’t Gonna Need It Helps fight scope creep MVP: Minimum Viable ProductGet it Done!This is a balancing actKISS – Keep It Simple Stupid
20 Generics Not a design principle or pattern Language Feature, can be treated as a patternSince 2.0Use ReturnResult Pattern as an example (next slide).
21 ReturnResult Pattern Ok, I made that name up. For APIs, don’t return simple results or sets.Usually there is a need for more information.public Person GetPerson(Parameters p)What if it fails?What if the parameters are not valid?What does it mean if null is returned? No record exists? Error?
22 What we need…This would get problematic very quickly
25 More Result Objects PersistResult PersistResult<T> ExecuteResult ExecuteResult<T>
26 Repository Pattern A repository is an abstraction over a data set Helps with testingAbstracts the implementation so it can be changed (But who does that?)Data SET vs Data SOURCE. One repo per table, not db.Expose CRUD Operations not implementation detailsShould not understand or care about business rules
27 Implementing Repository Pattern Use for ALL data sourcesEntity FrameworkOther DatabaseFilesWeb Services3rd Party LibrariesI like it for consistencyQuery is where it breaks down and has “morphed” latelyExpose IQueryable?? I do.Don’t confuse the pattern with the implementation (Generics does not make it a pattern)Names should not expose the implementationXYZRepository that happens to store XYZ data in a fileNot XYZFileRepository(Demo)
28 Unit of WorkMartin Fowler on the Unit of Work pattern: "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.“Entity Framework implements Unit of Work with DbContext.SaveChanges()In my solutions, I create a UnitOfWork Class that works better with a layered design. It essentially wraps DbContext.
29 Exception Handling Not a pattern, but how you use it is a pattern Why do you catch exceptions?When you can do something about it.If not, what is the point?When should you catch exceptions?As seldom as possibleAt boundariesWhen it mattersELMAH
30 Macro and Micro Services Came up with the name while working at AcademyOne with Troy Starcher.Micro Services are the small Single Responsibility Classes such as:ValidatorsInitializersAdapters/ConvertersMacro Services are the Orchestrators, the classes that “use” the Micro Services
31 MVC I use MVC on the Server MVVM on the Client Less and Less MVC Model ViewControllerASP.NET MVC is a Server Side implementation of the MVC Pattern
33 Model vs ViewModel Name SSN HireDate Department Title etc Employee EmpoyeeEditEmployeeVmNameSSNHireDateDepartmentTitleetcEmployeeDepartmentListTitleListUpdateEmployee
34 Async PatternFor UI apps, the primary benefit of async is responsivenessFor Server apps, the primary benefit of async is scalabilityThreads go back to the thread pool.Async uses less memory because each thread needs memory.There are limits on how fast threads can be created(demo)
35 A lot of food for thought It’s important to really understand these thingsTo do so, you must play around with them and experiment