NSManagedObject: Should I use transient or a regular #property? - core-data

Why not just use a regular #property instead of transient? I don't care about supporting undo.

If you don't need undo, there's a good chance a plain unmodeled #property is better. When explicitly modeling a property as transient, the main differences are:
Setting the property marks the object as dirty, even though nothing would actually be saved;
The property is cleared when the object turns into a fault;
Weird things can happen when merging changes, depending on your chosen merge strategy.
Some experiments working out the semantics of a transient modeled property might be found at https://web.archive.org/web/20160423093331/http://www.2pi.dk/tech/cocoa/transient_properties.html by Jakob Stoklund Olesen. Because that's a dying archive.org link, I'll excerpt some choice tidbits:
"A transient property ... You should be thinking of it as something whose value is nil in the persistent store."
"So what are transient properties good for? ... [for] any property you don't need to be stored, but would like undo support for."
"Another use ... is caching for properties that can't be stored. Cross-store relationships and attributes with unsupported types are the typical examples. Before saving, you convert the property into something that can be stored, and write it to a binary 'shadow' attribute."
"It is better to imagine transient properties as representing 'something that is nil in the persistent store', than the common 'fancy instance variables with undo'."
A good article and I wish Jakob had left it up.

Related

How to implement a proper layer separation in XPages (i.e. talk to Java objects, not DominoViews and DominoDocuments)

I'm trying to implement a proper layer separation in my XPage project. Ideally I'm trying to get to a point where the XML in the XPage contains no SSJS and uses only EL to access Java objects.
So far I've worked out how to load all my data from the domino database into Java Beans (where 1 document = 1 Object, more or less), I'm reading view contents into Java Maps or Lists, and I've managed to display the content of these collections in repeat controls.
What I'm unsure of is how to display the content of a 'form', of a single document, without referencing the domino document. In particular, I'm unsure of how to deal with the 'new document' case. I suppose I create an empty object, then set that object as a data source for the Xpage.
I'm aware that I have to use a ObjectDataSource for this, but I'm unsure where to actually store it. I read an article from Stephan Wissel stating that one shouldn't put them in managed bean, so where can I put it? In one of the scoped variables like viewScope?
Right now I've written an 'ApplicationBean' which is a session-scope Managed Bean where I'm storing all my objects.
What is the best practise? It seems that there are many different ways to meet that goal. Currently I'm exploring Christian Güdemann's XPages Toolkit, which sounds very promising. I know that Samir Pipalia, John Daalsgard and Frank van der Linden have worked up their own frameworks.
So how should I go about it? Any pitfalls?
This is a large topic indeed. As Paul mentioned, Tim's document model classes are a great example of how to do that clearly, and Tim goes into more detail in later episodes in that NotesIn9 series. My own Framework's model objects are fairly similar, though I also added collection managers to handle the dirty business of accessing views. For better or for worse, almost every XPage developer solves this problem in a unique way.
There are a number of ways you can go about implementing this sort of thing, and some of the differences aren't terribly important in normal cases (for example, whether you preload all data from the document when constructing the model object or do lazy fetching to the back-end only as needed), but there are definitely a couple overarching questions to tackle.
Model Access
As you mentioned in the question, one of the big problems is how you actually access model objects from the XPage - how the objects are fetched from the DB or created anew. My Framework's model objects use a conceit of "Manager" objects, which are application-scoped beans that allow getting either named collections (which map to views), model objects by UNID, or a new model object via the keyword "new". Generally, these models (which are Serializable) are then stored in the view scope of the page using them either via <xp:dataContext/>, <xe:objectData/>, or the Framework's own <ff:modelObjectData/>.
I've found it very wise to avoid using managed beans to represent individual objects (like "CurrentWhatever" that you then fill with data on each page), since that muddies up your faces-config in the best case or runs into session problems in the worst (if you put it in session scope, which I rarely use).
How you implement "new" vs. "fetched" model objects depends largely on the tack you take to write your models in the first place, but most boil down to having two constructors: one to take a UNID (at least) to point to existing document and one to create a new one. If you go the "write every properly explicitly in the object with getters and setters" route, the latter would also initialize all of the fields with default values instead of reading them from a document. Internally, you should have fields to store the UNID of the document, which can indicate whether it's new or not - then, your save method can check if this field is empty and create a new document if needed (and then store the new doc's UNID in the field).
Views
It sounds like you're already reading your model collections into Lists, which is good. One down side there, though, is scalability: with small (less than 100) collections, you're likely to not run into any load-speed problems, but afterwards things are going to slow down on initial page load as your code reads in the entire view ahead of time. You can mitigate this somewhat with efficient view reading, but there's a limit. The built-in views are generally speedy because they only load data as needed (they also cheat like hell to do so, but that's another issue).
This is a noble goal to aim for yourself, but doing so to cover all cases is no small feat: you end up running into questions of FT searching, column resorting, efficient data preloading (you don't want to re-open the View object only to read in one entry at a time, but you also don't want to read the whole thing), use in viewPanel and maybe others (which require specialized interfaces), expanding/collapsing categories, and so forth. It's a large sub-topic on its own.
Esoterica
You're also liable to run across other areas that are more difficult than you'd think at first, such as "proper" rich text handing and file attachments. Attachments, in particular, require direct conflict with the XSP framework to get to function properly with custom model objects and the standard upload/download controls.
Case-sensitivity in field names is another potential area of trouble. If you're writing getters and setters for all of your fields, it's a moot point, but if you're going the "thin wrapper" route (which I prefer), it's important to code any intermediary caches/lookups in a way that deal with the fact that "FOO" and "foo" are (basically) the same as item names to Notes, but are distinct in Java. The tack I take is to make extensive use of TreeMaps: if you pass String.CASE_INSENSITIVE_ORDER as the parameter to the constructor, it handles treating Strings as generally case-insensitive when used as keys.
Having your model objects work with all the standard controls like that may or may not be a priority - I find it very valuable, so I did a lot of legwork to make it happen with my framework, but if you're just going to do some basic Strings-and-numbers models, you don't necessarily need to worry.
So... yeah, it's a big topic! Depending on how confident you are with Java and the XPages undergirdings, I would suggest either going the route of fairly-simple "beans with getters and setters" for your objects or by looking into the implementation details of one of the existing frameworks (my own or the ones you mentioned). Sadly, there are a lot of little things that will crop up as your code gets more complicated, many of which are non-obvious to deal with.
Jesse Gallagher's Scaffolding framework also accesses Java objects rather than dominoDocument datasources. I've used (and modified) Tim Tripcony's Java objects in his "Using Java in XPages series" from NotesIn9 (the first is episode 132. The source code for what he does is on BitBucket. This basically converts the dominoDocument to a Map. It doesn't cover MIME (Rich Text) or attachments. If it's useful, I can share the amendments I made (e.g. making field names all the same case, to ensure it still works for existing documents, where fields may have been created with LotusScript).
Andrew - Jesse's one of the experts here so I'd read his response carefully.
What I do is I took one of the key pieces of Jesses bigger framework - the "pageControllers" and I use that HEAVILY. So I end up with a Java Class for each XPages to act as the controller. "All" Jesse's page controller framework does is make it a little easier to consume. So you can reference it on each page as "controller" and don't nee dot make individual managed beans for them.
I still will use SOMES SSJS on the XPage if I really need to for things like button events.. some methods that don't have proper getters and setters.. HashMap.size() for instance. But the vast bulk of the code goes into the Java Class. No real need for viewScope variables any more as well.
in the case of a "New Document".. In the controller I'll create a new Java Object that represents the "Current document". I'll bind all the fields to that. If it's new I create a new Object and assign it to the private variable. If I'm loading form somewhere then I take that variable and load the document I want.
I've started to really try and detail this in more recent NotesIn9's. Especially the little series on Java for Xpages developers. I think I got far enough there to show you what you need to know. I do plan on doing a lot more on this topic as soon as I can.

