Strongly Type Entity Identifiers - c#

When working with service oriented applications we often use system types to identify / query our business entities.
IList<Product> GetProductsByUserAndCategoryId(int userId, int categoryId);
However we can't prevent developpers to pass another identifier which is not a "User Identifier" and not a "Category Identifier", or maybe inverse the ids on method call.
So a solution is to use Strongly Type Identifiers, like this :
IList<Product> GetProductsByUserAndCategoryId(UserId userId, CategoryId categoryId);
GetProductsByUserAndCategoryId(new UserId(123), new CategoryId(456));
What do you think about this ? Pros and cons ?

Pros and cons ?
Well, first off, this only shifts the moment of validation; it still has to happen, preferably as soon as a UserId (…) is instantiated. You also have to see whether this really has any benefits in your system at all.
On the other hand, I do think that it prevents bugs by disambiguating between inherently ambiguous numbers. Letting the same type int stand for two completely unrelated things can actually be dangerous.
In a recent code review (for a course at University) the no. 1 error students had made was to use an integer in the wrong way. Having used different types as in your example would effectively have prevented this source of errors altogether.
So, in summary, I don’t think there’s a blanked answer but I am generally in favour of such idioms. This is one of the real benefits of a strict type system.

The only real con for me is having to type extra code. You code becomes more tightly defined, which is a good thing, but now there is extra friction to actually getting it written. It is just a matter of will spending the extra time and effort up front pay off in saved maintenance and dependability later.
It is the same with any methodology. The TDD guys spend time building scaffolding and tests up front with the hope it will make there code more reliable and more easily maintainable. -- Many of them say it saves time upfront as well...but I have my doubts :) --
Ultimately I agree with Mr. Rudolph. This is the strength of strict type systems; Use it to your advantage.

Related

