DDD Building Blocks Dictionary

0

Category : ,

Ubiquitous language

- A common language to help communication between software developers and domain experts.

Invariant

- describes something that must be true with your design all the time.

Bounded Context

- A specific responsibility enforced by explicit boundaries. These boundaries are set by the different way we represent models. Different contexts may have completely different models of common concepts with mechanisms to map between them.
- A Bounded Context can be considered as a miniature application, containing it’s own Domain, own code and persistence mechanisms.
- Communication to and from a Bounded Context is done via a Context Map.

describe things in the domain model

Entity

- A unique thing that has a life cycle and can change state. For example, a conference in a conference management system will be an entity; many of its attributes could change over time (such as its status, size, and even name), but within the system each particular conference will have its own unique identity.

Value object

- Not all objects are defined by their identity. For some objects what is important are the values of their attributes.
- Sometimes in one context something is an entity while in another it is just a value object.

Services

- You cannot always model everything as an object.
- it may make sense to model a third-party payment processing system as a service. The system can pass the parameters required by the payment processing service and then receive a result back from the service.
- A service in a DDD domain model is not a web service. It communicates aggregate roots, performs complex use cases, cross aggregates transaction. An operation offered as an interface that stands alone in the model, with no encapsulated state.

Aggregate

- Whereas entities, value objects, and services are terms for the elements that DDD uses to describe things in the domain model, the terms aggregate and aggregate root relate specifically to the lifecycle and grouping of those elements.
- Aggregate is a cluster of domain objects that can be treated as a single unit to provide a specific functionality and for the purpose of data changes.
- Every aggregate has a unique ID; therefore, you can use that ID to record which aggregate in the system was the source of a particular event.
- In summary, aggregates are the mechanism that DDD uses to manage the complex set of relationships that typically exist between the many entities and value objects in a typical domain model.

Aggregate root

- An aggregate root (also known as a root entity) is the gatekeeper object for the aggregate. All access to the objects within the aggregate must occur through the aggregate root; external entities are only permitted to hold a reference to the aggregate root, and all invariants should be checked by the aggregate root.
- An aggregate root is an entity that composes other entities (as well as its own values) by composition. It is the domain’s only entry point for data access. A heart of your domain.
- Another area where there can be confusion is in distinguishing entities from aggregates. Every aggregate has an entity acting as its aggregate root, and for lots and lots of entities the aggregate will consist of just this entity. The point is that "Customer have Orders" does not mean imply aggregation; Customer, Order and Product are all aggregate roots.

Domain Event

- A Domain Event is something that happened in the past, and that is of interest to the business.
- Domain Events is an immutable array of Domain Event objects. Once they have been initialized, there's no way to change them, there are no setters. Because events happen in the past, they cannot be changed or undone. That makes perfect sense: History can't be altered!
- Events happen in the past. For example, "the speaker was booked," "the seat was reserved," "the cash was dispensed."
- Events can be processed multiple times, by multiple consumers.
- Here are sets of events we may come up with from the cafe tab scenario. TabOpened, DrinksOrdered, FoodOrdered, FoodCancelled, DrinksServed, FoodPrepared, FoodServed, TabClosed.

CQRS — Command-Query Responsibility Segregation

- A common sense rather than a pattern. CQRS just separates a model into two separate parts — READ model and WRITE model.
- They also can be referenced as Query model and Command model. Segregation must be clean so commands can’t return any data.
- A command is any method that mutates state and a query is any method that returns a value.
- CQRS is not a top-level architecture. CQRS is something that happens at a much lower level.

Commands

- Commands are imperatives; they are requests for the system to perform a task or action. For example, "book two places for conference X" or "allocate speaker Y to room Z." Commands are usually processed just once, by a single recipient.
- Commands are things that indicate requests to our domain.
- A command may be accepted or rejected.
- An accepted command leads to zero or more events being emitted to incorporate new facts into the system.
- A rejected command leads to some kind of exception.
- Commands are also identified by looking for verbs. For example OpenTab, PlaceOrder, MarkFoodServed, CloseTab etc. However, they are focused around what the user considers as an operation.

