Weekly Dev Tips cover image

Weekly Dev Tips

Latest episodes

undefined
Jul 2, 2018 • 7min

What Good is a Repository

What good is a repository? This week I'm following up on last week's tip about the Repository pattern. A listener pointed out to me that I never directly answered the question posed in the last episode of "Do I need a repository?" I'll be sure to do so here. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript Last episode I addressed a fairly common online argument against the use of repositories. I suggest you listen to that episode and then jump back into this one, but hey, you do what you want. I addressed the usual arguments against using a repository by using a particular article as an example, but I want to be clear that that article was by no means the direct cause of my response. In fact, I hadn't even seen that particular article until I sat down to record the episode and it happened to be pretty high up in my search results and made a good example of the kinds of arguments folks like to throw out when arguing against the pattern. So, now that we've heard and perhaps refuted some of the arguments against using the repository pattern, let's talk about why you might use it. What good is a Repository in your application? The Repository pattern is simply an abstraction of your persistence strategy for your application. In fact, the repository pattern is most frequently used along with the strategy design pattern as a way to pull low level knowledge of persistence details out of your application's other classes. I've heard the repository pattern also described as an example of the facade design pattern, since it hides away much of the detail of this or that persistence technology and exposes a much simpler interface for getting and storing entities. I can get behind that definition, too. You can think of the repository pattern as essentially a particular use case of the facade pattern in which the complex underlying implementation is related to persistence. There's one more pattern we can consider in relation to the repository, though, and that's the adapter. The main difference between a facade and an adapter is in the intent. A facade's intent is to simplify, while an adapter's intent is to allow multiple implementations to be accessed through a common interface. A repository typically does both of these things, providing a simple interface that hides unneeded complexity and allows multiple implementations, like relational, non-relational, in-memory, or even file- or API-based approaches. So, the repository pattern is all about providing an intention-revealing name to a facade or adapter that can be used as a strategy to reduce coupling in your application. Let's drill into these other patterns a little more. The strategy pattern lets you change how a class does something without having to change the class itself. If you're familiar with dependency injection, you already know this pattern. It works by passing in as a parameter a particular implementation to be used, allowing this implementation to vary without the class that uses it having to change. It's one of the most powerful design patterns for writing loosely-coupled code that follows the SOLID principles. It's very challenging to write unit-testable code in strongly typed languages without using this pattern. The facade pattern is helpful when you want to make a complex API easier to use. This might be because the complexity is unnecessary, or because there are certain "right ways" to do things in your particular application and you want to make it easier for your team to follow the right path and avoid the wrong ones. Creating a facade to expose simple persistence operations like creating, updating, and deleting records, as well as some mechanism for fetching and querying, is a pretty common technique and can allow teams to focus on business logic moreso than data access logic in many cases. That said, keep in mind that the facade can hide useful features and sometimes necessary complexity that client software should otherwise be able to access. Care must be taken in how the facade is designed to ensure it doesn't cripple the use of the libraries it wraps. The adapter pattern is helpful for testing, since it allows tests to easily substitute in implementations that behave however the particular test requires. Using adapters can also allow an application to work more flexibly with different actual providers, plugging in the appropriate one as necessary. You can see that the Repository pattern is really a particular implementation of one or more other, more generic patterns. Next week I'll talk a little bit more about the pattern, and how it can be further extended by layering additional patterns on top of it. Let's wrap up this episode by answering an important question. Do I need a repository? No, you don't need a repository. However, if any of the benefits I've described in the last two episodes sounds like something you might want in your application, you might consider it. If you want unit testability, an abstraction over data access will save you a lot of pain. If you want flexible, modular code, the same is true. If you want low-level access to all the features of your data access technology everywhere you use it, then you might not want an abstraction over it. If your application isn't set up to make use of dependency injection, it may not be worthwhile, since newing up repositories everywhere you need them will still tightly couple you to implementation details. Do you think your team or application could be improved by better use of design patterns? I offer remote and onsite workshops guaranteed to improve your coding skills and application code quality. Contact me at ardalis.com and let's see how I can help. Show Resources and Links Repository Pattern SOLID Principles New is Glue (why you don't want to new up repositories everywhere - seel also Ep 5)
undefined
Jun 11, 2018 • 8min

Do I Need a Repository?