Questions on Juval Lowy's IDesign C# Coding Standard [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
We are trying to use the IDesign C# Coding standard. Unfortunately, I found no comprehensive document to explain all the rules that it gives, and also his book does not always help.
Here are the open questions that remain for me (from chapter 2, Coding Practices):
No. 26: Avoid providing explicit values for enums unless they are integer powers of 2
No. 34: Always explicitly initialize an array of reference types using a for loop
No. 50: Avoid events as interface members
No. 52: Expose interfaces on class hierarchies
No. 73: Do not define method-specific constraints in interfaces
No. 74: Do not define constraints in delegates
Here's what I think about those:
I thought that providing explicit values would be especially useful when adding new enum members at a later point in time. If these members are added between other already existing members, I would provide explicit values to make sure the integer representation of existing members does not change.
No idea why I would want to do this. I'd say this totally depends on the logic of my program.
I see that there is alternative option of providing "Sink interfaces" (simply providing already all "OnXxxHappened" methods), but what is the reason to prefer one over the other?
Unsure what he means here: Could this mean "When implementing an interface explicitly in a non-sealed class, consider providing the implementation in a protected virtual method that can be overridden"? (see Programming .NET Components 2nd Edition, end of chapter “Interfaces and Class Hierarchies”).
I suppose this is about providing a "where" clause when using generics, but why is this bad on an interface?
I suppose this is about providing a "where" clause when using generics, but why is this bad on a delegate?
Ok so I will basically chip in with the little rep I have on stackoverflow: You can all kill me for opening a religious debate.
The hint to working with Juval's code standard is really in it's preface:
"I believe that while fully understanding every insight that goes into a particular programming decision may require reading books and even years of experience, applying the standard should not."
Next hint is to read his work.
Next would be doing what he advices.
Maybe on the way understand why he is recognised as a "microsoft software legend".
The next might be that it is delivered in a read-only pdf.
That didnt satisfy you?
The key here is realizing this is not a religious narrative, it is indeed a pragmatic one.
My personal experience with his standard is pretty much:
If you follow the advices as best you can, you will get a productive outcome.
Your needs of refactoring will be less, you productivity in the later cycles of the project will be higher.
This is an experience based evaluation.
Basically what you are looking for are the answers to "why" certain portions of the coding standard is in there, specifically these: 26, 34, 50, 52, 73, 74
You are asking these questions from a pragmatic perspective: You want to incorporate the standard and you "somehow" know this will give you a benefit in the longer run.
By examining these rules, through experience, you will perhaps come to understand why they are indeed there. Experience is here doing and not doing your code in accordance with the principles.
But really that isnt the point. The point is that by working from the basis of a well considered, mature and reliable standard, your work now becomes work of quality.
On how to follow a standard
Really read the rules as advices, they are already very strictly worded: "Avoid, do not, do and so on" really means what they say. Avoid means "think really hard before breaking the principle". "Do not" really means "do not".
Juval is all about decoupling and most of his harder-to-grok advices really comes from not thinking "separation" into your code design.
Sometimes this is hard to do with a team that works in less abstract terms or in more feature oriented environments, and you can therefore sometimes find it necessary to break rules, "to get the team moving", but you really should refactor this to the standard when you can do so.
After a few years, a few projects more, you perhaps will come to understand the rationale for each and every rule in the simple guide. If you are a bright student. Me, I'm not so bright, so I base it on experience: Stuff that is in the non-standardized parts of the code often fails during integration testing. It is often harder to come back to. It often ties poorly to the environment and so on.
It really is a matter of trust. If you cant find it in yourself to trust this (not adopt it - trust it), standard, I will propose to you that you will find it hard to ever really write comprehensible c# code that is generally of a acceptable quality.
This of course not considering the few really smart and really experienced out there that managed to build up their own set of internalizable rule sets on how to write code that is:
Stable, readable, maintainable, extendable and generally mega-ble.
This not saying that this is the only standard, just that it do indeed work. Also over time.
You will be able to find other standards, most if not all, though sub-standard to this for working with code you "really want to work" in the long run, involving a team of developers and changing real time situations.
So consider your standard, it is really setting the bar for the quality you provide for the $ you earn.
Do not reconsider it, unless you have "real good reasons to".
But do learn from it.
You reached here and you are still not satisfied. You want answers!
Darn it. Ok let me give you my clouded and sub-par experience based view on the rules your team can't grok.
No. 26: Avoid providing explicit values for enums unless they are integer powers of 2
Its about simplicity and working within that simplicity.
Enum's in c# are already numbered from "i=0" and injecting "++i" for every new field you define. The simplest way to [read code with/] think about enums are therefore either you flag them or you enumerate them.
When you dont do this, you are probably doing something wrong.
If you use the enum to "map" some other domain model, this rule can be broken, but the enum should be visibily separated from normal enums through placement/namespace/etc - to indicate you are "doing something not ordinary".
Now look at the enums you have created out-of-standard. Really look at them. Probably they are mapping something that really do not belong in a hard-coded enum at all. You wanted the efficiency of a switch, but you have in actuality now begun to hardcode out-of-domain properties. Sometimes this is ok and can be refactored later, sometimes it is not.
So avoid it.
The argument of "inserting into the middle" in the development process, is not really an issue that should break the standard. Why? Well if you are using or in any way storing the "int value" of the enumeration, then you are already diverging into a usage pattern where you need to stay very focused indeed. Not using 0, 1, 2 is not the answer to problems in that particular domain, i.e you are probably "doing it wrong".
The EF code-first argument is, probably not an issue to circumvent the rule here. If you feel you have such a need, please do describe your situation in a separate thread and I will try to guide you how to both follow the standard and work with your persistance framework.
My initial take would be: If they are code-first poco entities, then let them abide by the code standard, After all your team have decided to work with a code-first view on the data model. Allow them to do just that, following the same semantics as the rest of their code base.
If you run into specific problems related to the mapping to database tables, then solve these problems while maintaining the standard. For EF 4.3 I would say use the get/set with int pattern and replace in 5.0.
The real gritty stuff here is how to maintain this entity as the database evolves. Be sure to provide clear migration paths for your production database when your enum containing entities change design. Be very sure if the entities themselves change values. This go for add/remove/insert of new definitions. Not just add.
No. 34: Always explicitly initialize an array of reference types using a for loop
My guess is this is an "experience based" rule. In such a way that he looked through a lot of code and this point seemed to fail often for those that did not do it.
No. 50: Avoid events as interface members
Basically a question of separation - your interfaces are now coupled "both" ways into the interface and out of it. Read his book for clarification on why that is not "best practice" in the c# world.
In my limited view this is probably argumentation along the lines of: "Call-backs are very different in nature from function-calls. they make assumptions on the state of the receiver at an undefined "later time" of execution. If you want to provide callbacks, by all means do provide them, but make them into separate interfaces and also define an interface to negotiate these callbacks, in effect establishing all the hard things you wanted to abstract away, but really just circumvented. Or probably just use a recognized pattern. aka read the book."
No. 52: Expose interfaces on class hierarchies
Separation. I cant really explain it any further than: The alternative is hard to factor into a larger context/solution.
No. 73: Do not define method-specific constraints in interfaces
Separation. same as #52
No. 74: Do not define constraints in delegates
Separation.
Conclusion
......
Another view on #50 is that it is one of those rules where:
If you dont get it, its probably not important for you.
Importance here is an estimate on how critical the code is - and how critically you want that code to always work as intended.
This again leads into a broader context on how to verify your code actually is quality.
Some would say this can be done with tests only.
They however fail to understand the interconnectedness between defensively writing quality software and aggressively trying to prove it wrong.
In the real world, those two should be parts of a greater totality with the actual requirements of the software being the third.
Doing a quick mock-up? who cares. Doing a little visual thingy that you understand the runtime constraints of? who cares - well probably you should, but perhaps acceptable. and so on.
In the end compliance to a coding standard is not something you take on lightly.
There are reasons for doing it that goes beyond just the code:
Collaboration and communication primarily.
Agreement on shared views.
Assertions of assumptions.
etc.
No. 26: Power of two means you want to use the enum as a bitmask (flags). Thats the only reason to specify enum values. For adding new members later on, you can still append them to the enum definition without changing existing values. No reason to put them between existing members.
No. 34: I think he wants to avoid the situation where you have an array wich contains (partially) uninitialized pointers (null references). As the consumer of an array its tempting
not to check for null entries in a valid array variable.
No. 26: He's quite wrong, at least for public enums. The problem crops up when you remove an item, not when you add one (for which adding to the end of the list would be equivalent to adding an item with the next available value).
For the others, I'm really not sure why he's making these recommendations, although I have to admit that I find a few (or maybe most) of them rather dubious...