Exceptions

- An important part of the modeling process is thinking about the things that can cause a command to be refused. We are expected to model these "sad paths" into exception types, just as commands and events are expressed as DTOs.
- Looking to the cafe domain scenario, we can identify three notable exceptions we need in our model: CannotCancelServedItem, TabHasUnservedItems and MustPayEnough. The names here try to explain why the command failed.

Command Bus

- The idea of a command bus is that you create command objects that represent what you want your application to do. Then, you toss it into the bus and the bus makes sure that the command object gets to where it needs to go.
- So, the command goes in -> the bus hands it off to a handler -> and then the handler actually does the job. The command essentially represents a method call to your service layer.
- The Command Bus pattern relies on 3 types of classes:
Command (encapsulate our input, does simple validation on it)
CommandHandler (dedicated to a single Command, does the actual logic)
CommandBus (interface allowing us to build Middlewares that calls the appropriate CommandHandle for the given Command)

Query

— an interpreter, which is a structure of objects which can form itself into an SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way, those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.

Event Sourcing

- Event sourcing is a way of persisting your application's state by storing the history that determines the current state of your application. For example, a conference management system needs to track the number of completed bookings for a conference so it can check whether there are still seats available when someone tries to make a new booking.
- ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.

Repository

- mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
- A mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
- pretends to be a collection of Aggregate Roots.



https://developer-paradize.blogspot.com/2016/05/ddd-building-blocks-dictionary.html
https://blog.lelonek.me/ddd-building-blocks-for-ruby-developers-cdc6c25a80d2

Value Objects

0

Category :

It's often useful to represent things as a compound. A 2D coordinate consists of an x value and y value. An amount of money consists of a number and a currency. A date range consists of start and end dates, which themselves can be compounds of year, month, and day.

I run into the question of whether two compound objects are the same. Objects that are equal due to the value of their properties, in this case their x and y coordinates, are called value objects.

In some noon functional languages you will need to override the default equals method with the tests for the values.

One of the nice consequences of value objects is that I don't need to care about whether I have a reference to the same object in memory or a different reference with an equal value.

Aliasing Bug

To avoid aliasing bugs I follow a simple but important rule: value objects should be immutable. If I want to change my object, I create a new object instead. With objects I can usually do this by simply not providing any setting methods.


my thanks to:
https://martinfowler.com/bliki/ValueObject.html

.Net Debugging Tips

0

Category :

Tip 1: Use object exporter

During debugging, it’s often necessary to inspect the current object instances. if you’re working with arrays, this becomes tedious very quickly.

Oftentimes, it’s necessary to find a specific set of elements in the array. Object Exporter is for. It’s a Visual Studio extension, and you can install it manually from the Visual Studio Marketplace. Or you can install it from within Visual Studio via Tools -> Extensions and Updates. Please make sure that you select Online in the tree view to the left before you search for the extension.

It can export an object in different formats, namely JSON, XML, and C#. It’s also possible to export custom expressions. This is very helpful if you just want to export a subtree of an object graph.

Tip 2: Use ,nse to evaluate an expression without side effects

During debugging, you need to evaluate expressions all the time. As long as these expressions don’t change the state of the system, all is fine.

However, oftentimes, evaluating an expression causes a side effect.

For example, if you’re evaluating a property with lazy initialization, it’ll actually initialize that property in the context of the debugged code. This can lead to strange problems during debugging.

So if you want to watch o.MyProperty, add the following to the Watch window:

o.MyProperty, nse

This will execute the expression in a special sandbox, preventing any changes to the state of the debugged application.

Tip 3: Freeze multithreaded applications

Debugging multi-threaded applications can be a real pain, especially if multiple threads are executing the same code. Breakpoints will be hit by each thread, and single-stepping will switch between threads. It’s very easy to lose orientation and concentration like this. Wouldn’t it be great if it were possible to tell Visual Studio that you want to debug just this one thread and not switch to other threads that are currently executing the same code?

Well, turns out, there is a way to do this.