Do I Need a Repository? This week we'll answer this extremely common question about the Repository pattern, and when you should think about using it. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript This week we're going to return to the Repository design pattern to answer a very common question: when should you use it? This question appears very frequently in discussions about Entity Framework or EF Core, usually with someone saying "Since EF already acts like a repository, why would you create your own repository pattern on top of it?" Before we get into the answer to this question, though, let me point out that if you're interested in the repository pattern in general I have a link to a very useful EF Core implementation in the show notes for this episode that should help get you started or perhaps give you some ideas you can use with your existing implementation. Also, just a reminder that we talked about the pattern in episode 18 on query logic encapsulation, but otherwise I haven't spent a lot of time on repository tips here, yet. Ok, so on to this week's topic. Should you bother using the repository pattern when you're working with EF or EF Core, since these already act like a repository? If you Google for this, you're likely to discover an article discussing this topic that suggests repository isn't useful. In setting the scene, the author discusses an app he inherited that had performance issues caused by lazy loading, which he says "was needed because the application used the repository/unit of work pattern." Before going further, let's point out two things. One, lazy loading in web applications is evil. Just don't do it except maybe for internal apps that have very few users and very small data sets. Read my article on why, linked from the show notes. Second, no, you don't need lazy loading if you're using repository. You just need to know how to pass query and loading information into the repository. The author later goes on to say "one of the ideas behind repository is that you might replace EF Core with another database access library but my view it's a misconception because a) it's very hard to replace a database access library, and b) are you really going to?" I agree that it's very hard to replace your data access library, unless you put it behind a good abstraction. As to whether you're going to, that's a tougher one to answer. I've personally seen organizations change data access between raw ADO.NET, Enterprise Application Block, Typed Datasets, LINQ-to-SQL, LLBLGen, NHibernate, EF, and EF Core. I've probably forgotten a couple. Oh yeah, and Dapper and other "micro-ORMs", too. If you're using an abstraction layer, you can swap out these implementation details quickly and easily. You just write a new class that is essentially an adapter of your repository to that particular tool. If you're hardcoded to any one of them, it's going to be a much bigger job (and so, yeah, you're less likely to do it because of the pain involved.) Next, the author lists some of the bad parts of using repository. First, sorting and filtering, because a particular implementation he found from 2013 only returned an IEnumerable and didn't provide a way to allow filtering and sorting to be done in the database. Yes, poor implementations of a pattern can result in poor performance. Don't do that if performance is important. Next, he hits on lazy loading again. Ironically, at the time this article was published, EF Core didn't even support lazy loading, so this couldn't be a problem with it. Unfortunately, now it does, but as I mentioned, you shouldn't use it in web apps anyway. It has nothing to do with repository, despite the author thinking they're linked somehow. His third perf-related issue is with updates, claiming that a repository around EF Core would require saving every property, not just those that have changed. This is also untrue. You can use EF Core's change tracking capability with and through a repository just fine. His fourth and final "bad part" of repositories when used with EF Core is that they're too generic. You can write one generic repository and then use that or subtype from it. He notes that it should minimize the code you need to write, but in his experience as things grow in complexity you end up writing more and more code in the individual repositories. Having less code to write and maintain really is a good thing. The issue with complexity resulting in more and more code in repositories is a symptom of not using another pattern, the specification. In fact, the specification pattern addresses pretty much all of the issues described in his post that I haven't already debunked. The author knows about this pattern, which he describes as 'query objects', but doesn't see how they can be used together with repositories just as effectively as he uses them instead of repositories. One last thing I want to point out that many folks (including the author of this article) misunderstand is the idea of being able to unit test code that works with data. This might just come down to the definition of a unit test, so I'll start with that. A unit test is a test that only tests your code at the unit level. That typically means a single method, or at most a class since to access a single method you may need to create an instance of a class and thus also execute its constructor, etc. If you have a test that tests more than one class working together, or that depends on code that isn't yours (like, say, an ORM), it's not a unit test. It's an integration test. The author goes on to suggest that since EF Core supports an in-memory database, you can use that for unit-testing your application. You can't. You can use it for integration testing, which is great. But it's not unit testing. The distinction is important because clean code should be unit testable. If it isn't, it's a code smell, suggesting that you may have too much coupling. You might be OK with that, but you should at least be aware of the issue so you can decide for yourself whether you're OK with it, rather than having a false sense of complacency because your integration tests work well enough. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Repository Pattern Is the repository pattern useful with EF Core? Avoid Lazy Loading Entities in ASP.NET Applications Specification Pattern Unit Test or Integration Test (and why you should care) Integration Tests in ASP.NET Core
undefined
Jun 4, 2018 • 5min

Domain Events - After Persistence

Domain Events - After Persistence The previous tip talked about domain events that fire before persistence. This week we'll look at another kind of domain event that should typically only fire after persistence. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript If you're new to the domain events pattern, I recommend you listen to episode 22 before this one. In general, I recommend listening to this podcast in order, but I can't force that on you... When you have a scenario in your application where a requirement is phrased "when X happens, then Y should happen," that's often an indication that using a domain event might be appropriate. If the follow-on behavior has side effects that extend beyond your application, that's often an indication that the event shouldn't occur unless persistence is successful. Let's consider a contrived real-world example. Imagine you have a simple ecommerce application. People can browse products, add them to a virtual cart or basket, and checkout by providing payment and shipping details. Everything is working fine when you get a new requirement: when the customer checks out, they should get an email confirming their purchase. Sounds like a good candidate for a domain event, right? Ok, so your first pass at this is to simply go into the Checkout method and raise a CartCheckedOut event, which you then handle with a NotifyCustomerOnCheckoutHandler class. You're using a simple in-proc approach to domain events so when you raise an event, all handlers fire immediately before execution resumes. You roll out the change with the next deployment. Unfortunately, another change to the codebase resulted in an undetected error related to saving new orders. Meaning, they're not being saved in the database. Now the result is that customers are checking out, being redirected to a friendly error screen, but also getting an email now confirming their order was placed. They're mostly assuming everything is fine on account of the pleasant email confirmation, but in fact your system has no record of the order they just placed because it didn't save. In this kind of situation, you'd really rather not send that confirmation email until you've successfully saved the new order. While in-proc domain events are often implemented using simple static method calls to raise or register for events, post-persistence events need to be stored somewhere and only dispatched once persistence has been successful. One approach you can use for this in .NET applications is to store the events in a collection on the entity or aggregate root, and then override the behavior of the Entity Framework DbContext so that it dispatches these events once it has successfully saved the entity or aggregate. My CleanArchitecture sample on GitHub demonstrates how to put this approach into action using a technique Jimmy Bogard wrote about a few years ago. It involves overriding the SaveChanges method on the DbContext, finding all tracked entities with events in their collection, and then dispatching these events. His original approach fires the events before actually saving the entity, but I much prefer persisting first and using a different kind of domain event for immediate, no side effect events. In the Clean Architecture sample, I have a simple ToDo entity that raises an event when it is marked complete. This event is only fired once the entity's state is saved. At that point, a handler tasked with notifying anybody subscribed to that entity's status could safely send out notifications. The pattern is very effective as a lightweight way to decouple follow-on behavior from actions that trigger them within the domain model, and it doesn't require adding additional architecture in the form of message queues or buses to achieve it. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Clean Architecture Sample (GitHub) Domain-Driven Design Fundamentals - includes Domain Events
undefined
Apr 30, 2018 • 7min

Domain Events - Before Persistence

Domain Events - Before Peristence Domain Events are a DDD design pattern that in my experience can really improve the design of complex applications. In this episode I describe specifically how you would benefit from raising and handling these events prior to persisting the state of your entities. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript So before we get started, let's describe what a domain event is. A domain event is something that happens in your system that a domain expert cares about. Domain events are part of your domain model. They belong in the Core of your Clean Architecture. They should be designed at the abstraction level of your domain model, and shouldn't reference UI or infrastructure concerns. Domain events are a pattern, and one with several difference implementation approaches. I generally segment these approaches into two camps: before persistence and after persistence. For this tip, we're going to focus on events that occur and are handled prior to persistence. In future tips, I'll talk about domain events that should only be dispatched once persistence has been successful. So, as a pattern, what problem are domain events designed to solve? Just as with other event-driven programming models, such as user interface events, domain events provide a way to decouple things that occur in your system from things such occurrences trigger. A common example I use is checking out a shopping cart from an ecommerce site. When the user checks out, a variety of other things generally should take place. The order should be saved. Payment should be processed. Inventory should be checked. Notifications should be sent. Now, you could put all of this logic into a Checkout method, but then that method is going to be pretty large and all-knowing. It's probably going to violate the Single Responsibility and Open/Closed Principles. Another approach would be to raise an event when the user checks out, and then to have separate handlers responsible for payment processing, inventory monitoring, notifications, etc. Looking specifically at events that make sense to handle before persistence, the primary rule is that such events shouldn't have any side effects external to the application. A common scenario is to perform some kind of validation. Imagine you have a Purchase Order domain object, which includes a collection of Line Item objects. The Purchase Order has a maximum amount associated with it, and the total of all the Line Item object amounts must not exceed this amount. For the sake of simplicity let's say the Purchase Order object includes the logic to check whether its child Line Item objects exceeds its maximum. When a Line Item object is updated, how can we run this code? One option would be to provide a reference from each Line Item to its parent Purchase Order. This is fairly common but results in circular dependencies since Purchase Order also has a reference to a collection of its Line Item objects. These objects together can be considered an Aggregate, and ideally dependencies should flow from the Aggregate Root (in this case Purchase Order) to its children, and not the other way around. So, let's assume we follow this practice, which means we can simply call a method on Purchase Order from Line Item directly. Another common approach I see developers use instead of domain events is to pull all of the logic up from child objects into the aggregate root object. So instead of having a property setter or property on Line Item to update its amount, there might be a method on Purchase Order called UpdateLineItemAmount that would do the work. This breaks encapsulation and will cause the root object to become bloated while the child objects become mere DTOs. It can work, but it's not very good from an object-oriented design standpoint. So how would domain events apply here? First, you'd put the logic to modify Line Item on the Line Item class where it belongs. Then, in the UpdateAmount method, you would raise an appropriate domain event, like LineItemAmountUpdated. The aggregate root would subscribe to this event and would handled the event in process (not asynchronously or in another thread). If necessary, the handler could raise an exception. In any case, it could update properties of the root object to indicate whether it was currently in a valid state, which could easily be reflected in the UI. This is one particular use case for domain events that I've found very helpful, and which I typically refer to as aggregate events since there isn't a separate event handler type in this case. I have a small sample showing them in action on GitHub you can check out in the show notes. With aggregate events in place, you can check all the blocks for your object design. Your aggregate's dependencies flow from root to children. Your aggregate's child objects are responsible for their own behavior. Changes to child objects are communicated to the aggregate root which is responsible for ensuring the validity of the entire aggregate. Many scenarios have rules where the root object has to perform validation checks that are based on the aggregate of several child objects, and this pattern provides an elegant solution to this problem. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Clean Architecture Sample (GitHub) Aggregate Design Pattern Aggregate Events Sample (GitHub)
undefined
Apr 23, 2018 • 6min

Breadcrumbs and Troubleshooting

Breadcrumbs and Troubleshooting This week I'm taking a break from design patterns to talk about a useful skill to prevent you and your team having to reinvent the wheel when it comes to troubleshooting problems or working through new tools or frameworks. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript Have you ever spent a few hours working through getting a new tool, library, package, or framework working? Along the way, did you run into things that didn't quite go as easily as the documentation, video, or presentation on the subject made it out to be? Did you end up spending time on Google, StackOverflow, etc. trying to figure out how to really get things to work in your real world environment? If you answered yes to these questions, you're in good company. I've certainly been there countless times. Now, follow-up question. Have you ever done all of the above, but with a sense of deja vu, because you'd had to do the exact same thing some time previously? And when you found the blog post or sample that reminded you of the issue, you were like "Oh yeah, I had to do this last time, too!" I find these to be some of the most frustrating hours of my work. I want to be building things, making progress, seeing things grow in functionality, not banging my head against the same walls I've left dents and bloodstains on in the past. I also want to make sure my coworkers, my teammates, and my clients benefit from the cuts and bruises I acquire as I blaze a trail through unknown territories. So, what can you do to limit the amount of retreading through through the same painful terrain you (and often your team) have to do? Obviously the first thing you could do is take notes. This is natural for some developers, but others find it distracting. When they're in the zone, figuring things out and getting things done, they don't want to stop to document things along the way. Breaking their flow might mean the difference between getting things working and giving up and walking away. If you can take notes, do so. I suggest keeping track of the URLs you found useful, along with screenshots of things like property settings or other configurations that you needed to modify to get things working. Sometimes, you can document things after you got things working. This is often true for fairly simple problems. However, for something that's taken hours rather than minutes, it's likely that by the time you're done, you've forgotten a few steps along the way. Here are a few things you can do to leave yourself a trail of breadcrumbs as you work. And of course, by breadcrumbs, I actually mean something better than breadcrumbs that you'll actually find later, since the whole origin of breadcrumbs is from a story in which breadcrumbs are a decidedly poor choice to leave behind you in order to find your way. One approach I use is to use a particular browser instance while I'm working on a specific problem, and to open all links related to the problem at hand in their own tabs. If they're useless, I close them, but if they're at all helpful, I leave them open. Once I've figured out whatever it is I've been working on, I can look at my tab history and add the links as references wherever is appropriate. Sometimes that's a link in a source code file. Sometimes it's in a README file. Sometimes it's in a blog post (or a Trello card for a blog post I want to write). In any case, I associate the links to the resources that helped me along the way with the problem I just solved while everything is still fresh in my mind and the links are literally stil open in my browser. Another tool you can use is screen recording. If you don't like actually writing/typing notes, you can record conference calls with clients using tools like Zoom or GoToMeeting. You can also record your own screen using tools like Camtasia, which I highly recommend. Then you can quickly jump around in the video to see yourself tackling problems, and retroactively make notes or write up a postmortem or checklist. Occasionaly the video itself might even be worth editing into something, perhaps for internal consumption by your team. Yet another tool I've used in the past is TimeSnapper, which would take and store screenshots every so many seconds on your machine. Then it would let you play them back later to see what you'd been spending your time on. I haven't used it in a while but it appears to still be active. You could do something similar by just taking a screenshot periodically as you progress through a problem, but you're much more likely to forget without a tool like this. The most important thing to take away from this episode is that you don't want to fight through the same problem more than once. Ideally you want to prevent your team from having to fight through problems you've already solved. The key is to share the necessary information in a way that doesn't slow you down while you're solving the problem, but which ultimately is discoverable by you and your team the next time you encounter the same problem. An approach I've used for years is to blog about things once I find a solution. I can't tell you how many times I've googled for something only to find the answer on my own blog. If you have your own techniques you use to rediscover solutions to problems you've previously solved, please leave them in the comments for the show. Oh, and I wrote an article last year on Working Through Roadblocks - A Guide for New Programmers. I'll leave a link in the show notes for that as well. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Camtasia TimeSnapper Working Through Roadblocks - A Guide for New Programmers
undefined
Mar 12, 2018 • 6min

Abstraction Levels and Authorization

Abstraction Levels and Authorization Working at too low of an abstraction level is a common source of duplication and technical debt. A very common culprit in this area is authorization. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript Let's take a quick break from the more commonplace design patterns and talk a little bit about abstraction levels and how they impact duplication and technical debt in our software designs. You can think of high levels of abstraction as being at the level of the real world concept your software is modeling. For an ecommerce application, it might be buying something, or adding an item to a cart. The whole notion of a cart or basket is a metaphor explicitly pulled into ecommerce applications from the real world. There's certainly no literal cart or basket involved in most online shopping experiences. Low levels of abstraction refer to implementation details used by the actual software (and sometimes hardware) used by the system. When developing software, it's a good design decision to encapsulate low levels of abstraction separately from higher levels, and thus to avoid mixing abstraction layers more than necessary within any given module. The more you mix abstraction levels, the more you add tight coupling to your design, making it harder to change in response to future requirements. A common requirement in many applications is authorization. Authorization is often conflated with the other auth word, authentication. Authentication is the process of determining who the user is. Authorization is the process of determining whether a particular user should be allowed to perform a certain operation. It can include default rules for anonymous users, but aside from that authorization only makes sense once authentication has taken place and you know who the user is. Authorization rules can take many forms, and can be as granular as specifying that a specific user has access to a specific resource. However, most applications that need authorization will leverage roles or claims to specify how groups of users should or should not have access to certain sets of resources. This makes it much easier to manage collections of users and collections of resources, since otherwise a huge number of specific user-to-resource rights would need to be maintained. However, even this is often prone to duplication that results from too low of an abstraction level. It's common in platforms like .NET to use roles as at least one part of determining authorization, and to use conditional logic like if (user.IsInRole("Admins")) any time authorization logic needs to be performed. In any non-trivial system that uses this pattern, you'll probably find quite a few lines of code that match this expression, meaning there is a great deal of duplication. Duplication isn't always bad, but in this case the implementation detail of performing a role check as one part of checking whether a user is authorized to access a particular resource is adding to the system's technical debt. Frequently, authorization rules will change over time. What happens when a new role or set of claims is created that should have access to some resources? Every one of the if statements related to access to that resource will need to be modified. What happens if you switch from using roles to claims? Every if statement will need to be modified. Of course, when these modifications take place, there's also the chance that bugs will be introduced, and these will manifest in many cases as security breaches. There are many patterns you can use to improve this design. You can use a more declarative approach, such that adding certain attributes will protect certain endpoints in your application. This can remove conditional logic and can eliminate some duplication since these attributes can be applied at class or even base class levels. However, if your authorization logic is more complex than simple role membership, it may not be sufficient or at the least you'll need to write your own attributes or filters. Another approach I've found useful is to create a first-class abstraction that describes whether a given user should have access to a given resource. I typically call such types privileges but you can refer to them as AuthorizationPolicies or whatever makes sense to you and your team if you prefer. A privilege takes in who the user is and what resource they're attempting to work with, and specifies what operations that user can perform on that resource. Since it's a design pattern, not a specific solution, how you implement the details is up to you. A common approach is to implement methods for things CanRead, CanCreate, and CanModify. You can also further modify it to work for collections or types of resources, so that for example if the user should be able to manage product definitions, you could check whether the user has rights to type Product and if so, include a link to manage products in the application's menu. I have an article describing how to use privileges instead of repetitive role checks that I'll link to in the show notes that may help you get started if you're interested in learning more. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Favor Privileges over Role Checks Technical Debt
undefined
Feb 26, 2018 • 6min

Learn the Strategy Pattern

Learn the Strategy Pattern The Strategy design pattern is one of the most fundamental and commonly-used patterns in modern object-oriented design. Take some time to make sure you're proficient with it. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript I'm continuing a small series of tips on design patterns that I started with episode 17. I encourage you to listen to these tips in order, since in many cases they'll build on one another. This week I want to briefly describe the strategy pattern, and more importantly, why I think it's a pattern every object-oriented software developer should know. The strategy design pattern is often applied as a refactoring technique to improve the design of some existing code. The original code likely has some tightly-coupled and/or complex logic in it that would be better off separated from the current implementation. I think one reason why I'm so fond of the strategy pattern is that it literally helps with every one of the SOLID principles of object-oriented design. In my SOLID course on Pluralsight, I also discuss the Don't Repeat Yourself, or DRY, principle, which strategy can help with as well. Let's look at how. First, if you have a class that's doing too much (therefore breaking SRP - Single Responsibility Principle), common refactorings like extract method and move method can be used to pull logic out of one big method. However, if you then call this method from the big method, either statically or by directly instantiating a class to which you've moved the logic, you're not helping the coupling aspect of the problem. We'll get to that when we get to the 'D' in SOLID. Applying the strategy design pattern in this case is really just a slight twist on the usual extract and move method refactorings. You're still doing that, but you also typically create a new interface and pass in the interface to the original code. After moving the original implementation code to a new class that implements the new interface, you should have a new class that follows SRP and your original class should at least have fewer responsibilities. Considering this refactoring I just described, it's easy to see how it can help with the Open/Closed principle, or OCP, too. Whereas the original code's complex logic would have needed modified and recompiled any time a change was requested, the new design can accommodate changes in the implementation of extracted method by writing new code that implements the same interface. Then, an instance of the new class that has this new implementation can be passed into the existing code without touching the existing code. I talked about how important this is with legacy code in episode 15. Of course, if you do have multiple implementations of your abstract types, it's important that they all behave as advertised, otherwise you may encounter runtime exceptions. Ensuring that any implementation you write that inherits from another type, whether an interface or a class, means following the Liskov Substitution Principle, or LSP. Following LSP is much easier when the base type's behavior is fairly small. Large interfaces require much more effort to fully implement that smaller ones. The Interface Segregation Principle, or ISP, suggests keeping interfaces small and cohesive, so that client code doesn't need to depend on behavior it doesn't use. Done properly, the interfaces you create while implementing the strategy design pattern should be tightly focused. That brings us to the Dependency Inversion Principle, or DIP. This is really what the strategy pattern is all about. Whereas the initial code was tightly coupled to a specific implementation, the refactored version of the original method now depends on an abstraction. Instead of the original method deciding how to do the work, the code that calls the method makes that decision by deciding which implementation of the interface to provide. If you're familiar with dependency injection, then the strategy pattern should already be familiar to you. Make sure you're comfortable with pulling out dependencies when you discover them, though. The method extract and interface creation aspects of the strategy pattern aren't always emphasized when dependency injection is discussed. We're out of time for this week but I'll mention that the strategy pattern also helps with the DRY principle by creating a single place for a particular implementation to live, as well as the Explicit Dependencies Principle, by ensuring classes request their dependencies rather than hiding them in their methods. You can learn more about these principles from the show notes at weeklydevtips.com/019. Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Strategy Pattern SOLID Principles of OO Design (Pluralsight) Refactoring Fundamentals (Pluralsight) Don't Repeat Yourself (DRY) Explicit Dependencies Principle Design Patterns by Gamma, Helm, Johnson, Vlissides (Gang of Four) Design Patterns Library (Pluralsight)
undefined
Feb 19, 2018 • 9min

Repository Tip - Encapsulate Query Logic

Repository Tip - Encapsulate Query Logic The Repository design pattern is one of the most popular patterns in .NET development today. However, depending on its specific implementation, its benefits to the system's design may vary. One thing to watch out for is query logic leaking out of the repository implementation. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript Last week I talked about Design Patterns in general, and how in most cases it makes sense to have basic familiarity with a breadth of patterns, but to go deep on the ones that are most valuable in your day-to-day development. Repository is one of a handful of patterns I've found to be useful in virtually every ASP.NET app I've been involved with over the last ten years or so. Before I knew about this pattern, I'd already learned that separation of concerns was a good idea, and that having a separate layer or set of types for data access was beneficial. The biggest benefit you get by using a Repository instead of a Data Access Layer or static DB helper class is reduced coupling, because you can follow the Dependency Inversion Principle. By the way, if you're not familiar with any of these terms or principles, there are links on the show notes page at weeklydevtips.com/018, where you'll also find a link to my recommended generic repository implementation. This week's tip assumes you're already at least basically familiar with the repository pattern. Recently, I'm spending most of my time helping a variety of teams to write better software, and a pretty common issue I find for those app using the repository is that query logic can leak out. This can result in code and concept duplication, which violates the Don't Repeat Yourself, or DRY, principle. It can also result in runtime errors if query expressions are used that LINQ-to-Entities cannot translate into SQL. The most common reason for this issue is repository List implementations that return back IQueryable results. An IQueryable result is an expression, not a true collection type. It can be enumerated, but until it is, the actual translation from the expression into a SQL query isn't performed. This is referred to as deferred execution, and it does have some advantages. For instance, if you have a repository method that returns a list of customers, and you only want those whose last name is 'Smith', it can dramatically reduce how much data you need to pull back from the database if you can apply the LastName == Smith filter before the database query is made. But where are you going to add the query logic that says you only want customers named 'Smith'? That sort of thing is often done in the UI layer, perhaps in an MVC Controller action method. For something very simple, it's hard to see the harm in this. But imagine that instead of filtering for customers named 'Smith', you were instead writing a filter that would list the optimal customers to target for your next marketing campaign, using a variety of customer characteristics and perhaps some machine learning algorithms. Once you start putting your query logic in the UI, it's going to start to multiply, and you're going to have important business logic where it doesn't belong. This makes your business logic harder to isolate and test, and makes your UI layer bloated and harder to work with. The problem with the IQueryable return type from repositories is that it invites this kind of thing. Developers find it easy to build complex filters using LINQ and lambda expressions, but rarely take the time to see whether they're reinventing the wheel with a particular query. The fact that this approach can easily be justified because of the benefits of deferred execution and perhaps the notion that the underlying repository List method is benefiting greatly from code reuse only exacerbates the problem. The underlying problem with returning IQueryable is that it breaks encapsulation and leaks data access responsiblities out of the repository abstraction where it belongs. Rather than returning IQueryable, repositories should return IEnumerable or even just List types. Doing so consistently will ensure there is no confusion among developers as to whether the result of a repository is an in-memory result or an expression that can still be modified before a query is made. But then how do you allow for different kinds of queries, without performing them all in memory? There are a few different approaches that can work, and I'll cover them in future tips, but the simplest one is to add additional methods to the Repository as needed. This is often a good place to start, as it is simple and discoverable. In the example I'm using here, the CustomerRepository class could have a new method called ListByLastName added to it, which accepted a lastName parameter and returned all customers with that last name. Likewise, a collection of customers fitting certain characteristics for a new marketing campaign would be returned by another appropriately-named method. Over time, this may result in repositories with a lot of different methods, but this is preferable to having query logic scattered across the UI and possibly other parts of your application (and we'll see how to fix this soon). Would your team or application benefit from an application assessment, highlighting potential problem areas and identifying a path toward better maintainability? Contact me at ardalis.com and let's see how I can help. Show Resources and Links Repository Pattern Design Patterns by Gamma, Helm, Johnson, Vlissides (Gang of Four) Domain-Driven Design Fundamentals (Pluralsight) Design Patterns Library (Pluralsight)
undefined
Feb 5, 2018 • 5min

On Design Patterns

On Design Patterns Design Patterns offer well-known, proven approaches to common problems or situations in software application development. Having a broad knowledge of the existence of patterns, and at least a few you're proficient in, can dramatically improve your productivity. Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript I'll admit I've been a fan of design patterns for a long time. The idea of design patterns transcends software development, and in fact the so-called Gang of Four book, Design Patterns, takes its organization and inspiration from the 1977 book, A Pattern Language. That book, by Christpher Alexander, describes common patterns in towns, buildings, and construction methods, but the idea that there are common patterns to solving similar problems applies equally to software as well as traditional building construction and architecture. One thing that really appeals to me about design patterns is their ability to reduce waste. As software developers, we tend to want to increase efficiency and productivity, and one of the most frustrating parts of writing software (for me, at least) is when I'm stuck on a problem. This frustration is even greater when it's a problem I feel like I should know the answer to, or that I know is relatively common, so someone has solved it before. Design patterns are a great way to help you avoid reinventing the wheel (or, in many cases, a giant square that you're hoping will work as a wheel). Unfortunately, you can't always use your usual search engine skills to come up with a design pattern. You usually have to at least be aware that it exists so that you can start to recognize scenarios where it might apply. Once you know that a pattern exists, and have at least a vague sense of when it's used, then you can easily search for more information on how to apply the pattern when you think you might have a situation that warrants it. Thus, the first step in your path to pattern mastery is exposure. You need to spend at least a little bit of time learning the names of the patterns that exist, and where they're used. If you haven't already, you'll probably find a few design patterns that you use all the time. You can go deep in your knowledge of how and when to use these patterns. Last week, I talked about becoming a T-shaped developer as a means of differentiating yourself among competitors. Your knowledge of design patterns should have a similar T-shape, but for different reasons. You want the wide breadth of knowledge so you can speak intelligently about patterns and know what terms to search for when you want to go deep. But many patterns have fairly specific uses, so there's no need for you to try and become an expert in all of them if you're not solving the kinds of problems for which some patterns are designed. I'm sure I'll have more tips about design patterns in upcoming shows, but one last reason why you owe it to yourself to gain at least a cursory knowledge of them is their value as a higher level language tool. When you know a design pattern by name, and how and why one would use it, you can discuss possible solutions with your team in a far more efficient and clear manner. The actual implementation of many patterns can involve several different types organized in a particular fashion, usually with specific inheritance or composition relationships. How these types are used by your system is another aspect of the pattern's implementation. Without knowing the pattern and its name, communicating a proposed solution to another developer would require describe at least most of this detail. However, if both developers are familiar with the pattern in question, one can simply say to the other, "have you thought about applying the XYZ pattern here?" and convey the same intent with less chance for confusion and with fewer words. If you want to learn more about design patterns, I recommend the Design Pattern Library on Pluralsight as a good place to start. You can also reach out to me if you think your team would benefit from a private workshop on design patterns. Show Resources and Links Design Patterns by Gamma, Helm, Johnson, Vlissides (Gang of Four) A Pattern Language by Christopher Alexander Design Patterns Library (Pluralsight)
undefined
Jan 29, 2018 • 5min

Becoming a T-Shaped Developer

Becoming a T-Shaped Developer It's difficult to differentiate yourself if you don't have a single area of expertise. Either you'll have difficulty landing work or you'll be forced to compete with a host of other non-specialists on rate. By becoming a T-shaped developer, you can market yourself as an expert in a particular area and stand out from the crowd! Sponsor - DevIQ Thanks to DevIQ for sponsoring this episode! Check out their list of available courses and how-to videos. Show Notes / Transcript In this episode, I'm going to talk about what it means to be a "T-Shaped" developer. But before we get into that, let's talk a little bit about how software developers typically market themselves, and how companies post job openings, using some real data and numbers. Let's consider a pretty common, but vague, job description: "web developer". Let's search for jobs using this term on a few different sites. We'll leave location out of the search - remote work is becoming increasingly acceptable and it's just easier to compare numbers if we don't restrict by location. Looking at Indeed.com, there are 40,000 jobs matching this search string. LinkedIn's Job Search has over 14,000. GlassDoor finds 110,000. Monster.com will only tell us there were over 1000 results found, but it's a good guess it was a lot more than 1000. The point is, there are a huge number of positions out there that match the search term (or exact job title) of 'web developer'. If you identify primarily as simply a 'web developer', you're in a crowd of hundreds of thousands. The good news is, there's definitely demand for people to fill that kind of role. The bad news is, how do you convince a particular client that you're the best candidate for their 'web developer' vacancy, if that's as far as you've gone in differentiating yourself? When you're marketing a product, one that isn't creating a brand new market segment, it can be useful to identify how big the market for that kind of product is. Say you're looking to enter the footwear business. It's good to know that there are billions of dollars spent by millions of customers on footwear every year. However, when you go to actually sell your footwear, you're probably not going to try to market it to "people who buy shoes" - you're going to niche down to a particular segment. Maybe basketball playing teens who aspire to be NBA players. Maybe outdoor fanatics who want the best hiking shoes. Maybe fashion-conscious women who will pay a premium for comfort. You'll sell more shoes by appealing to specific demographics of buyers than by trying to appeal broadly to any shoe-buyer. People can only remember one or two leaders in a given market niche, and as a marketer you want your product to occupy one of those positions. If you can't be the #1 or #2 for the market, you need to pick a smaller, more focused market in which you can occupy that position. Think about it for automobile companies. What's the most successful automobile company? In my opinion there's not even a clear winner here. What if we narrow it down to trucks? Many of you would probably say Ford or Chevrolet. How about electric cars? I would argue Tesla has done an excellent job of being first in mind as the electric car manufacturer, even though last year Nissan sold more electric vehicles globally than did Tesla. As a developer, you are the product you're trying to sell. You have a set of skills and experience that you can bring to bear when presented with a problem. There are a wide number of skills that most developers need to know, but don't need to be expert in. Visualize a horizontal line representing the breadth of skills you have. Now make the line thicker at the bottom by a few units to represent the relatively shallow depth of knowledge you have for most skills. You work with source control, but you're not known throughout the industry for your source control skills. You can apply CSS to HTML, but you're not writing books about how to apply CSS to HTML. You're competent with C#, or JavaScript, or PHP, but again you're not a well-known expert in them. Now think about a particular skill or passion you have that goes beyond mere competence. Maybe you could have a podcast all about your git knowledge and the dark arts of mastering its intricacies. Maybe you could write a book about the most powerful ways to use CSS selectors to achieve amazing results. Whole programming languages might be tough to become well-known for (think Jon Skeet for C# for example), but you could position yourself as the go-to expert in lambda expressions or arrow functions or a particular design pattern. Whatever skill you already have, or could have, that's where you're going to go deep with your knowledge. Visualize that thick horizontal line representing your shallow knowledge of a wide variety of topics, and now draw a much deeper vertical line dropping down from its center, forming a 'T' shape. This T-shape represents your skillset, or at least how you'd like to market your skillset. The T-shaped developer has greater success because they're able to position themselves in the minds of customers, managers, and peers as experts in a particular niche. How you choose your niche and how you make sure others are aware of your expertise will have to wait for future shows. Please leave a comment at weeklydevtips.com/016 if you have questions or ideas you'd like to share. Show Resources and Links Positioning - The Battle for Your Mind (book) Tesla vs Nissan Jon Skeet - C# More Career Advice Articles

The AI-powered Podcast Player

Save insights by tapping your headphones, chat with episodes, discover the best highlights - and more!
App store bannerPlay store banner
Get the app