What is preferable: an Enum or a singleton

I have the folowing question:
What is the prefered way to use the status in code, an enum OR singleton?
I have in a DB stored the status values with their ID's. If the status changes in de DB is would also need some changes in the code.
does anyone now what is more prefered, based on conventions?
I've been looking on the internet but couldn't find a clear answer.
It depends in part on whether the ids for your statuses have guaranteed values, or whether the ids could change per-database (via an IDENTITY). Personally, for statuses I prefer fixed - which gives you the most flexibility, and least overhead - you can choose to use an enum (or maybe some consts if more convenient), and you never have to add an indirection, i.e. "get the id that is open".
This isn't always possible, though, and when it isn't it is still definitely useful to cache and re-use them (to avoid hitting the DB for that lookup). However, I would avoid a singleton, not least because it won't play nicely if you ever need to talk to more than one database - the ids in each could well be different. However, any suitable cache implementation (or maybe IoC/DI) should allow you to store the appropriate data (probably some kind of dictionary). Singletons are also just a bit of a pain generally if you like testing etc.
But: an enum and fixed id values is a lot simpler.
Note that under any implementation, changing the status list is a non-trivial operation, not least it will be a big UPDATE (or several if you are denormalized).
If you intend to use the Status across the application and is standardised across then it would be best fit for an Enum
Enum Status
{Open, Pending, Closed, Deferred}
Also this makes the code more readable

Where are order IDs allocated?

Sorry for the naive question; I'm still working through understanding DDD. Let's say I have an IOrderService. Is this where I would have a method GetNewOrderID? Or, I guess more generally, what is the right way to allocate new orders in a DDD scenario?
Unless I've misunderstood DDD then it's not a naive question - instead when it's not clear where the responsibility then not enough of the domain has been investigated / understood. Things like:
What is the format of the Order ID,
what information goes into a single
OrderID.
Is there a requirement to
save anything at the point of getting
a new OrderID - like who requested
it, etc.
Is there a requirement
that requested, but unused Order IDs
be freed up?
One or more of these requirements might clarify the situation.
I like to listen to the words that the business use. If they talk about, for instance, catalogue orders and phone orders both being sources of orders, I might have an OrderSource or IOrderSource instead of an OrderService - the last is code-speak instead of business-speak. I might have two implementations, or just one which uses an identifier to say "this is from a phone", depending on how different the processes are.
If the business people talk about getting IDs from their service, then yes, do that. It's more likely though that they talk about receiving an order from an OrderSource, dispatching it to the Warehouse or creating an OrderForm and receiving a ReferenceNumber. That ReferenceNumber may well be the primary key, but it's probably not an Id.
The language that the business use can guide you to write software which matches their process well. Keeps things easy to change and helps you spot if there's an aspect of the domain which could use some learning. The design patterns are all the same that you're used to; I just don't call my code after those if the business have some better terms. See DDD's Ubiquitous Language, and good luck!