InitialValue of transient attribute in a persistent object?

Even though I use a specific ORM framework, Bold for Delphi, I'm more interested in framework agnostic theoretical view on the problem.
So the question is about having a persistent object and a transient attribute with initial value tag.
The initial tag specifies the value attribute will get when instance of owning object is created.
However when subsequently loading this object from persistence, what should be the value of transient attribute?
Should initial value tag be applied again? Logically, it should, otherwise it will be left unassigned (null).
I couldn't find any specs on this particular case in any of the docs.
We can't create object up to the DB record only - because we would lose all transient attributes. So, when you are loading a persistent object, it can be done only into the already created instance. And there is no other way of instantiating without using the base object constructor, which sets the initial values. Of course, some language could make a workaround about it, but why?

Is it better to calculate object state from properties or vice versa?

For an arbitrary business object, is it better practice to calculate state from properties, or vice versa?
For example, if I had a TrafficLight with properties Red, Yellow and Green, is it considered better to create a function SetState(state) that toggles the lights as required, or to toggle the lights individually and have GetState() return the calculated state?
Is it simply a matter of preference, or are there certain situations that work better with one or the other?
UPDATE:
The answers/comments so far have made me realize that what I'm really after is whether to store the current state as individual properties or as a combined state. Would the traffic light state be best saved as Red=Off, Yellow=Off, Green=On or as State=Go?
I could easily determine either one from the other when reading the values, and in my real-world problem (as far as I currently know) the relationship of property-combinations to states = 1:1.
I believe it's not so much a matter of preference but rather a matter of usage.
For the traffic light example, you may have some internal timers and such running that alter the lit values. Users of your traffic light class would rather be interested in the state of the object, so the GetState method would be applicable much more so than a publicly available SetState.
However, there are situations where you'd rather set the state of an object and you're really interested in the outcome by reading different properties of that object.
So I'd say that usage drives this. Hope this helps!
As I understand it, direct property access is generally frowned on, as that exposes those properties on the surface of the object, and creates a semi-brittle model. Other objects that can interact with TrafficLight have direct access to modify the state of the object, and if you need to modify the way that state is managed internally to TrafficLight, you now have to also modify any objects that rely on TrafficLight exposing those properties.
Hiding properties behind methods to set and get state allow some level of abstraction. Other objects don't have to worry about /how/ TrafficLight works internally, they only have to know to use the proper getter/setter methods. This makes it easier to maintain the internals of your TrafficLight without forcing more changes to other objects.
A secondary benefit to handling it via getter/setter methods is that you can therefore also create listener-observer interactions by broadcasting changes during a set-method call. It's more flexible, in the long run, as I understand it.
Of course, if your object is more "throwaway" and needs to be kept very simple (say, for serialization purposes), then exposing the properties directly may be your best choice.
I have concluded that in most cases the best way to persist the data is as individual properties, but that adding additional properties which represent the combined state may be necessary if the property-combination to state relationship is not 1:1.
For the traffic light example, if SetState(go) and SetSate(goFast) both produce a combination of R=0, Y=0, G=1 then it would be necessary to introduce something like a GoState property if that information needs to be stored.
My reasons for this approach include:
much simpler code to get (and set, if allowed) property values
often many property combinations result in the same state (ex: R=1, Y=1, G=0 and R=1, Y=0, G=1 and several others are all Error states)
more true-to-life, i.e. physical properties of an object typically determine it's status, not the other way around.
I agree with the other answers that accessing (both setting and getting) the information depends primarily on usage requirements.

