How to create two figures on a single Drag and drop in GEF? - eclipse-gef

I like to create two figure on a single drag and drop form the palette i.e At a single drag and drop two figures should be created both have separate EditPart and Model class.
Thanks in advance

There is multiple ways to make this happen: the easiest is to make you creationFactory return
an array or a list of objects. Then, in you
protected Command getCreateCommand(final CreateRequest request) {
if (request.getNewObject() instanceof List<?>/Object[]) {
...
}
}
or, the other way is to sublcass CreationTool to have a List of creation factories. Then, create a custom request type, for example,
public class MultiCreateRequest extends Request {
...
}
and override getCommand(Request request) dispatching method that it will handle that case:
public Command getCommand(Request request) {
if (REQ_MULTI_CREATE.equals(request.getType()))
return getMultiCreateCommand((MultiCreateRequest) request);
}
when subclassing creation tool you should pay you attention to:
Constructor
createTargetRequest() (return MultiCreateRequest)
getCommandName() (return REQ_MULTI_CREATE)
getCreateRequest() (specify)
selectAddedObject(EditPartViewer viewer) (to select all created that way objects)
updateTargetRequest() (specify)
Oh, i've actually came up with the idea, that creation new Tool subclassing TargetingTool is a better idea then subclassing CreationTool. Instead, you can just copy implementation (it's easy actually) and change it as you need.

Related

How to eliminate method side effects?

When I write codes, I try to be careful about SOLID and clean code principles. When I look at my functions, I think that I fall into side effect error.
For example, lets assume that I have a logic in a web service. When I trigger a method, it must get all data from another service and insert them to database. My representative methods are like below.
//when I call the method, process starts
public void TriggerProcess()
{
GetInformationsFromService();
}
public void GetInformationsFromService()
{
var informations = exampleService.GetInformations();
InsertInformations(informations);
}
public void InsertInformations(informations)
{
insertThemToDb(informations);
}
When I write codes like above, I fall into side effect error. If someone wants to use only GetInformationsFromService() methods in the service, it shoud not insert data.
However, If I call methods like below..
public void TriggerProcess()
{
var informations = GetInformationsFromService();
InsertInformations(informations);
}
There will be always a lot of methods like chain methods which have one purpose that is to call methods in proper order and there is always a middle
layer between trigger methods and methods with one responsibility. if business gets bigger, it seems strange I think.
public void RepresentativeMethod()
{
method1();
method2();
method3();
//...
}
How can I avoid side effect? Which pattern can I use to make good implementation?
Updating/Inserting data in the database from the data from another service and just viewing of data is two different use cases/process. Don't try to reuse your GetInformationsFromService() because it has different purpose. Actually, you must rename it something like SyncInformation() and you will have another method called GetInformation() just to view data.
Here's what you can do, eliminate the TriggerProcess() because SyncInformation() is already a process, just call it directly:
This use cases/process should also be included in the domain layer:
Synchronize Information Use Case:
public void SyncInformation() {
var informations = exampleService.GetInformations();
informationRepository.insertInformation(informations);
}
Get Information Use Case:
public List<Information> GetInformation() {
return exampleService.getInformation();
}
Fetching and saving of data should be in your data layer:
ExampleService:
public List<Information> getInformation() {
// logic to fetch from another service, eg: API
}
InformationRepository:
public void insertInformation(informations)
{
// insert to database logic
}
Here, we are following the separation of concerns because we're splitting it into two layers, domain and data. Domain layer handles all the application/business logic like for example the steps on how to synchronize of information. It knows WHEN it should save data but it doesn't know HOW. Data layer knows HOW to read and save data, but it doesn't know WHEN it should happen.

The difference between object validation and persistence validation in DDD?