Open the Threads window via Debug -> Windows -> Threads. This window shows all threads of the current application. Double-clicking a thread switches to it. Right-clicking a thread shows different options, one of which is Freeze:

Threads window to freeze all threads for the current location except one. You can now debug this one thread and single-step through the code without thread switches interrupting your concentration. You can also set breakpoints and be sure they’ll be hit for the correct thread.

If you want to continue running the program after you’ve debugged the code in the thread, you should unfreeze—or Thaw—the other threads so they can perform their work as well.

Tip 4: Use Object ID

Object IDs are a feature of the Visual Studio Debugger that has several helpful use cases.

One such use case is that object IDs basically allow you to make a certain object instance globally available during debugging. This lets you compare it to other instances at a code location where the instance wouldn’t be available otherwise.

Another use case is to compare object identities. Imagine a scenario where you’re debugging an app that uses a dependency injection container. This app contains two classes that are receiving an instance of a service class via their constructors. The service instance resembles the way by which the two classes can communicate with each other. However, this coordination doesn’t work for some reason. One reason for this issue could be that the two classes aren’t receiving the same instance of the service class.

Object ID can easily identify this issue.

To use it, add a breakpoint at the constructors of the two classes. When the breakpoint gets hit in the first class, right-click the service instance in the Locals window and choose Make Object ID. When the breakpoint in the second class gets hit, check if the instance shows the object ID. If so, they’re the exact same instance.

Tip 5: Make sure you’re getting stack traces

When you catch an exception and rethrow it, never ever use throw ex;. Instead, use throw; . The first variant loses the original stack trace and therefore masks the original error location.





my thanks to this great article:
https://raygun.com/blog/dot-net-debugging/

Delegates and their flavours

0

Category :

Delegate Types

A delegate is simply a reference to a method. Delegates can be stored and passed around in a variable, and hence they must have a type definition:
private delegate int FuncTwoInts(int one, int two);

The line above defines the type FuncTwoInts. The FuncTwoInts type is a reference to a method that takes two int parameters and returns a single int result.

Delegate expressions

The FuncTwoInts type can be used to declare variables like this:
private static int Add(int one, int two)
{
    return one + two;
}

private FuncTwoInts theFunc = Add;
Or like this:
FuncTwoInts theFunc = delegate (int one, int two)
{
    return one + two;
};
Or this:
FuncTwoInts theFunc = (one, two) =>
{
    return one + two;
};
Or even like this:
FuncTwoInts theFunc = (one, two) => one + two;

Lambda expressions

The last two delegate examples above (the ones utilizing the => operator) are called lambda expressions. Lambda expressions are just a more efficient way of defining a delegate. If the function defined by the lambda expression is more than a single line, then the { } are required, as is the return keyword.

Built-in delegate types

There is a family of built-in delegate types that can be used to declare delegate variables without the need to define a custom type.

Action

The types that represent a delegate without a return value (void return) are the Action types in the System namespace.
private Action supFunction = () => Console.WriteLine("Sup?!");
Here's an example of a delegate that takes three parameters of different types:
private Action<string, int, bool> printThreeValues =
    (s, i, b) => Console.WriteLine($"string: {s}, int: {i}, bool: {b}");

Func

The Func family of delegate types can return a value of any type you wish. For example: Func<TResult> for no params and TResult return type.
private Func twoPlusThree = () => 2 + 3;
Func<T1, T2, TResult> for two parameters and TResult return type. Here is an example of a delegate declaration that takes two string parameters and returns an int:
private Func<string, string, int> sumCharacters = 
    (s1, s2) => s1.Length + s2.Length;


my thanks to this course:
https://www.codingame.com/playgrounds/345/c-linq-background-topics/review

Read Code

0

Category : ,

If you woke up one day resolved to be a great writer, you’d hear two simple pieces of feedback: write a lot, and read a lot.

In software, nearly everyone falls short on the latter. Early in your career, embrace reading code. Read widely and read often.

Why read code?

Great writers are a function of the writers they’ve read. Similarly, seeing diverse coding practices lets you expand your own palette when it comes time to write your own code. It exposes you to new language functionality, different coding styles, and important dependencies.

