Is it better to populate an object's properties in the constructor or when the property is referenced? - oop

Background: I have an object with a dozen or so properties. The object is instantiated by passing a GUID to the constructor. This GUID is a primary key used to retrieve the property values from the database. Each property is stored in a separate table in the database. We are using EF4 to connect to the database.
Is it better to get all the properties at once from the database or is it better to fetch the property values from the database when the property is actually used in the code? What is the recommended best practice?

I would probably change the code to pass a Guid to a static factory method, which then did the lookup, and passed the recovered entity to the constructor. That way the constructor itself doesn't have to do as much work.
In most cases I would do all this eagerly though - it's usually odd to have an object which "feels" simple, but which then does potentially expensive and fallible database lookups when you access properties. And yes, you should strive to fetch everything in one database lookup - unless one of the properties is actually a collection in itself, etc. If it's just a case of fetching simple fields from the database, it would be crazy to perform one lookup per property access - which could end up giving inconsistent data, too.

At my job we use java / hibernate to handle the db related queries. You can configure it either way - lazy fetching waits for the application to request a property, or you can populate the object's properties on the initial query.
I'm not sure of a standard; however for our application we've found that populating the properties first turned out to be much faster. Its probably worth running a handful of tests to see how your application behaves - could be very different from ours.

Related

Class with a list of materials: best practice

I've created the custom class ZMaterial that can be instantiated passing an ID to the constructor which sets the properties for a single material using SELECTs and BAPIs. This class is basically used to READ and UPDATE a single material.
Now I need to create a service to return a list of materials. I already have the procedural code for it in a static method (for now actually a function module), but I would like to keep using a full OOP approach and instantiate a list of my custom material object. The first approach I found is to enhance the static method to instantiate a list of my single material object after the selects are executed and I have the data in internal tables, but it does not seem the most OOP.
The second option in my mind is to create a new class ZMaterialList with one property being a list of objects ZMaterial and then a constructor with the necessary input parameters for the database select. The problem I see with this option is that I create a full class just for the constructor.
What do you think is the best way to proceed?
Create a separate class to produce the list of materials. The single responsibility principle says each class should do exactly one thing. In all but the most simple cases, using a thing is a different responsibility than producing it.
Don’t make a ZMaterialList class. A list’s focus would be managing the list items, i.e. adding, removing, iterating, sorting etc. But you should be fine with a regular STANDARD TABLE OF REF TO ZMaterial.
Make a ZMaterialReader, -Repository, -Query or -Factory class or the like, depending on the precise way you want to produce the ZMaterials. Readers read by keys, repositories read and write, queries use varying sets of selection criteria, factories instantiate with possibly different sets of inputs.
You can well let that class use the original FUNCTION underneath. It’s good style to exploit what’s already there. Just make sure you trust that code, put it in a test harness, and keep it afar from the rest of your oo code.
Extract all public interaction of ZMaterial to an interface and use only that interface. That allows you to offer alternative implementations of ZMaterial, ones that differ in the way they are produced or how they store their data.
Split single production from mass production. Reading MARA to retrieve a single material is okay. But you don’t want thousands of ZMaterials reading MARA individually - that wrecks performance.
Now you’ve got the interface, you could offer a second implementation of ZMaterial whose constructor receives all relevant data and relies on it already having been validated to avoid additional SELECTs.
You could also offer an implementation that doesn’t store its data at all but only stores pointers to rows in internal tables somewhere else. See the flyweight pattern for ideas.
If you expect mass updates on the materials, such as “reclassify all of these as B”, consider extracting these list-oriented operations to separate classes as well.

Neo4j - Wrapping/Inheriting a Node object