Right now, I have a domain entity named StyleBundle. This StyleBundle takes a list of Styles:
public class StyleBundle
{
public StyleBundle(List<Style> styles)
{
this.Styles = styles;
}
public IEnumerable<Style> Styles { get; private set;}
}
So, in my original design, a StyleBundle should never be created with an empty Style list. This was a rule that the domain experts basically said was good.
I wrote this using a guard clause in the constructor:
if (styles.Count() == 0)
throw new Exception("You must have at least one Style in a StyleBundle.");
which made sure I could not create StyleBundle in an invalid state. I thought an exception made sense here b/c a StyleBundle being created without at least one Style was exceptional in the system.
Of course, change came down the road during the rest of the project, and now it should be possible for a user to create a StyleBundle without Styles, but they should not be allowed to PERSIST a StyleBundle without Styles.
So now I'm looking at my guard clause and realizing that I can't have the exception thrown from the constructor anymore.
Moving forward, I have a Service/Application layer that my code-behinds interact with when they're working with StyleBundles. In my Service Layer, I have a StyleBundleService class, and that class exposes basic functionality to the UI... among them is "CreateStyleBundle".
It seems as if I'll have to have my Service Layer check to see if the StyleBundle does or does not have any Styles before it's persisted to the database, but something about this decision feels "wrong" to me.
Anyone run into a similar thing? Basically, the different between the state of an object being valid when "new'ed up" vs. the state of the same object when it comes to persistence?
Thanks!
Mike
I would add an IsValid method to your entity. This would check if the entity is currently in a valid state (in your case, check if there are styles).
This method can be called from your Repository to check if an entity may be persisted. You can add more rules to the IsValid method for specific entities and you can implement something like a collection of Validation errors is you want to throw a meaningful exception.
Expanding what Wouter said, plus handy BeforeSaving and BeforeDeleting methods:
public interface IDomainObject<T>
{
bool IsValid();
}
public interface IEntity<T> : IDomainObject<T>
{
}
public interface IAggregateRoot<T> : IEntity<T>
{
void BeforeSaving();
void BeforeDeleting();
}
public interface IAggregateRoot { //or simply IEntity depending on the model
bool IsValid();
}
public class StyleBundle : IAggregateRoot<T> {
return styles.Count() > 0
}
public class StyleBundleRepository : Repository<StyleBundle> {
}
public abstract class Repository<T> : IRepository<T> where T : class, IAggregateRoot<T> {
public T Save(T t)
{
t.BeforeSaving(); //for all AggregateRoots, maybe logging what the aggregate was like before the changes
if(!t.IsValid())
throw Exeception("Entity invalid");
EntityStore.Current.SaveChanges();
// "AfterSaving" here, i.e.: log how the entity looks after the update
}
}
Edit: I dont personally use the IsValid idea, I go with a full class of EntityValidationErrors where I can report back to the client what was wrong before attempting to save, things that shouldnt be null, shouldnt be empty (like your Styles etc)
There are multiple strategies:
Some developers prefer to create 2 methods in the entity itself, one called IsValid() which validates the entity in terms of business rules (general validation) and another one called IsValidForPersistence() which validates the entity for persistence.
Regarding IsValid() I prefer instead not to allow invalid state in the first place by validating all inputs, and to support invariants I use factory or builder.
you may check the link http://www.codethinked.com/thoughts-on-domain-validation-part-1
for some thoughts.
I know, this question is three years old, but seeing the current answer is something I like to respond to. We are talking about the domain data. Hence, there can't be a valid StyleBundle with 0 objects. I imagine, you have a frontend editor somewhere, were you create a "new" StyleBundle and have to add at least one style, before hitting the "save" button.
At this point in the frontend, you won't have a domain object. You may have a data transfer object, that will be send with a "CreateNewStyleBundle" command.
In my opinion, the domain object must be agnostic to persitance and should always be in a valid state. If you have to call a "IsValid" method, you circumvent the whole idea of having domain objects in the first place.
That's just my humble opinion.

In Spring MVC 3, how do I bind an object to a query string when the query string parameters don't match up with the object fields?

A 3rd party is sending me part of the data to fill in my domain object via a query string. I need to partially fill in my domain object, and then have the user fill in the rest via a form. I don't have any control over the query string parameters coming in, so I can't change those, but I'd really like to be able to use Spring MVC's data binding abilities, rather than doing it by hand.
How can I do this?
To add some complication to this, some of the parameters will require extensive processing because they map to other objects (such as mapping to a user from just a name) that may not even exist yet and will need to be created. This aspect, I assume, can be handled using property editors. If I run into trouble with this, I will ask another question.
Once I have a partially filled domain object, passing it on to the edit view, etc. is no problem, but I don't know how to properly deal with the initial domain object population.
The only thing I have been able to come up with so far is to have an extra class that has it's properties named to match the inbound query parameters and a function to convert from this intermediary class to my domain class.
This seems like a lot of overhead though just to map between variable names.
Can you not just have the getter named differently from the setter, or have 2 getters and 2 setters if necessary?
private int spn;
// Standard getter/setter
public int getSpn() {
return spn;
}
public void setSpn(int spn) {
this.spn = spn;
}
// More descriptively named getter/setter
public int getShortParameterName() {
return spn;
}
public void setShortParameterName(int spn) {
this.spn = spn;
}
Maybe that is not standard bean convention, but surely would work?

Replace conditional with polymorphism - nice in theory but not practical

