Aside from the MVVM, as well as MVC patterns for the overall structure of a WPF app, how exactly do you break up the model/controller aspect of an app into subcomponents? The reason I ask is that I have no problem architecting the solution from the perspective of the patterns mentioned above, but when it comes to actually writing the backend; I feel that i'm fudging a lot of it. I end up with high quality apps from the user perspective, but my design asthetics don't allow me accept this.
To clarify; a lot of my business logic cannot be refactored into a class (or class hierarchy, with all associated interfaces) in any easy or meaningful way without having to change the entire app. I've been developing professionally for a year and a half now, so it may be an issue of inexperience; but I feel that it's still no excuse. Any pointers to this admittedly open ended question?
Edit: code request (in Silverlight)- The following is a -snippet- from a mousebuttonup handler in a drag-drop allocation application that's part of a much larger app-
I just really don't like how blunt the logic is, and hate the way that it's all completely unfactorable, since everything is getting stuffed into event handlers.
//determine if there is a previously existing allocated sale corresponding to this purchase's ID
SaleWS allocSaleExisting = colltoaddsale.FirstOrDefault(s => (s.p_TRADEID == allocPurch.TRADEID));
if (allocSaleExisting != null && allocSale.TRADEID == allocSaleExisting.TRADEID)
{
PurchaseWS allocPurchExisting = colltoadd.First(p => p.TRADEID == allocPurch.TRADEID);
//allocPurchExisting.AMOUNT += allocPurch.AMOUNT;
allocSaleExisting.AMOUNT += allocSale.AMOUNT;
allocPurchExisting.AMOUNT += allocSale.AMOUNT;
allocPurch.AMOUNT -= allocSale.AMOUNT;
colltoaddsale.Remove(allocSale);
//colltoadd.Remove(allocPurch);
}
else
{
//Create new "split" item in the data source for the source table
PurchaseWS splitAllocPurch = new PurchaseWS { COMMODITY = allocPurch.COMMODITY, CONTRACTNUMBER = allocPurch.CONTRACTNUMBER, AMOUNT = allocPurch.AMOUNT - allocSale.AMOUNT, FORM = allocPurch.FORM, GRADE = allocPurch.GRADE, LOCATION = allocPurch.LOCATION, SHIP_DATE = allocPurch.SHIP_DATE, TRADEID = allocPurch.TRADEID, UNITS = allocPurch.UNITS };
//update the source table's selecteditem datacontext with the target allocation id
allocPurch.s_TRADEID = allocSale.TRADEID;
allocSale.p_TRADEID = allocPurch.TRADEID;
allocPurch.AMOUNT = allocSale.AMOUNT;
colltoadd.Insert(colltoadd.IndexOf(allocPurch) + 1, splitAllocPurch);
}
}
Take a look at the Composite Application Guidance from the Patterns and Practices group.
It's geared specifically towards this, including using MVVM for WPF/Silverlight in large scale applications, and how to handle business logic concerns, etc.
You should also check Caliburn.
Related
As per my understanding, one of the characteristics of functional programming is the way we deal with mutable objects.
Ex:
var notFunctionalFilter = function(objectArray) {
for (var i=0; i< objectArray.length; i++) {
if (objectArray[i].active) {
objectArray.splice(i, 1);
i --;
}
}
return objectArray;
};
var functionalFilter = function(objectArray) {
var filtered = [];
for (var i=0; i< objectArray.length; i++) {
if (objectArray[i].active) {
filtered.push(objectArray[i]);
}
}
return filtered;
};
I tend to write more and more code with the "functionnal way", as it feels much cleaner (especially in JS using the beautiful LoDash library, but that's not the topic).
There actually has been quite some articles about this topic going around recently, like this very good one: A practical introduction to functional programming
But there's something that is never discussed there, it is memory management. Here are my questions:
Do we agree that functionalFilter uses more memory than notFunctionalFilter?
Should this be taken into account when deciding how to write the filter function?
Or does the garbage collector handles this perfectly (in most languages) because it is written the functional way?
Thanks
This is a slight aside but your functional filter should look like this:
var functionalFilter = function (item) {
return item.active;
};
and used like this:
var filtered = objectArray.filter(functionFilter);
The only "functional" thing about your "functionalFilter" is that it has no side effects. There is a lot more to functional programming and functional JS than that.
As for memory. Yes it uses more... maybe... sort of. I am going on the assumption that you are passing in an array of objects based on the name. Using the builtin Array.filter is going to minimize this, but in your code the extra memory footprint is tiny.
Objects in JS are passed by reference, that means that your new array is merely an array of pointers to the original objects. (Warning: this means changing them in filtered changes them in objectArray as well. Unless you do a deep clone) That array wrapper is relatively small and probably not even worth talking about in memory terms.
I have a scenario where, at certain points in my program, a thread needs to update several shared data structures. Each data structure can be safely updated in parallel with any other data structure, but each data structure can only be updated by one thread at a time. The simple, naive way I've expressed this in my code is:
synchronized updateStructure1();
synchronized updateStructure2();
// ...
This seems inefficient because if multiple threads are trying to update structure 1, but no thread is trying to update structure 2, they'll all block waiting for the lock that protects structure 1, while the lock for structure 2 sits untaken.
Is there a "standard" way of remedying this? In other words, is there a standard threading primitive that tries to update all structures in a round-robin fashion, blocks only if all locks are taken, and returns when all structures are updated?
This is a somewhat language agnostic question, but in case it helps, the language I'm using is D.
If your language supported lightweight threads or Actors, you could always have the updating thread spawn a new a new thread to change each object, where each thread just locks, modifies, and unlocks each object. Then have your updating thread join on all its child threads before returning. This punts the problem to the runtime's schedule, and it's free to schedule those child threads any way it can for best performance.
You could do this in langauges with heavier threads, but the spawn and join might have too much overhead (though thread pooling might mitigate some of this).
I don't know if there's a standard way to do this. However, I would implement this something like the following:
do
{
if (!updatedA && mutexA.tryLock())
{
scope(exit) mutexA.unlock();
updateA();
updatedA = true;
}
if (!updatedB && mutexB.tryLock())
{
scope(exit) mutexB.unlock();
updateB();
updatedB = true;
}
}
while (!(updatedA && updatedB));
Some clever metaprogramming could probably cut down the repetition, but I leave that as an exercise for you.
Sorry if I'm being naive, but do you not just Synchronize on objects to make the concerns independent?
e.g.
public Object lock1 = new Object; // access to resource 1
public Object lock2 = new Object; // access to resource 2
updateStructure1() {
synchronized( lock1 ) {
...
}
}
updateStructure2() {
synchronized( lock2 ) {
...
}
}
To my knowledge, there is not a standard way to accomplish this, and you'll have to get your hands dirty.
To paraphrase your requirements, you have a set of data structures, and you need to do work on them, but not in any particular order. You only want to block waiting on a data structure if all other objects are blocked. Here's the pseudocode I would base my solution on:
work = unshared list of objects that need updating
while work is not empty:
found = false
for each obj in work:
try locking obj
if successful:
remove obj from work
found = true
obj.update()
unlock obj
if !found:
// Everything is locked, so we have to wait
obj = randomly pick an object from work
remove obj from work
lock obj
obj.update()
unlock obj
An updating thread will only block if it finds that all objects it needs to use are locked. Then it must wait on something, so it just picks one and locks it. Ideally, it would pick the object that will be unlocked earliest, but there's no simple way of telling that.
Also, it's conceivable that an object might become free while the updater is in the try loop and so the updater would skip it. But if the amount of work you're doing is large enough, relative to the cost of iterating through that loop, the false conflict should be rare, and it would only matter in cases of extremely high contention.
I don't know any "standard" way of doing this, sorry. So this below is just a ThreadGroup, abstracted by a Swarm-class, that »hacks» at a job list until all are done, round-robin style, and makes sure that as many threads as possible are used. I don't know how to do this without a job list.
Disclaimer: I'm very new to D, and concurrency programming, so the code is rather amateurish. I saw this more as a fun exercise. (I'm too dealing with some concurrency stuff.) I also understand that this isn't quite what you're looking for. If anyone has any pointers I'd love to hear them!
import core.thread,
core.sync.mutex,
std.c.stdio,
std.stdio;
class Swarm{
ThreadGroup group;
Mutex mutex;
auto numThreads = 1;
void delegate ()[int] jobs;
this(void delegate()[int] aJobs, int aNumThreads){
jobs = aJobs;
numThreads = aNumThreads;
group = new ThreadGroup;
mutex = new Mutex();
}
void runBlocking(){
run();
group.joinAll();
}
void run(){
foreach(c;0..numThreads)
group.create( &swarmJobs );
}
void swarmJobs(){
void delegate () myJob;
do{
myJob = null;
synchronized(mutex){
if(jobs.length > 0)
foreach(i,job;jobs){
myJob = job;
jobs.remove(i);
break;
}
}
if(myJob)
myJob();
}while(myJob)
}
}
class Jobs{
void job1(){
foreach(c;0..1000){
foreach(j;0..2_000_000){}
writef("1");
fflush(core.stdc.stdio.stdout);
}
}
void job2(){
foreach(c;0..1000){
foreach(j;0..1_000_000){}
writef("2");
fflush(core.stdc.stdio.stdout);
}
}
}
void main(){
auto jobs = new Jobs();
void delegate ()[int] jobsList =
[1:&jobs.job1,2:&jobs.job2,3:&jobs.job1,4:&jobs.job2];
int numThreads = 2;
auto swarm = new Swarm(jobsList,numThreads);
swarm.runBlocking();
writefln("end");
}
There's no standard solution but rather a class of standard solutions depending on your needs.
http://en.wikipedia.org/wiki/Scheduling_algorithm
I've got a designer that relies on the existence of other solution items. If one of those items is deleted the designer crashes and you have to edit as XML to fix. Not exactly user friendly.
I do, however, have the DTE object representing the instance of Visual Studio, as well as the ProjectItems I am dependent on.
Is it possible to, somewhere in the depths of the DTE, register a listener for the deletion of that ProjectItem? And, if so, How would I do it?
It looks like the culprit here is garbage collection. I found the following two event sets behaved identically.
Events2 events2 = dte.Events as Events2;
if (events2 != null)
{
this.projectItemsEvents = events2.ProjectItemsEvents;
this.projectItemsEvents.ItemAdded += this.ProjectItemsEvents_ItemAdded;
this.projectItemsEvents.ItemRemoved += this.ProjectItemsEvents_ItemRemoved;
this.projectItemsEvents.ItemRenamed += this.ProjectItemsEvents_ItemRenamed;
}
this.csharpProjectItemsEvents =
dte.Events.GetObject("CSharpProjectItemsEvents") as ProjectItemsEvents;
if (this.csharpProjectItemsEvents != null)
{
this.csharpProjectItemsEvents.ItemAdded += this.CSharpProjectItemsEvents_ItemAdded;
this.csharpProjectItemsEvents.ItemRemoved += this.CSharpProjectItemsEvents_ItemRemoved;
this.csharpProjectItemsEvents.ItemRenamed += this.CSharpProjectItemsEvents_ItemRenamed;
}
The key to both was making sure to keep a reference to the events object in the subscriber. Once I added the reference, they behaved like I expected.
private ProjectItemsEvents projectItemsEvents;
private ProjectItemsEvents csharpProjectItemsEvents;
Check out this FAQ article which explains how to register for ProjectItems events (including ItemDeleted).
How much information hiding is necessary? I have boilerplate code before I delete a record, it looks like this:
public override void OrderProcessing_Delete(Dictionary<string, object> pkColumns)
{
var c = Connect();
using (var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM orders WHERE order_id = :_order_id", c)
{ Parameters = { {"_order_id", pkColumns["order_id"]} } } )
{
var count = (long)cmd.ExecuteScalar();
// deletion's boilerplate code...
if (count == 0) throw new RecordNotFoundException();
else if (count > 1) throw new DatabaseStructureChangedException();
// ...boiler plate code
}
// deleting of table(s) goes here...
}
NOTE: boilerplate code is code-generated, including the "using (var cmd = new NpgsqlCommand( ... )"
But I'm seriously thinking to refactor the boiler plate code, I wanted a more succint code. This is how I envision to refactor the code (made nicer with extension method (not the sole reason ;))
using (var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM orders WHERE order_id = :_order_id", c)
{ Parameters = { {"_order_id", pkColumns["order_id"]} } } )
{
cmd.VerifyDeletion(); // [EDIT: was ExecuteWithVerification before]
}
I wanted the executescalar and the boilerplate code to goes inside the extension method.
For my code above, does it warrants code refactoring / information hiding? Is my refactored operation looks too opaque?
I would say that your refactor is extremely good, if your new single line of code replaces a handful of lines of code in many places in your program. Especially since the functionality is going to be the same in all of those places.
The programmer coming after you and looking at your code will simply look at the definition of the extension method to find out what it does, and now he knows that this code is defined in one place, so there is no possibility of it differing from place to place.
Try it if you must, but my feeling is it's not about succinctness but whether or not you want to enforce the behavior every time or most of the time. And by extension, if the verify-condition changes that it would likely change across the board.
Basically, reducing a small chunk of boiler-plate code doesn't necessarily make things more succinct; it's just one more bit of abstractness the developer has to wade through and understand.
As a developer, I'd have no idea what "ExecuteWithVerify" means. What exactly are we verifying? I'd have to look it up and remember it. But with the boiler-plate code, I can look at the code and understand exactly what's going on.
And by NOT reducing it to a separate method I can also tune the boiler-plate code for cases where exceptions need to be thrown for differing conditions.
It's not information-hiding when you extract or refactor your code. It's only information-hiding when you start restricting access to your extension definition after refactoring.
"new" operator within a Class (except for the Constructor) should be Avoided at all costs. This is what you need to refactor here.
I'm working with WPF and I'm developing a complex usercontrol, which is composed of a tree with rich functionality etc.
For this purpose I used a View-Model design pattern, because some operations couldn't be achieved directly in WPF. So I take the IHierarchyItem (which is a node and pass it to this constructor to create a tree structure)
private IHierarchyItemViewModel(IHierarchyItem hierarchyItem, IHierarchyItemViewModel parent)
{
this.hierarchyItem = hierarchyItem;
this.parent = parent;
List<IHierarchyItemViewModel> l = new List<IHierarchyItemViewModel>();
foreach (IHierarchyItem item in hierarchyItem.Children)
{
l.Add(new IHierarchyItemViewModel(item, this));
}
children = new ReadOnlyCollection<IHierarchyItemViewModel>(l);
}
The problem is that this constructor takes about 3 seconds !! for 200 items on my dual-core.
Am I doing anythig wrong or recursive constructor call is that slow?
Thank you very much!
OK I found a non recursive version by myself, although it uses the Stack.
It traverses the whole tree:
Stack<MyItem> stack = new Stack<MyItem>();
stack.Push(root);
while (stack.Count > 0)
{
MyItem taken = stack.Pop();
foreach (MyItem child in taken.Children)
stack.Push(MyItem);
}
There should be nothing wrong with a recursive implementation of a tree, especially for such a small number of items. A recursive implementation is sometimes less space efficient, and slightly less time efficient, but the code clarity often makes up for it.
It would be useful for you to perform some simple profiling on your constructor. Using one of the suggestions from: http://en.csharp-online.net/Measure_execution_time you could indicate for yourself how long each piece is taking.
There is a possibility that one piece in particular is taking a long time. In any case, that might help you narrow down where you are really spending the time.