Effects of variable scope on performance? (C#)

Assume that we have 3 classes:
Place, Contact, PhoneNumber classes.
Under the Place class, I want to have a Contact class but it is better to keep PhoneNumber class under the Contact class. So in the Place class, it is more logical to reach the PhoneNumber by first getting the Contact object, then the PhoneNumber under the Contact object.
If I often need to get the PhoneNumber object from a place object, does keeping the PhoneNumber class under the Contact class (Place.Contact.PhoneNumber) instead of directly insert that object under the Place (Place.Contact) class cause any performance issues?
Why I ask this question is that these kind of scope issues have lots of performance effects in JavaScript. Does it worth to be so paranoiac about variable scope - performance relations in C#?
Thank you.
In C# you won't see many performance issues around trivial* property getters and setters like this. However, without profiling, it is impossible to say if this will be a problem for you.
For most cases though, object graph constructions never create performance problems in C# like they can in JavaScript.
* Properties that simply return a reference to an existing object and have no additional logic.
It will have an effect on performance, but won't cause issues. The just-in-time compiler compiles member accesses into direct pointer computations (having computed the layout of each class when the assembly was loaded), so member access is much faster in C# than it is in JavaScript.
Unless this is the absolutely last stop on your list of things to try in order to make your program run slightly faster, and by "slightly" I actually mean "minuscule" in this case, then I would not worry about it.
To answer your question first, yes, this might impact code performance. The code to read ref.ref.prop will take slightly more code to do than ref.prop, obviously.
However, this will make very small impacts on code performance, and unless you're reading this property 2 levels down many many times in a loop, and doing not much else useful, the effect of having 1 or 2 levels on this particular scenario will be dwarfed by any other code you might be executing.
In any case, the general rule is to write the code the most obvious way, the most simple way, and the most understandable way, so that it is first and foremost easy to write and easy to maintain, which in the long term will lead to fewer bugs.
At some point, if your program has a performance problem, and you find out that this particular code is the piece of code that is taking the most time, at that moment, then, and only then, do you go in and try to optimize that code.

Is AspectF (a Fluent Aspect Framework) an AOP-like design that can be used without much concern?

Omar Al Zabir is looking for "a simpler way to do AOP style coding".
He created a framework called AspectF, which is "a fluent and simple way to add Aspects to your code".
It is not true AOP, because it doesn't do any compile time or runtime weaving, but does it accomplish the same goals as AOP?
Here's an example of AspectF usage:
public void InsertCustomerTheEasyWay(string firstName, string lastName, int age,
Dictionary<string, string> attributes)
{
AspectF.Define
.Log(Logger.Writer, "Inserting customer the easy way")
.HowLong(Logger.Writer, "Starting customer insert", "Inserted customer in {1} seconds")
.Retry()
.Do(() =>
{
CustomerData data = new CustomerData();
data.Insert(firstName, lastName, age, attributes);
});
}
Here are some posts by the author that further clarify the aim of AspectF:
AspectF fluent way to put Aspects into your code for separation of concern (Blog)
AspectF (google code)
AspectF Fluent Way to Add Aspects for Cleaner Maintainable Code (CodeProject)
According to the author, I gather that AspectF is not designed so much as an AOP replacement, but a way to achieve "separation of concern and keep code nice and clean".
Some thoughts/questions:
Any thoughts on using this style of coding as project grows?
Is it a scalable architecture?
performance concerns?
How does maintainability compare against a true AOP solution?
I don't mean to bash the project, but
IMHO this is abusing AOP. Aspects are not suitable for everything, and used like this it only hampers readability.
Moreover, I think this misses one of the main points of AOP, which is being able to add/remove/redefine aspects without touching the underlying code.
Aspects should be defined outside of the affected code in order to make them truly cross-cutting concerns. In AspectF's case, the aspects are embedded in the affected code, which violates SoC/SRP.
Performance-wise there is no penalty (or it's negligible) because there is no runtime IL manipulation, just as explained in the codeproject article. However, I've never had any perf problems with Castle DynamicProxy.
On a recent project, it was recommended to me that I give AspectF a try.
I took to heart the idea of laying all the concerns up front, and having the code that does the real work blissfully unaware of all the checks and balances that happened outside of it.
I actually took it a little further, and added a security "concern" that required credentials that were being received as part of a WCF request. It went off to the database and did what it had to. I did obvious validations, and the security check before running the actual code that would return the required data.
I found this approach quite a refreshing change, and I certainly liked that I had the source of AspectF to walk through as I was debugging and testing the service calls.
In the office, some argued that these concerns should be implemented as a decoration on a class / method. But it doesn't really matter where you decorate it, at some point somewhere, you need to say you wish to perform certain actions / checks. I like the fact that it's all laid out in-place, not as another code file, not as some kind of configuration file, and for once, not adding yet another decoration to a class / method.
I'm not saying it's true AOP - and I certainly think there are solutions and situations where it really isn't the best way of implementing your objectives, but given that it's just a couple of K of source files, that makes for a very light-weight implementation.
AspectF is basically a very clever way of chaining delegates together.
I don't think every developer is going to look at the code and say how wonderful it is to look at, indeed in our office it confused some of us! But once you understand what's going on, it's an inexpensive way of achieving much of what can be done by other approaches too.

Categories