Reading your dependencies will make you a more productive programmer. You’ll know what the full functionality your dependencies offer. You’ll know exactly how they work and what tradeoffs they’re making. You’ll know where to debug when things go wrong.

Being comfortable reading code reduces the likelihood that you’ll have a “not invented here” mindset. The more you read, the more comfortable you’ll feel depending or augmenting someone else’s code, rather than building your own.

Cultivating regular reading will teach you tools and products widely different from your day to day work.

As a web engineer, reading a small part of a raytracer’s codebase will expose you to a wholly different set of constraints and user needs.

The more you read, the less scary it’ll be. Developing a strategy to read code then becomes a virtuous cycle.

How to “read” code?

Approaching a codebase like you would a book— reading from start to end—is a recipe for failure. Any medium-sized codebase is impossible to read linearly. Instead, “reading” code requires a substantial amount of active work.

I use this four-party strategy for approaching any complex code base (RSDW for short):

  1) Run: compile, run, and understand what the code is supposed to do

  2) Structure: Learn high level structure and review key integration tests

  3) Deep Dives: Follow key flows and read important data structures

  4) Write: Write tests and prioritize simple features and bug fixes

When you’re starting to read, be humble. A common mistake for early engineers is to weigh their code as “good” and that of others as “bad.” Instead, have some empathy for the styles of others and the uneven process that leads to the birth of most new software systems.

As a new developer, when you notice missing things, especially documentation and poor test coverage, help out. This is an exceptional way to learn, and will endear you to the others who develop the codebase, whose support will speed up your journey to learn a new codebase.

Second, reading new code is exhausting. You are intricately retracing code flows and trying to hold tens of new data structures and functions in your head concurrently. Be aggressive about taking breaks when you’re approaching a new code base. When I’m starting on a new complex codebase, a few good hours of reading is all I need to feel productive for the rest of the day.

With the right frame of mind, it’s much easier to go through the active process of digesting new code.

1) Run

The first step in reading code, isn’t to read code. It is to use the software.

Do not read code without understanding exactly what the software does and what functionality it offers. During this stage of reading, you should be able to make a summary of the code and have an understanding what the inputs and outputs could be.

Using the software forces you to get it to run. This means compiling the code (in some languages) and pulling down the dependencies. This is also the time to run the tests and review the output messages. If you have trouble getting the system running, this is the perfect time to document what it actually takes to compile and run the software.

2) Structure

Next, identify the most critical parts of the code. This is the part that is most different from reading a book. Instead of beginning at the beginning, you identify the key nexuses in the code.

Start with understand the structure of the code. At minimal, use tree | less and cloc to figure out the languages and files of the codebase.

To identify the most important files, look at the most modified files (git log --pretty=format: -name-only | sort | uniq -c | sort -rg | head -10[2]) and use other advanced tools. Review the most important integration tests, listing out the functions that are called. Flag these tests for later.

There’s a cheat code for this process too: find someone who’s worked on the code before. understanding the structure is a good first task for a whiteboarding session.

3) Deep Dives

Once you have a lay of the land, dig in.

Programming languages revolve around two fundamental paradigms: functional (when actions are primary) and objects (when objects are primary). Similarly, when reading code, you should look at code flows (seeing the actions that are being created) and look at data structures (where the results of actions are stored).

Pick 3-5 few critical flows you’ve found from key integration tests or your review of the source files. Then dive deeper. Start at the top of a specific action and trace the code through. Some developers swear by debuggers that let you step through. Others prefer building UML diagrams or flamegraphs. If you decide to manually follow the code, make sure your editors is setup to let you use “go to definition” and “find all references” for quick navigation.

For data structures, review the data types and when key variables are being set. Use the debugger to interrogate these data structures at critical moments.

I also keep two markdown docs open for these deep dives. The first is a “level up my coding” doc where I list out new syntax I’m seeing and code patterns I find interesting for my own learning (others call this a glossary). This allows me to return for further investigation. The second is a doc that lists out key questions I have for the developers of the codebase. At this stage, I also add to the documentation when I notice gaps.