I'm developing kind of a social network with neo4j, and i wanted to make my Node object a bit more specific for my own needs. Does it considered a good practice to wrap a neo4j Node object or to inherit from it?
My problem with the wrapping approach arises when indexing the nodes objects with the built in Lucene engine. For example, what benefits will i earn if i'll wrap my Node object with a "Profile" class (with methods such as "addFriend", "setFirstName", etc..), but on the other hand, whenever i will run a query against my index i'll get back raw Node objects and not my wrapped objects? I can make some dirty solution for this case, by saving a reference for the wrapped object inside my node properties, but it looks very strange for me to do it.
What would you recommend to do in such case, in order to get a clean and well designed code?
Thanks.
I have found that wrapping a Node does not lead to very maintainable code/design. As you mentioned, one thing you need to take care of is not returning a Node but translating it to your domain object.
If your object has mostly getX methods, then you can just execute Cypher queries, compose your domain object(s) and return those. You don't even need to wrap the Node in this case- all you need is some property that you can use to look up the Node.
If you have setX methods, then you can update the Node via Cypher statements either via a save that updates all properties or on each setX (not great, as you'd be updating too often the setX method now implies persistence). Either of the two approaches does not require the Node to be wrapped.
I tried in earlier projects to wrap the Node but found that it leads to much more trouble and a generally smelly design. Now I work with pure domain POJOS's and keep Neo4j code in the persistence layer only, and this works much better for me. You haven't mentioned which language you're using- if Java, then I believe Spring Data can take care of a lot of boilerplate code.
Put your search code INTO the class they belongs to.
If you need to get, I don't know, something like getFriends from a Post class, you will create the method fromPosts into the Person class, and the getFriends method into Post.
From post, you will call the query from Person class, execute the query and return an Array / List of the nodes mapped into the Person class.
So your getFriends method into the Post class will be something like:
Person.fromPosts(self).results.map { |node| Person.new(node) }
Is simple to do that doing just a map of the result with a Person.new (or new Person, depend from which language are you using) and pass the node to the Person. This means that you must have a new method that populate object from a node.
Spring Data Neo4j is the definitive solution to your need, it maps annotated entity classes to Neo4j with advanced mapping functionality and provides access to nodes and relationships at different levels of abstraction.

nHibernate: determine property value before save

we are currently evaluating whether nHibernate supports the requirements for our project. We share the database with another application so that we are not completely free as regards changes to the schema.
Some columns are filled with unique and consecutive numbers (e.g. for invoices). The next number is determined by a stored procedure that also implements a locking algorithm so that the numbers are guaranteed to be consecutive.
On the one hand we could define a trigger on the respective tables that sets the value for the column when an empty or special value is provided. This would require changing the existing database definition - though it might be the most reliable way to implement this.
In order to avoid the change of the database definition we are trying to solve this in the nHibernate ORM. We've first tried to implement a user type that calls the stored procedure in NullSafeSet if an empty value is provided. Unfortunately, the connection and transaction of the provided command are not set yet when NullSafeSet is called.
How can we solve this with nHibernate?
Thanks in advance,
Markus
If you decide to go with trigger route, then you'll need to add generated attribute to your property mapping.
Generated properties are properties which have their values generated
by the database. Typically, NHibernate applications needed to Refresh
objects which contain any properties for which the database was
generating values. Marking properties as generated, however, lets the
application delegate this responsibility to NHibernate. Essentially,
whenever NHibernate issues an SQL INSERT or UPDATE for an entity which
has defined generated properties, it immediately issues a select
afterwards to retrieve the generated values.
Aside from that, I'm not quite sure how would you call stored procedure from NHibernate issued INSERT, without adding a trigger or default constraint on column.
Edit
Looks like NHibernate has a notion of class persisters, through the interface IEntityPersister. Maybe you could hack something out from that.
The persister attribute lets you customize the persistence strategy
used for the class. You may, for example, specify your own subclass of
NHibernate.Persister.EntityPersister or you might even provide a
completely new implementation of the interface
NHibernate.Persister.IClassPersister that implements persistence via,
for example, stored procedure calls, serialization to flat files or
LDAP. See NHibernate.DomainModel.CustomPersister for a simple example
(of "persistence" to a Hashtable).
You could start from NHibernate's source.
If you have the ability to add triggers to database, that would probably be the best, straightforward way, without investing too much time to fight with NHibernate's internals.

best practice for a function which interacts with a database

Say I have a User object, which is generated by a Usermapper. The User object does not know anything about the database/repository in use (which I believe to be good design).
When creating a User, I only want it to have it filled by the mapper with the most trivial things e.g. Name, address etc. However after object instantiation I might have a method userX.getTotalDebt(), getTotalDebt() would need to reconnect to the database , because I don't want this relatively expensive operation to be done for every User instantiation (multiple tables needed etc). If I'd simply insert some sql in the getTotalDebt() or a dependency back to the Mapper where the coupledness is growing tight very fast.
There is an obvious good/best practice for this, because it's a situation arises often, however I can't find it or I'm looking at this problem totally from a wrong angle.
Say I have a User object, which is generated by a Usermapper. The User object does not know anything about the database/repository in use (which I believe to be good design).
They are often referred to as POCOs (Plain Old CLR Objects).
When creating a User I only want it to have it filled by the mapper with the most trivial things e.g. Name, address etc.
There are several OR/M layers which can achieve this. Use either nhibernate or Entity Framework 4.1 Code First.
I might have a method userX.getTotalDebt(), getTotalDebt() would need to reconnect to the database
Then it's not a poco anymore. Although it is possible using a transparent proxy. Both EF and nhibernate supports this and it's called Lazy Loading.
There is an obvious good/best practice for this, because it's a situation arises often, however I can't find it or I'm looking at this problem totally from a wrong angle
I usually keep my objects dumb and disconnected. I use the Repository pattern (even if I use nhibernate or another orm) since it makes my classes testable.
I either use the repository classes directly or create a service class which contains all logic. It depends on how complex my application is.

What classes should I map against with NHibernate?

Currently, we use NHibernate to map business objects to database tables. Said business objects enforce business rules: The set accessors will throw an exception on the spot if the contract for that property is violated. Also, the properties enforce relationships with other objects (sometimes bidirectional!). Well, whenever NHibernate loads an object from the database (e.g. when ISession.Get(id) is called), the set accessors of the mapped properties are used to put the data into the object.
What's good is that the middle tier of the application enforces business logic. What's bad is that the database does not. Sometimes crap finds its way into the database. If crap is loaded into the application, it bails (throws an exception). Sometimes it clearly should bail because it cannot do anything, but what if it can continue working? E.g., an admin tool that gathers real-time reports runs a high risk of failing unnecessarily instead of allowing an admin to even fix a (potential) problem.
I don't have an example on me right now, but in some instances, letting NHibernate use the "front door" properties that also enforce relationships (especially bidi) leads to bugs.
What are the best solutions?
Currently, I will, on a per-property basis, create a "back door" just for NHibernate:
public virtual int Blah {get {return _Blah;} set {/*enforces BR's*/}}
protected virtual int _Blah {get {return blah;} set {blah = value;}}
private int blah;
I showed the above in C# 2 (no default properties) to demonstrate how this gets us basically 3 layers of, or views, to blah!!! While this certainly works, it does not seem ideal as it requires the BL to provide one (public) interface for the app-at-large, and another (protected) interface for the data access layer.
There is an additional problem: To my knowledge, NHibernate does not give you a way to distinguish between the name of the property in the BL and the name of the property in the entity model (i.e. the name you use when you query, e.g. via HQL--whenever you give NHibernate the name (string) of a property). This becomes a problem when, at first, the BR's for some property Blah are no problem, so you refer to it in your O/R mapping... but then later, you have to add some BR's that do become a problem, so then you have to change your O/R mapping to use a new _Blah property, which breaks all existing queries using "Blah" (common problem with programming against strings).
Has anyone solved these problems?!
While I found most of your architecture problematic, the usual way to deal with this stuff is having NHibernate use the backing field instead of the setter.
In your example above, you don't need to define an additional protected property. Just use this in the mapping:
<property name="Blah" access="nosetter.lowercase"/>
This is described in the docs, http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-property (Table 5.1. Access Strategies)