"Replace conditional with polymorphism" is elegant only when type of object you're doing switch/if statement for is already selected for you. As an example, I have a web application which reads a query string parameter called "action". Action can have "view", "edit", "sort", and etc. values. So how do I implement this with polymorphism? Well, I can create an abstract class called BaseAction, and derive ViewAction, EditAction, and SortAction from it. But don't I need a conditional to decided which flavor of type BaseAction to instantiate? I don't see how you can entirely replace conditionals with polymorphism. If anything, the conditionals are just getting pushed up to the top of the chain.
EDIT:
public abstract class BaseAction
{
public abstract void doSomething();
}
public class ViewAction : BaseAction
{
public override void doSomething() { // perform a view action here... }
}
public class EditAction : BaseAction
{
public override void doSomething() { // perform an edit action here... }
}
public class SortAction : BaseAction
{
public override void doSomething() { // perform a sort action here... }
}
string action = "view"; // suppose user can pass either "view", "edit", or "sort" strings to you.
BaseAction theAction = null;
switch (action)
{
case "view":
theAction = new ViewAction();
break;
case "edit":
theAction = new EditAction();
break;
case "sort":
theAction = new SortAction();
break;
}
theAction.doSomething(); // So I don't need conditionals here, but I still need it to decide which BaseAction type to instantiate first. There's no way to completely get rid of the conditionals.
You're right - "the conditionals are getting pushed up to the top of the chain" - but there's no "just" about it. It's very powerful. As #thkala says, you just make the choice once; from there on out, the object knows how to go about its business. The approach you describe - BaseAction, ViewAction, and the rest - is a good way to go about it. Try it out and see how much cleaner your code becomes.
When you've got one factory method that takes a string like "View" and returns an Action, and you call that, you have isolated your conditionality. That's great. And you can't properly appreciate the power 'til you've tried it - so give it a shot!
Even though the last answer was a year ago, I would like to make some reviews/comments on this topic.
Answers Review
I agree with #CarlManaster about coding the switch statement once to avoid all well known problems of dealing with duplicated code, in this case involving conditionals (some of them mentioned by #thkala).
I don't believe the approach proposed by #KonradSzałwiński or #AlexanderKogtenkov fits this scenario for two reasons:
First, from the problem you've described, you don't need to dynamically change the mapping between the name of an action and the instance of an action that handles it.
Notice these solutions allows doing that (by simply assigning an action name to a new action instance), while the static switch-based solution doesn't (the mappings are hardcoded).
Also, you'll still need a conditional to check if a given key is defined in the mapping table, if not an action should be taken (the default part of a switch statement).
Second, in this particular example, dictionaries are really hidden implementations of switch statement. Even more, it might be easier to read/understand the switch statement with the default clause than having to mentally execute the code that returns the handling object from the mapping table, including the handling of a not defined key.
There is a way you can get rid of all conditionals, including the switch statement:
Removing the switch statement (use no conditionals at all)
How to create the right action object from the action name?
I'll be language-agnostic so this answer doesn't get that long, but the trick is to realize classes are objects too.
If you've already defined a polimorphic hierarchy, it makes no sense to make reference to a concrete subclass of BaseAction: why not ask it to return the right instance handling an action by its name?
That is usually implemented by the same switch statement you had written (say, a factory method)... but what about this:
public class BaseAction {
//I'm using this notation to write a class method
public static handlingByName(anActionName) {
subclasses = this.concreteSubclasses()
handlingClass = subclasses.detect(x => x.handlesByName(anActionName));
return new handlingClass();
}
}
So, what is that method doing?
First, retrieves all concrete subclasses of this (which points to BaseAction). In your example you would get back a collection with ViewAction, EditAction and SortAction.
Notice that I said concrete subclasses, not all subclasses. If the hierarchy is deeper, concrete subclasses will always be the ones in the bottom of the hierarchy (leaf). That's because they are the only ones supposed not to be abstract and provide real implementation.
Second, get the first subclass that answer whether or not it can handle an action by its name (I'm using a lambda/closure flavored notation). A sample implementation of the handlesByName class method for ViewAction would look like:
public static class ViewAction {
public static bool handlesByName(anActionName) {
return anActionName == 'view'
}
}
Third, we send the message new to the class that handles the action, effectively creating an instance of it.
Of course, you have to deal with the case when none of the subclass handles the action by it's name. Many programming languages, including Smalltalk and Ruby, allows passing the detect method a second lambda/closure that will only get evaluated if none of the subclasses matches the criteria.
Also, you will have to deal with the case more than one subclass handles the action by its name (probably, one of these methods was coded in the wrong way).
Conclusion
One advantage of this approach is that new actions can be supported by writing (and not modifying) existing code: just create a new subclass of BaseAction and implementing the handlesByName class method correctly. It effectively supports adding a new feature by adding a new concept, without modifying the existing impementation. It is clear that, if the new feature requires a new polimorphic method to be added to the hierarchy, changes will be needed.
Also, you can provide the developers using your system feedback: "The action provided is not handled by any subclass of BaseAction, please create a new subclass and implement the abstract methods". For me, the fact that the model itself tells you what's wrong (instead of trying to execute mentally a look up table) adds value and clear directions about what has to be done.
Yes, this might sound over-design. Please keep an open mind and realize that whether a solution is over-designed or not has to do, among other things, with the development culture of the particular programming language you're using. For example, .NET guys probably won't be using it because the .NET doesn't allow you to treat classes as real objects, while in the other hand, that solution is used in Smalltalk/Ruby cultures.
Finally, use common sense and taste to determine beforehand if a particular technique really solves your problem before using it. It is tempting yes, but all trade-offs (culture, seniority of the developers, resistance to change, open mindness, etc) should be evaluated.
A few things to consider:
You only instantiate each object once. Once you do that, no more conditionals should be needed regarding its type.
Even in one-time instances, how many conditionals would you get rid of, if you used sub-classes? Code using conditionals like this is quite prone to being full of the exact same conditional again and again and again...
What happens when you need a foo Action value in the future? How many places will you have to modify?
What if you need a bar that is only slightly different than foo? With classes, you just inherit BarAction from FooAction, overriding the one thing that you need to change.
In the long run object oriented code is generally easier to maintain than procedural code - the gurus won't have an issue with either, but for the rest of us there is a difference.
Your example does not require polymorphism, and it may not be advised. The original idea of replacing conditional logic with polymorphic dispatch is sound though.
Here's the difference: in your example you have a small fixed (and predetermined) set of actions. Furthermore the actions are not strongly related in the sense that 'sort' and 'edit' actions have little in common. Polymorphism is over-architecting your solution.
On the other hand, if you have lots of objects with specialised behaviour for a common notion, polymorphism is exactly what you want. For example, in a game there may be many objects that the player can 'activate', but each responds differently. You could implement this with complex conditions (or more likely a switch statement), but polymorphism would be better. Polymorphism allows you to introduce new objects and behaviours that were not part of your original design (but fit within its ethos).
In your example, in would still be a good idea to abstract over the objects that support the view/edit/sort actions, but perhaps not abstract these actions themselves. Here's a test: would you ever want to put those actions in a collection? Probably not, but you might have a list of the objects that support them.
There are several ways to translate an input string to an object of a given type and a conditional is definitely one of them. Depending on the implementation language it might also be possible to use a switch statement that allows to specify expected strings as indexes and create or fetch an object of the corresponding type. Still there is a better way of doing that.
A lookup table can be used to map input strings to the required objects:
action = table.lookup (action_name); // Retrieve an action by its name
if (action == null) ... // No matching action is found
The initialization code would take care of creating the required objects, for example
table ["edit"] = new EditAction ();
table ["view"] = new ViewAction ();
...
This is the basic scheme that can be extended to cover more details, such as additional arguments of the action objects, normalization of the action names before using them for table lookup, replacing a table with a plain array by using integers instead of strings to identify requested actions, etc.
I've been thinking about this problem probably more than the rest developers that I met. Most of them are totally unaware cost of maintaining long nested if-else statement or switch cases. I totally understand your problem in applying solution called "Replace conditional with polymorphism" in your case. You successfully noticed that polymorphism works as long as object is already selected. It has been also said in this tread that this problem can be reduced to association [key] -> [class]. Here is for example AS3 implementation of the solution.
private var _mapping:Dictionary;
private function map():void
{
_mapping["view"] = new ViewAction();
_mapping["edit"] = new EditAction();
_mapping["sort"] = new SortAction();
}
private function getAction(key:String):BaseAction
{
return _mapping[key] as BaseAction;
}
Running that would you like:
public function run(action:String):void
{
var selectedAction:BaseAction = _mapping[action];
selectedAction.apply();
}
In ActionScript3 there is a global function called getDefinitionByName(key:String):Class. The idea is to use your key values to match the names of the classes that represent the solution to your condition. In your case you would need to change "view" to "ViewAction", "edit" to "EditAction" and "sort" to "SortAtion". The is no need to memorize anything using lookup tables. The function run will look like this:
public function run(action:Script):void
{
var class:Class = getDefintionByName(action);
var selectedAction:BaseAction = new class();
selectedAction.apply();
}
Unfortunately you loose compile checking with this solution, but you get flexibility for adding new actions. If you create a new key the only thing you need to do is create an appropriate class that will handle it.
Please leave a comment even if you disagree with me.
public abstract class BaseAction
{
public abstract void doSomething();
}
public class ViewAction : BaseAction
{
public override void doSomething() { // perform a view action here... }
}
public class EditAction : BaseAction
{
public override void doSomething() { // perform an edit action here... }
}
public class SortAction : BaseAction
{
public override void doSomething() { // perform a sort action here... }
}
string action = "view"; // suppose user can pass either
// "view", "edit", or "sort" strings to you.
BaseAction theAction = null;
switch (action)
{
case "view":
theAction = new ViewAction();
break;
case "edit":
theAction = new EditAction();
break;
case "sort":
theAction = new SortAction();
break;
}
theAction.doSomething();
So I don't need conditionals here, but I still need it to decide which BaseAction type to instantiate first. There's no way to completely get rid of the conditionals.
Polymorphism is a method of binding. It is a special case of thing known as "Object Model". Object models are used to manipulate complex systems, like circuit or drawing. Consider something stored/marshalled it text format: item "A", connected to item "B" and "C". Now you need to know what is connected to A. A guy may say that I'm not going to create an Object Model for this because I can count it while parsing, single-pass. In this case, you may be right, you may get away without object model. But what if you need to do a lot of complex manipulations with imported design? Will you manipulate it in text format or sending messages by invoking java methods and referencing java objects is more convenient? That is why it was mentioned that you need to do the translation only once.
You can store string and corresponding action type somewhere in hash map.
public abstract class BaseAction
{
public abstract void doSomething();
}
public class ViewAction : BaseAction
{
public override void doSomething() { // perform a view action here... }
}
public class EditAction : BaseAction
{
public override void doSomething() { // perform an edit action here... }
}
public class SortAction : BaseAction
{
public override void doSomething() { // perform a sort action here... }
}
string action = "view"; // suppose user can pass either
// "view", "edit", or "sort" strings to you.
BaseAction theAction = null;
theAction = actionMap.get(action); // decide at runtime, no conditions
theAction.doSomething();
The switch is simple and looks OK. I don't think it would be that secure if a user could feed in a class name and you could directly use it without a switch conditional.
For obtaining data though, Coders have been known to use a look up table loop to get extra data reducing it to one if in an array look up search. Still thinking the switch looks simple enough to understand but would be cumbersome if you had 100s of choices.

Filter every call made by a DataContext when using LinQ Entities

I'm using logical delete in my system and would like to have every call made to the database filtered automatically.
Let say that I'm loading data from the database in the following way :
product.Regions
How could I filter every request made since Regions is an EntitySet<Region> and not a custom method thus not allowing me to add isDeleted = 0
So far I found AssociateWith but I'd hate to have to write a line of code for each Table -> Association of the current project...
I'm looking into either building generic lambda Expressions or.. something else?
You could create an extension method that implements your filter and use that as your convention.
public static class RegionQuery
{
public static IQueryable<Region> GetAll(this IQueryable<Region> query, bool excludeDeleted=true)
{
if (excludeDeleted)
return query.Regions.Where(r => !r.isDeleted);
return query.Regions;
}
}
So whenever you want to query for regions you can make the following call to get only the live regions still providing an opportunity to get at the deleted ones as well.
context.Regions.GetAll();
It my be a little wonky for access the Products property, but still doable. Only issue is you would have to conform to the convention. Or extend the containing class.
someProduct.Regions.GetAll();
I hope that helps. That is what I ended up settling on because I haven't been able to find a solution to this either outside of creating more indirection. Let me know if you or anyone else comes up with a solution to this one. I'm very interested.
It looks to me like you're using a relationship between your Product and Region classes. If so, then somewhere, (the .dbml file for auto-generated LINQ-to-SQL), there exists a mapping that defines the relationship:
[Table(Name = "Product")]
public partial class Product
{
...
private EntitySet<Region> _Regions;
[Association(Storage = "_Regions")]
public EntitySet<Region> Regions
{
get { return this._Regions; }
set { this._Regions.Assign(value); }
}
...
}
You could put some logic in the accessor here, for example:
public IEnumerable<Region> Regions
{
get { return this._Regions.Where(r => !r.isDeleted); }
set { this._Regions.Assign(value); }
}
This way every access through product.Regions will return your filtered Enumerable.

Resources