Do I need to add RowVersion TimeStamp type property "Entity Framework Code First" to Parent and Child classes?

My question here is if I should place a RowVersion [TimeStamp] property in every
entity in my domain model.
For Example: I have an Order class and an OrderDetails "navigation, reference" property,
should I use a RowVersion property for both entities, or is it enough to the parent object?
These classes are pocos meant to be used with Entity Framework Code First approach.
Thank you.
The answer, as often, is "it depends".
Since it will almost always be possible to have an Order without any OrderDetails, you're right that the parent object should have a RowVersion property.
Is it possible to modify an OrderDetail without also modifying the Order? Should it be?
If it isn't possible and shouldn't be, a RowVersion property at the detail level doesn't add anything. You already catch all possible modifications by checking the Order's RowVersion. In that case, only add the property at the top level, and stop reading here.
Otherwise, if two independent contexts load the same order and details, both modify a different OrderDetail, and both try to save, do you want to treat this as a conflict? In some cases, this makes sense. In other cases, it doesn't. To treat it as a conflict, the simplest solution is to actually mark the Order as modified too if it is unchanged (using ObjectStateEntry.SetModified, not ObjectStateEntry.ChangeState). EF will check and cause an update to the Order's RowVersion property, and complain if anyone else made any modifications.
If you do want to allow two independent contexts to modify two different OrderDetails of the same Order, yes, you need a RowVersion attribute at the detail level.
That said: if you load an Order and its OrderDetails into the same context, modify an OrderDetail, and save your changes, Entity Framework may also check and update the Order's RowVersion, even if you don't actually change the Order, causing bogus concurrency exceptions. This has been labelled a bug, and a hotfix is available, or you can install .NET Framework 4.5 (currently available in release candidate form), which fixes it even if your application uses .NET 4.0.

Using object's setter to trigger data updates, best practices

I have an object that gets instantiated in a linq to sql method. When the object fields are being assigned, i want to check a date field and if it is an old date, retrieve data from another table and perform calculations before continuing with assigning this object.
Is there anything wrong with triggering such an event through the property setter Or should I independently check the date through some service and make the changes if necessary at some point aftwewards?
There's nothing wrong with doing some logic from within your setters, but you should be careful about just how much logic you put within your setters. One of the fundamental problems of setters is that since they act like attributes, but have backing code, it's easy to forget that there are potentially some non-trivial actions going on behind the scenes.
This sort of thing can cause problems if you have accessors which use accessors which use accessors; you can rapidly end up causing unexpected performance problems. Generally, it's a good idea to keep the actions of setters (or getters, for that matter) to a relatively small set of actions. For example, validation can work perfectly fine in a setter, but I'd generally advise against doing validation against external resources, because of two things: first, resource delays can cause problems with expected access speed, and secondly, the number of external resource accesses can destroy your performance.
Generally, the rule is this: keep it simple. It's not unreasonable to do complicated things in a setter, but if you do, it's really important to understand the consequences of all of the actions you'll be causing, and it's EXTREMELY important to document what it does extremely well, so the next guy (or girl) to use the code doesn't just try to naively use the accessor and end up causing massive resource contention issues unexpectedly.
Half the point of using setters instead of, say, public fields, is to be able to trigger events associated with setting certain data.
Keyword: associated. If you're just using the setter as a "convenient" time to do some other stuff because it happens to work, you're doing it wrong. If setting this value requires other work to be done, then by all means, use the setter to do it.

Resources