Override == (equality) operator in NHibernate? - nhibernate

With NHibernate entities, you are meant to override Equals and GetHashCode. Is it a good idea to override the == operator to use the .Equals implementation also?

Yes, it is a more general .NET "best practice" to keep Equals(), operator== and GethasCode() consistent.
See Guidelines for Overloading Equals() and Operator == .

Why do you believe you need to override Equals and GetHashCode when using NHibernate? NHibernate guarantees entity equality for any entity accessed in the same ISession. See Considering object identity in the documentation.
Edited to add:
After re-reading the question and doing some googling, I have to admit I had no idea that the equality operator (==) could be overridden in C#.

Related

Should I use properties in interface in Kotlin?

I'm learning Kotlin and coming from Java world I find idea of properties in interfaces quite peculiar.
What's the general consensus on properties in interfaces?
Is it considered a good practice to have them?
I've seen few discussions on the related topic but for C# but none on Kotlin.
Properties in Kotlin are a shorthand to Java Beans naming convention, a read-only property is the same as a getter, a writeable property is a pair of getter and setter. You may use properties for Java getters and settings on Kotlin too. Same applies both to classes and interfaces.
Properties have shorted syntax and improve readability
Delegated properties in Kotlin helps to build come up with short and powerful code, e.g. val lazyCompoutedVariable by lazy { computeIt() }
Properties are likely to be cheap to call, the same code style is used, for example in C#
You may find more information on that in the documentation
https://kotlinlang.org/docs/reference/properties.html
They are used in the standard library, e.g. CharSequence#length, Collection#size are just the first ones I've thought of. If the alternative is forcing them to be getLength()/getSize(), this seems obviously bad.
Do you remove String#length? Do you implement length for every implementation of CharSequence separately? Do you make length an extension property
val CharSequence.length get() = this.getLength()
? Only the last one seems remotely acceptable.
Or you can just have val length in CharSequence and no problems :)

Any Mapping using Fluent NHibernate

Nhibernate documentation specfies ReferenceAny() as a method to do the mapping inheritance trees.
Check doc here. However the code specifies the method as deprecated and will be removed in the next versions. Is there any other way to map this.
Only the ReferencesAny<TOther>(Member property) overload has been deprecated. ReferencesAny<TOther>(Expression<Func<T,TOther>> memberExpression) is still perfectly valid.
It's the same type of confusion as when people claim that Enum.ToString has been deprecated. The overloads that take an IFormatProvider have been deprecated, but the other ToString overloads are fine. The problem is that Intellisense shows the member stricken-out, even though only a subset of its overloads are actually obsolete.
For more information on using ReferencesAny in Fluent NHibernate, see my other answer: Mapping to multiple tables with Fluent nHibernate

Fluent nHibernate, ToManyBase, Generic usage

I have discovered the method T Generic() in the abstract class ToManyBase<T, TChild, TRelationshipAttributes> but I cannot find any documentation or examples of how this is used, or what it does. Can anyone enlighten me a bit?
Nothing of significance.
It's the equivalent of the NHibernate generic= attribute, which is simply away of explicitly specifying that a collection is a generic one. A holdover from NHibernate's pre-generic days.

NHibernate and making an abstract entity base class

I saw in some NHibernate examples that an abstract base entity class is used, which has overridden Equals , GetHashCode , to handle transient entities , proxy object (in lazy loading scenario .. I guess) .
Is it really necessary to implement such an abstract base entity class to derive all my entities ?
Not necessary at all. It just makes things easier because you can put things like the Id on it. As well common functionality like you previously mentioned like Equals/GetHashCode.
Yeah, the base class itself is not required,but overriding Equals and GetHashcode is something you'll want to do on all your entities, so the base class makes thAt a lot less repetetive
In my experience, having a base class that exposes an Id property is really useful to be able to create generic repository methods that take advantage of that, or for automatic mapping conventions.
Overriding Equals, however, is another story.
Doing so forces loading of uninitialized proxies when you compare them (for example, by calling Distinct on a sequence). For that reason, it's better done only for class hierarchies of seldom-changing entities that are likely to be cached.
Overridding Equals is definetely required if you want to do lazy loading.
This is because NHibernate relies on the Equals method to determine equality. The default is reference equality.
When NHibernate implements lazy loading, it uses proxy objects, which are subclasses of the real entity class, with every member overridden to enable lazy loading.
Hence for your application to recognise that a proxy object is the same as the object it is meant to be the real instance - it shouldn't be aware of the proxy object at all.
So you must override the Equals operator to intelligently recognise equality (after checking reference equality ... etc) that objects are equal if their IDs are equal.

