How can methods be added to Custom Objects in Force.com APEX? - object

I was under the impression that Force.com eliminated the necessity of object-relational mapping.
I can't create a an object that extends a custom object like this:
class Program extends Program__C() { public Program() { super(); } }
So to "add a method to the Program__c() object" I have been doing this:
class Program {
Program__c program;
public Program() {
program = new Program__c();
}
}
But then this leads to the same ERM problems that I thought Force was supposed to eliminate by virtue of the intercourse between APEX and the DB.
Is there any way to extend custom objects, or at least add methods to custom objects, in APEX? Am I incorrect in that developers don't have to do ORM?
Thank you,
-Matthew Mosien

As far as I know (and I'm pretty certain), there is no way to extend custom objects in the manner you wish.
What you're doing seems to be a reasonable solution to the problem.
You don't have to do ORM in the sense that any objects and fields you have in your DB are already accessible in your code with no extra effort. However, you can't do much (if anything) to affect your schema programmatically in your code. You're kinda stuck with it.
Hope this helps!

Related

Usage of implementsInterface element on entities in guidewire

I would like to know why do we use implementsInterface element in entities. I know one example where they use it to make it as assignable entity. But I could not understand what other purpose and how/why it is being used in entities.
Example: Injuryincident entity has claimantsupplier and coveragesupplier interface
I like to see it from this prespective, simplified and assuming that you have some java background:
As you probably already know it, having an entity means in the end of the day, having a Java class... Well, by using the implementsInterface element in your entity, is similar to implement an interface in you java class.
Here you have a quick example...
Consider the following:
MyEntiti.eti
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable"/>
AnInterface.gs
package mypkg
interface AnInterface {
function doSomething()
}
AnInterfaceImpl.gs
package mypkg
class AnInterfaceImpl implements AnInterface {
override function doSomething() {
print("Hello!")
}
}
Image that you need MyEntity to have the ability of "doSomething", you just need to add the implementsInterface:
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable">
<implementsInterface
iface="mypkg.AnInterface"
impl="mypkg.AnInterfaceImpl"/>
</entity>
By doing that, the following code must work:
var myEntity = new MyEntity()
myEntity.doSomething() //this will call the method defined in the interface-implementation
And even better, you migth let you implementation to recognize the related object of MyEntity and use it as per your needs:
package mypkg
class AnInterfaceImpl implements AnInterface {
private final var _relatedEntity : MyEntity
construct(relatedTo : MyEntity) {
_relatedEntity = relatedTo
}
override function doSomething() {
var createUser = _relatedEntity.CreateUser // you can accees to whatever you need
print("Hello!, this is the related instace of MyEntity: ${_relatedEntity}")
}
}
Hope it helps, regards!
I won't be repeating the other answer describing how it works, but I would like to mention how implementing an interface on an entity is different (and serves different purposes) compared to using enhancements.
On basic level both approaches let you add extra functionality to your entity classes. In most cases what you really want to do is just create/expand an enhancement - they are easier to write, more convenient to modify and just as effective when all you want is to just add a new function or calculated property.
When you implement an interface, you're bringing in some more serious guns. While this approach takes more work and requires creation of several files (not to mention modifying the entity itself), it gives you two important advantages over the enhancement mechanism:
The same interface can be implemented by several entities (typically each having its own implementation class) as well as non-entity classes. Objects of all such classes can then be used interchangeably in contexts expecting the interface (you can create an array of entity instances of several entities and even gosu-only wrappers/temporary objects and present it comfortably in the UI).
You can leverage polymorphism. While enhancement functions can't be overridden, the interface implementations allow you full flexibility of polymorphic OOP. You can, for example, set up a default "do nothing" implementation on high level entity that you intend to use and then add more meaningful implementations for specific subtypes meant to really make use of the new functionality.
It does have some overhead and complicates things, however. As mentioned - Enhancements are typically simpler. In practice you should ask yourself whether the extra effort of creating and implementing the interface is worth it - in many cases even situations seemingly calling for polymorphism can be handled well enough by a simple switch typeof this in the enhancement to provide all the necessary type-based logic.
In personal experience I've used interfaces in quite a few situations, but Enhancements are my first choice in overwhelming majority of cases.
As a final note I'd like to mention a delegate entity. If what you want to add to some unrelated entities is not functionality but Properties with underlying database fields, creating a delegate entity and "implement" it with the desired standalone entities. A delegate entity does work a bit like an interface (you can use entity objects implementing the delegate interchangeably in situations where the delegate is expected) and you can set-up both interface implementation and enhancements on delegate level as well.

Set of dynamic properties in domain-driven design

After through search i was unable to find any question which answers this, in my opinion fairly common design problem.
Given domain object:
public class Item {
private Long itemSN;
private String name;
methods, etc...
}
We need to store specific set of String properties which describes an item. It can be weight, color, sizes etc. System must be flexible and able to persist changeable list o properties. It needs to store allowed properties names, and preferably enforce some of them.
I tried several approaches, but concept of common constraints shared by all Item objects just don't fit in any standard domain model.
So i started to think about constraints as a form of configuration. Each Item has its's own properties (in simple String Map), constraints at the other hand are common configuration for all Items. So the next dilema emerged... how to express it without making big hole in domain model ?
It's easy to introduce additional application layer object to store constraints, but "allowed/required properites" are business affair, we need to allow domain user (manager of some sort) to change it, so its feels really horrible to draw this logic away from domain layer.
Any suggestions are welcome.
Edit 1.
After lot of brainstorming i managed to create valid object model for given situation. From first sight it was impossible to encapsulate properties with common constraints, but the latest out-of-domain implementation gave me an idea:
public class Item {
private Long itemSN;
private String name;
private List<Property> properties;
}
Core of the problem was solved here:
public class Property {
private Long propertyId;
private String propertyValue;
private Constraint constraint;
}
public class Constraint {
private String name;
private Boolean required;
private List<String> allowedValues;
}
So, each property have its value and constraint object which specifies name, allowed values and required status. This way constraint object can be shared by many properites, and any of this properties can have its own value.
It's adding some complexity to DB mapping and will hit performance but it's also keeping all domain logic in domain objects.
Any improvements, suggestions and opinions are welcome.
This problem can very reasonably be solved by the usage of annotations. Annotations allow you, the coder, to keep on using the language for the usage of properties by simply annotating your properties with constraints while still making it possible to apply the same constraints to user defined fields without the annotations.
JSR-349 is a Java standard for applying such constraints. Hibernate validator is a well known implementation.

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

How can I make JAXB-generated classes participate in a Visitor pattern?

Hey folks, hopefully a nice easy one here.
I'm generating classes with JAXB from a schema, and I'd like to be able to process them with a Visitor pattern.
To do that, I think I need every JAXB-generated class to implement the interface I've defined, and add a very simple method to them, so a simple example would be:
Default class:
public class MyClass {
private String name;
public void get/setName() {...}
}
Desired class:
public class MyClass implements MyVisitorNode {
private String name;
public void get/setName() {...}
public void accept(MyVisitorVisitor visitor) {
visitor.visit(this);
}
}
Is this possible, and if it is, what are the options? (Change the schema, runtime bytecode manipulation, manipulate the JAXBContext somehow...)
Ideally, without relying on vendor-specific extensions.
Thanks!
The xjc compiler for JAXB has a plugin interface that allows developers to create plugins that modify the generated code. My personal favorite is the fluent-api but there are others to add toString, equals, hashCode, etc.
I created a plugin using this technology to implement the visitor pattern and made it available as a google code project. It may not be exactly what you're looking for but it might be a good place to start to review the code and tests if you need to modify it to suit your needs.
http://code.google.com/p/jaxb-visitor/
The JAX-B generated classes are standard Java classes that you can customize in any way you desire, e.g., extend interface, add additional methods, etc..). The annotations on the class and attributes are the driving factor for the marshalling and unmarshalling process.
With that said, there are somethings you need to take into account if you customize the JAXB generated classes. As stated at the top of each class "Any modifications to this file will be lost upon recompilation of the source schema". In short, if you customize the class, you will need to manually make code changes to support any schema updates. If you do regenerated the classes, your custom code will be removed and you will have to start all over.

Adding properties to an existing object retrieved using SubSonic

I think this is more of a polymorphism question but it applies to SubSonic table objects...
Here's the thing (and I love this one):
TblUser userObj = new TblUser(1);
Which fills userObj's properties with all of PK=1's goodies.
Now, I'd like to add more properties to the existing user object, for example, an ArrayList property of say, account numbers.
I've seen questions like this around - "add a property to an existing object...", but in this case, would it be most-recommended to create a user wrapper object, then have a TblUser property type, and my own other additional properties in this?
Ok, so it looks like once-again I have come up with a solution to this, but am still curious about the possibility of adding properties to existing objects.
All the generated SubSonic classes are partials so all you need to do to add extra properties/methods to them is to create your own partial class with the same name in the same namespace and the two will be merged at compile time. For example for your TblUser class:
public partial class TblUser
{
public List<AccountNumber> AccountNumbers
{
get
{
// Get and return the AccountNumbers
}
}
}

Resources