Deep dives are especially powerful in pairs with someone who knows the code. If I have limited time with a developer on the project, I always have them trace me through a few key flows.

4) Write Code

Unlike passive reading in literature, a critical part of “reading” code is writing code. The two easy ways to “read” is to write tests and address simple features/ bugs.

Writing tests is an active form of reading, forcing you to pay attention to the actual inputs and outputs of a particular interaction.

Writing tests is when you realize that you’re still missing important details. Writing tests imprints the code in your memory in a way that reading alone cannot. Unit tests are an easy way to start, and once I have some base mastery, I move over to integration tests that force me to understand increasingly larger parts of the codebase.

The other easy way to write early code is to write simple features or address easy bugs. Both these tasks don’t demand complete knowledge of the codebase, but force you to confront the code. They also provide quick wins that increases your confidence and motivation.

What code to read?

Early in your career, 60% of your time should be spent reading code. Maybe half of that should be code outside of the direct codebases you actually build on top of. That’s an awfully large amount of time to fill, so what should you read?

The easiest way to get started reading and the highest ROI is to learn your dependencies. Internalizing how your dependencies work lets you more easily debug and reason across your entire system.

The other high ROI path is to pick an important system at your company that you interface with, and read through it. Not only will this be valuable in your work, but professional codebases are different from open source codebases. They are written closest to how your team’s engineers feel is the “right” way.

Beyond the direct systems you interact with, cultivate an openness to reading widely. Early on in my career, I recommend putting aside an hour in the morning or evening to read through code outside your day to day work.

To start, pick a few easily understood codebases. Redis is known as a popular starting point in C. Famed codebases — say reading Vim — are more complicated with lots of nuance, but an easy way to start is to read a specific subsystem.

Try to actively read tools widely different from your day job. If you’re used to high level abstractions, learn an abstraction level (or three) down. If you work in one language, pick another language to read in your free time.

Find coders you respect or want to mimic and follow them on Github. Read a few of their other codebases. Stay up to date of their most recent work.

Create a reading group, a code club. In Stockholm, I heard great things about “The Classical Code Reading Group of Stockholm,” where they read classic codebases (I used to join at an affiliate run by Thoughtbot in NYC).

When you first start reading code, uour focus is not simply to learn a codebase, but to develop a mindset that will pay long term dividends.

Links

Articles on reading code

  Ask HN: How do you familiarize yourself with a new codebase

  Ask HN: How to understand the large codebase of an open source project?

  Strategies to quickly become productive in an unfamiliar codebase

  What's the best way to become familiar with a large codebase?

  Tips for Reading Code

  Software Engineering Radio: Software Archaeology with Dave Thomas (Podcast)

Books

  Code Reading: The Open Source Perspective

(book)

  Working Effectively with Legacy Code (book)

Codebases to read

  Good Python codebases to read

  Good Go codebases to read



Source

this article is taken from a post on a forum which can be found here
https://news.ycombinator.com/item?id=19431874 https://hackernoon.com/one-secret-to-becoming-a-great-software-engineer-read-code-467e31f243b0

ASP.NET Core 2.0 Authentication and Authorization Overview

0

Category :

ClaimsPrincipal represents a user (is what the HttpContext.SignInAsync method accepts and passes to the specified AuthenticationHandler.) and contains one or more instances of

ClaimsIdentity which in turn represent a single form of identification and contain one or more instances of

Claim, which represents a single piece of information about a user.

Authentication handlers are components that actually implement the behavior of the 5 verbs above. The default auth handler provided by ASP.NET Core is the Cookies authentication handler

Authentication Middleware is a module that can be inserted into the startup sequence and is run on every request. When the request is run, the authentication middleware asks the default scheme auth handler to run its authentication code.

my thanks to this article:
https://digitalmccullough.com/posts/aspnetcore-auth-system-demystified.html

ASP.NET Core Developer Roadmap

0

Category :

my thanks to this great repo:
https://github.com/MoienTajik/AspNetCore-Developer-Roadmap