Fluent interfaces and leaky abstractions

What is a fluent interface? I can't find a good definition of this, but all I get are long code examples in a language I am not very familiar with (e.g. C++).
Also, what is a leaky abstraction?
Thanks
A fluent interface is an API that allows you to write code that reads more or less like normal English. For example:
Find.All.Questions(Where.IsAnswered == true);
Method-chaining is usually used as part of the implementation, but there is more to it than that. To quote Fowler:
I've also noticed a common misconception - many people seem to equate fluent interfaces with Method Chaining. Certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that.
It is also often called an internal DSL, since the syntax resembles that of a DSL, but it is implemented inside the host language instead of being processed by a parser.
A leaky abstraction is an abstraction where the details of the underlying reality often "leaks through".
All abstractions lie more or less, but sometimes the abstraction is such a bad fit to the underlying reality, that it causes more harm than it helps.
A simple example of a "leak" in an abstraction might be the usual float type. It seems to represent general real numbers and you can use it to perform basic calculations. But at some time you encounter a scenario where 1/3*3 != 1 or 1 + 10^-20 = 1. That is when the actual implementation details leak through and the abstraction breaks.
A fluent interface a term Eric Evans coined and it's just another name for method chaining. Martin Fowler wrote a couple of articles on this subject, but it roughly looks like this:
m_Window = window::with()
.width(l_Width)
.height(l_Height)
.title("default window")
.left(200)
.top(200)
.create();
Fluent interface are generally used to create named parameters in a language that doesn't support them (the Named Parameter Idiom in C++ for example), or in Domain Specific Languages to make the code read more fluently.
I've seen them being used for everything from image processing libraries, to regular expression libraries, 3D libraries. Other examples include the construction of tree structures, lists, or other datastructures. Everything that requires the construction of complex objects (load of parameters) can make use of Fluent Interfaces to make it more readable. For example, compare the previous example to the CreateWindow function call:
::CreateWindow(
"Window class",
"Window title",
dwStyle, X, Y,
nWidth, nHeight,
hWndPant, hMenu,
hInstance, NULL
);
Here's a regular every-day interface:
public interface NotFluent
{
void DoA();
void DoB();
void DoC();
}
And here's a fluent interface:
public interface Fluent
{
Fluent DoA();
Fluent DoB();
Fluent DoC();
}
The most obvious difference is that when we return a void, we return instead an instance of the interface type. What's understood is that the interface returned is the CURRENT INSTANCE, not a new instance of the same type. Of course, this isn't enforceable, and in the case of immutable objects (like string) it is a different instance but can be considered to be the same instance only updated.
Here are examples of their use:
NotFluent foo = new NotFluentImpl();
foo.DoA();
foo.DoB();
foo.DoC();
Fluent bar = new FluentImpl();
bar.DoA().DoB().DoC();
Notice that the fluent interface is easier to use when chaining different calls. IRL, check out the Linq extension methods and how each call is designed to flow into another. None of the methods return void, even if it would be a valid result.
An object-oriented interface is fluent if methods that are executed for side effect return self, so that such methods can be chained together.
I first encountered fluent interfaces in 1990 when the Modula-3 Interface Police (I am not making this up) required all initialization methods to return the object initialized. I believe this usage predates the coinage of the term "fluent interface".
In a fluent interface, a object's methods will return a reference to the object, so that you can chain the method calls together.
For example, in NValidate, I did this to simplify parameter validation:
public City GetCity(string zipCode)
{
zipCode.Assert("zipCode").IsNotNullOrEmpty().HasLength(5,10).Matches("\\d[5]-\\d[4]");
// Continue processing
}
I can't speak to leaky abstractions, though.
Neal Ford does a nice job of explaining and giving Fluent Interface examples in his book the 'Productive Programmer'.
Traditional Object or 'bean' with getters/setters:
Car car = new CarImpl();
MarketingDescription des = new MarketingDescriptionImpl();
desc.setType("Box");
desc.setSubtype("Insulated");
desc.setAttribute("length", "50.5");
desc.setAttribute("ladder", "yes");
desc.setAttribute("lining type", "cork");
car.setDescription(desc);
Meet the same need with a fluent interface:
Car car = Car.describedAs()
.box()
.length(50.5)
.type(Type.INSULATED)
.includes(Equipment.LADDER)
.lining(Lining.CORK);