问:
How to delete an object when other things reference it (and not making the code full of inter-dependencies)
The situation:

In my program, there are a list of cues. To call a cue at a certain time, there are objects called Triggers. Cues have many public methods that allow them, among other things, to be "fired" (which causes them to perform an action). Triggers "fire" cues when they are activated. They do this by taking a reference to the Cue and then calling Cue.fire(). The triggers are all stored in a class called TriggerManager which keeps them in an array list. Cues are part of a linked list with eachother. So, in summery: Triggers know about Cues, but Cues don't know about triggers; Triggers call cues at certain times.

The problem:

When I remove a Cue from the linked list, it's still "alive"/hasn't been garbage collected because there's a Trigger with a reference to it. The natural thing would be to delete the Trigger, but that creates a host of issues that need to be solved:

The main one is this: Since, the Cue doesn't know about the Trigger that references it, how do I get it to be deleted. (Especially since its referenced by a TriggerManager class). There has to be a way to do this without making Cues dependent on Triggers and Triggers dependent on their TriggerManagers OR Cues dependent on TriggerManagers, which should have nothing to do with Cues (Giving everything a bidirectional reference to each other will make the code complicated and hard to keep track of)

Question: Is there a solution that will fix my problem while keeping the code manageable? Is my design inherently flawed? If so, how do I fix it?

答:
The linked list isn't really helping you here.  Replace it with a CueManager that

Contains the list of Cues

Maps the Cues to their respective Triggers

The CueManager should then control the life-cycle of the Cues--adding them and removing them from their respective triggers.

```<code>interface CueManager {
  public addCueToTrigger(Cue, Trigger);
  public removeCueFromTrigger(Cue, Trigger);
  public deleteCue(Cue);
}
</code>```

Body:
The linked list isn't really helping you here.  Replace it with a CueManager that

Contains the list of Cues

Maps the Cues to their respective Triggers

The CueManager should then control the life-cycle of the Cues--adding them and removing them from their respective triggers.

interface CueManager {
  public addCueToTrigger(Cue, Trigger);
  public removeCueFromTrigger(Cue, Trigger);
  public deleteCue(Cue);
}


问:
Designing a robust architecture for multiple export types?
I'm looking for patterns or architectural guidance for an upcoming feature I'm designing. Basically, it's an export feature with multiple export targets, and I'm looking to find a way to make it generic enough where plugging in new export targets don't require a lot of core changes. By export targets, I'm simply referring to different types of output, whether that be PDFs, PowerPoint presentations, Word documents, RSS, etc. I have a base set of data, which is represented in JSON and XML. This data are used to construct images (using any number or export types [e.g., PNG, JPG, GIF, etc), graphs, textual representations, tables, and more.

I'm trying to find a way to abstract all the rendering and layout into some kind of rendering or layout engine that handles the addition of further export targets. Any help/suggestions/resources as to how to approach this would be greatly appreciated. Thanks in advance.

For a pictorial representation of what I'm trying to achieve.

答:
For me, the way to go would be interfaces and a Factory. One that returns references to interfaces behind which various classes can hide. The classes that do the actual grunt work all need to be registered with the Factory so it knows which class to instantiate given a set of parameters.

Note: instead of interfaces you could also use abstract base classes, but the drawback there is that for single inheritance languages it limits you to a single base class.

```<code>TRepresentationType = (rtImage, rtTable, rtGraph, ...);

Factory.RegisterReader(TJSONReader, 'json');
Factory.RegisterReader(TXMLReader, 'xml');

Factory.RegisterWriter(TPDFWriter, 'pdf');
Factory.RegisterWriter(TPowerPointWriter, 'ppt');
Factory.RegisterWriter(TWordWriter, 'doc');
Factory.RegisterWriter(TWordWriter, 'docx');

Factory.RegisterRepresentation(TPNGImage, rtImage, 'png');
Factory.RegisterRepresentation(TGIFImage, rtImage, 'gif');
Factory.RegisterRepresentation(TJPGImage, rtImage, 'jpg');
Factory.RegisterRepresentation(TCsvTable, rtTable, 'csv');
Factory.RegisterRepresentation(THTMLTable, rtTable, 'html');
Factory.RegisterRepresentation(TBarChart, rtTGraph, 'bar');
Factory.RegisterRepresentation(TPieChart, rtTGraph, 'pie');
</code>```

Code is in Delphi (Pascal) syntax as that is the language with which I am most familiar.

After all implementing classes are registered with the factory, you should be able to request an interface reference to an instance of such a class. For example:

```<code>Factory.GetReader('SomeFileName.xml');
Factory.GetWriter('SomeExportFileName.ppt');
Factory.GetRepresentation(rtTable, 'html');
</code>```

should return an IReader reference to an instance of TXMLReader; an IWriter reference to an instance of TPowerPointWriter and an IRepresentation reference to an instance of THTMLTable.

Now all the rendering engine needs to do, is tie everything together:

```<code>procedure Render(
  aDataFile: string;
  aExportFile: string;
  aRepresentationType: TRepresentationType;
  aFormat: string;
  );
var
  Reader: IReader;
  Writer: IWriter;
  Representation: IRepresentation;
begin
  Reader := Factory.GetReaderFor(aDataFile);
  Writer := Factory.GetWriterFor(aExportFile);
  Representation := Factory.GetRepresentationFor(aRepresentationType, aFormat);

  Representation.ConstructFrom(Reader);
  Writer.SaveToFile(Representation);
end;
</code>```

The IReader interface should provide methods to read the data needed by IRepresentation implementers to construct the representation of the data. Similarly IRepresentation should provide methods that IWriter implementers need to export the data representation to the requested export file format.

Assuming the data in your files is tabular in nature, IReader and its supporting interfaces could look like:

```<code>IReader = interface(IInterface)
  function MoveNext: Boolean;
  function GetCurrent: IRow;
end;

IRow = interface(IInterface)
  function MoveNext: Boolean;
  function GetCurrent: ICol;
end;

ICol = interface(IInterface)
  function GetName: string;
  function GetValue: Variant;
end;
</code>```

Iterating over a table would then be a matter of

```<code>while Reader.MoveNext do
begin
  Row := Reader.GetCurrent;
  while Row.MoveNext do
  begin
    Col := Row.GetCurrent;
    // Do something with the column's name or value
  end;
end;
</code>```

As the representations can be images, graphs and textual in nature, IRepresentation would probably have similar methods to IReader to traverse a constructed table and it would have methods to get the images and graphs, for example as a stream of bytes. It would be up to the IWriter implementers to encode the table values and the image/graph bytes as required by the export target.

ContentLicense: CC BY-SA 3.0

Body:
For me, the way to go would be interfaces and a Factory. One that returns references to interfaces behind which various classes can hide. The classes that do the actual grunt work all need to be registered with the Factory so it knows which class to instantiate given a set of parameters.

Note: instead of interfaces you could also use abstract base classes, but the drawback there is that for single inheritance languages it limits you to a single base class.

TRepresentationType = (rtImage, rtTable, rtGraph, ...);

Factory.RegisterReader(TJSONReader, 'json');
Factory.RegisterReader(TXMLReader, 'xml');

Factory.RegisterWriter(TPDFWriter, 'pdf');
Factory.RegisterWriter(TPowerPointWriter, 'ppt');
Factory.RegisterWriter(TWordWriter, 'doc');
Factory.RegisterWriter(TWordWriter, 'docx');

Factory.RegisterRepresentation(TPNGImage, rtImage, 'png');
Factory.RegisterRepresentation(TGIFImage, rtImage, 'gif');
Factory.RegisterRepresentation(TJPGImage, rtImage, 'jpg');
Factory.RegisterRepresentation(TCsvTable, rtTable, 'csv');
Factory.RegisterRepresentation(THTMLTable, rtTable, 'html');
Factory.RegisterRepresentation(TBarChart, rtTGraph, 'bar');
Factory.RegisterRepresentation(TPieChart, rtTGraph, 'pie');

Code is in Delphi (Pascal) syntax as that is the language with which I am most familiar.

After all implementing classes are registered with the factory, you should be able to request an interface reference to an instance of such a class. For example:

Factory.GetReader('SomeFileName.xml');
Factory.GetWriter('SomeExportFileName.ppt');
Factory.GetRepresentation(rtTable, 'html');

should return an IReader reference to an instance of TXMLReader; an IWriter reference to an instance of TPowerPointWriter and an IRepresentation reference to an instance of THTMLTable.

Now all the rendering engine needs to do, is tie everything together:

procedure Render(
  aDataFile: string;
  aExportFile: string;
  aRepresentationType: TRepresentationType;
  aFormat: string;
  );
var
  Reader: IReader;
  Writer: IWriter;
  Representation: IRepresentation;
begin
  Reader := Factory.GetReaderFor(aDataFile);
  Writer := Factory.GetWriterFor(aExportFile);
  Representation := Factory.GetRepresentationFor(aRepresentationType, aFormat);

  Representation.ConstructFrom(Reader);
  Writer.SaveToFile(Representation);
end;

The IReader interface should provide methods to read the data needed by IRepresentation implementers to construct the representation of the data. Similarly IRepresentation should provide methods that IWriter implementers need to export the data representation to the requested export file format.

Assuming the data in your files is tabular in nature, IReader and its supporting interfaces could look like:

IReader = interface(IInterface)
  function MoveNext: Boolean;
  function GetCurrent: IRow;
end;

IRow = interface(IInterface)
  function MoveNext: Boolean;
  function GetCurrent: ICol;
end;

ICol = interface(IInterface)
  function GetName: string;
  function GetValue: Variant;
end;

Iterating over a table would then be a matter of

while Reader.MoveNext do
begin
  Row := Reader.GetCurrent;
  while Row.MoveNext do
  begin
    Col := Row.GetCurrent;
    // Do something with the column's name or value
  end;
end;

As the representations can be images, graphs and textual in nature, IRepresentation would probably have similar methods to IReader to traverse a constructed table and it would have methods to get the images and graphs, for example as a stream of bytes. It would be up to the IWriter implementers to encode the table values and the image/graph bytes as required by the export target.


问:
naming convention for different types of functions (use prefixes or suffixes?)
Does anyone have suggestions for naming conventions for different types of functions, particularly wrapper functions that need to connect to and disconnect from the database vs. wrapper functions that are passed a db link and don't need to connect and disconnect?

The project on which I am working has these types of functions (among other types):

wrapper functions that need to connect to the database, then call other functions, then disconnect

wrapper functions that are passed a db link and call other functions (these functions don't need to connect to the db, that has already been done)

Has anyone worked in a similar environment?  Did you follow any naming conventions to distinguish between these wrapper functions that need to connect vs. being passed a db link, such as using a particular prefix or suffix?

答:
Fix the Blueprint, Not the Walls

Feeling a need to have these markers seems like a code smell. It doesn't appear to me to be a matter of naming convention but of architectural (and behavioral) design. Though obviously having a good naming convention will be important in making that design usable.

Solutions

There are various approaches, but here are 2 possibles options.

1 Class per DB Usage Approach (easy to do, but not recommended)

Have 2 separate classes to deal with both scenarios, thus effectively taking the distinction one level higher up the chain. For instance, something like (in no particular language):

```<code>class CustomerDirectDAO {

  save() {}

}

class CustomerIndirectDAO {

  save(Connection c) {}

}
</code>```

As mentioned, this would allow you to take the issue of selecting the right problem one level up your design chain. However, you can obviously the it looks tedious, and that you still need a distinction for each approach. Also, the first class probably does in essence what the second class does with just the extra step of creating the connection and invoking it.

This isn't so great.

1 Data Class, and 1 DB Connection Supplier/Factory

It would be better to have a class that always requires to be passed a connection object and another class constructing and supplying them. That'd seem a better way, and would allow to swap in place implementations of the connection objects that could originate from different suppliers.

A wrapper Connection object could also be supplied only once to the constructor, where the wrapper will check for the connection's status and recreate one if necessary.

For instance (in no particular language):

```<code>class Customer {

  save(ConnectionWrapper c) {}

  // (or pass the wrapper object only once to the constructor,
  // as the wrapper would automatically check to reconnect the
  // connection if invalid)

}

class ConnectionWrapper<T extends Connection> {

  T get() {}; // gets the wrapped connection or returns a newly created one

}

class ConnectionFactory<T extends Connection> {

  ConnectionWrapper<T> create() {}

}
</code>```

There are dozens of ways to achieve this, and you may pick whichever seems more applicable to you.

The approach above uses a single data-representation class allowing to switch classes used for storage. But another approach is to take the problem from the reverse angle, for instnace with this DAO pattern, where you can see a similar  approach to allow for swappable implementations of the backend without using method prefixes, but require 2 concrete implementations of your data object:

More on the topic with approaches for DAO on Wikipedia and DAO for JEE applications.

Body:
Fix the Blueprint, Not the Walls

Feeling a need to have these markers seems like a code smell. It doesn't appear to me to be a matter of naming convention but of architectural (and behavioral) design. Though obviously having a good naming convention will be important in making that design usable.

Solutions

There are various approaches, but here are 2 possibles options.

1 Class per DB Usage Approach (easy to do, but not recommended)

Have 2 separate classes to deal with both scenarios, thus effectively taking the distinction one level higher up the chain. For instance, something like (in no particular language):

class CustomerDirectDAO {

  save() {}

}

class CustomerIndirectDAO {

  save(Connection c) {}

}

As mentioned, this would allow you to take the issue of selecting the right problem one level up your design chain. However, you can obviously the it looks tedious, and that you still need a distinction for each approach. Also, the first class probably does in essence what the second class does with just the extra step of creating the connection and invoking it.

This isn't so great.

1 Data Class, and 1 DB Connection Supplier/Factory

It would be better to have a class that always requires to be passed a connection object and another class constructing and supplying them. That'd seem a better way, and would allow to swap in place implementations of the connection objects that could originate from different suppliers.

A wrapper Connection object could also be supplied only once to the constructor, where the wrapper will check for the connection's status and recreate one if necessary.

For instance (in no particular language):

class Customer {

  save(ConnectionWrapper c) {}

  // (or pass the wrapper object only once to the constructor,
  // as the wrapper would automatically check to reconnect the
  // connection if invalid)

}

class ConnectionWrapper<T extends Connection> {

  T get() {}; // gets the wrapped connection or returns a newly created one

}

class ConnectionFactory<T extends Connection> {

  ConnectionWrapper<T> create() {}

}

There are dozens of ways to achieve this, and you may pick whichever seems more applicable to you.

The approach above uses a single data-representation class allowing to switch classes used for storage. But another approach is to take the problem from the reverse angle, for instnace with this DAO pattern, where you can see a similar  approach to allow for swappable implementations of the backend without using method prefixes, but require 2 concrete implementations of your data object:

More on the topic with approaches for DAO on Wikipedia and DAO for JEE applications.


问:
Is there an equivalent term for Desktop Monitoring Recorder such as NVR or DVR?
Just like NVR (Network Video Recorder) and DVR (Digital Video Recorder), I was wondering if there's a term / acronym for Desktop Monitoring Recorder? Perhaps DMR? I can't find any standard terms for this type of system.

I'm writing a system which is just like an NVR but records / monitors computer desktops instead. It's not a "screen thief" or "desktop spy" or any type of malware - it's a surveillance system, only for computers rather than cameras. In the end, it will do things such as primarily monitoring/recording screens, watching for mouse movement when the computer user shouldn't be there, and more. There are also other commands such as taking control of the screen, executing remote shutdown / restart, posting messages to the user's screen, and more.

Is there a particular standard term or acronym for the recording software side of this?

答:
Over the Shoulder and Behind the Keys (OSBK) *

*contrived, no such system is known to exist by this name

Introduction to Audits

Past Announcement for a Presentation: Video Surveillance Technologies for
Retail Security (VISITORS); retail video monitoring for among
other reasons, loss prevention

Brochure: CISCO Video Retail Video Surveillance, contains intro
to Cisco Smart+Connected Retail Network; I think IBM and Oracle have or could easily offer similar systems, not to necessarily single out Cisco.

Such systems exist, but as I have never been on the design end of such systems, I cannot suggest how the names came about.  At essence though, they are fully integrated audit and control systems.

The operating environment featured a complete audit and control mechanism that monitored all system and user activity.  In addition, a physical access control system and a high-resolution/low sampling rate camera system monitored the occupants or nearby onlookers of the computer.

However, because the system was for highly sensitive or secret information, they never recorded the screen directly (without explicit cause).  This allowed some separation and protection from routine review of either footage or logs by access control personnel; yet, still provided full and precise forensic capability if the need arose.

When the need arose, it was merely a matter of synchronizing the two streams together during playback to recreate the conditions at the time in question and validate who, when, where, how, and what occurred.  The why was often left to deduction or admission.

Why was it setup like this?  The concern of system access and audit control was a separate concern from physical access.  By keeping the concerns separate, each functional and responsible monitoring agent only had to be particularly vigilant and knowledgeable of their realm.  Often times because the information was highly sensitive or secret, each monitoring agent did not have a 'need to know', and by keeping the aspects separate, it reduced the risk that they would inadvertently gain too much knowledge of the subject material being monitored.

As a user, I would find it difficult to accept working in conditions where real-time integration of all the monitoring information occurred without significant cause, and I suspect that it would be subject to greater risk of unchecked abuse or even misuse.  I am not suggesting it is a bad idea, just that it would be a slim market, and reputation/trust would probably be an overwhelming factor.


问:
Are there any Clojure libraries for p2p?
I'm a web developer, but lately I have been learning Clojure and now I'm interested in creating a p2p application. And since Clojure is a general purpose language, I guess I can just use that.

Any suggestions?

答:
Below are a couple links I just found:

Mist helps building distributed services by offering a UDP multiplexer, a Kademlia overlay and a simple pubsub protocol. At least that's what this gist says, and the code should be on github.

Nightweb can help building P2P apps on Android, and could be at least an inspiration.

As I said I just found these on the net, I never used any of these and don't even know how useful/usable these are. Also, this is not really an answer but this resource page on P2P created by a clojure programmer might be of interest.


问:
Which benchmarking software would you use to evaluate the performance of your development rig?
I have been tasked with evaluating a new PC for our dev team that is spec'd only slightly better than our current models.

Could anyone recommend appropriate benchmarking software that would be useful to emulate typical development tasks?

答:
I'd use a benchmark consisting of builds, integration and performance tests, and other development activities most frequently run on machine's of developers working in your organization.

Build time is important in day-to-day software development activities and if it's too long, build may become a bottleneck.  Suppose the build runs 15 minutes and occupies all of some machine's resources.  With a better machine, it takes only 5 minutes.  The better machine thus creates some value added and I want the benchmark to measure this value.

The same reasoning can be applied to integration/performance tests.  If they run too slowly, developers tend to run them less frequently, lengthening feedback loops.  Again, value can be added by running them faster.  A benchmark consisting of a sample of such tests would measure the value.

If your faster machine uses SSD while the slower machine uses HDD, such benchmarks should let you measure how much faster your faster machine is at your usual tasks.  Simply saying "SSD is faster than HDD" doesn't answer the question.

ContentLicense: CC BY-SA 2.5


问:
MVC seems to create dependencies that just "don't feel right"
I might be misunderstanding MVC, so forgive me if that is the case.

This is my program structure (Java/Swing): I have a JTable (View) that is pointed to by a custom linked list (Model). When the user tries to add something to the JTable, the action listener (Controller) updates the linked list (Model) which updates the JTable (View).

Here's my issue: The linked list should be able to function independently of the JTable, but it doesn't. Let's say I decided to get rid of the user interface and just use the linked list for internal stuff within the program (The linked list has other properties and functions outside the scope of MVC). That should be able to work, because the linked list's FUNCTION is independent of the JTable's function, yet I would have to edit a lot of code to do so (or have a bunch of code that no longer does anything) because of MVC.

So am I misunderstanding MVC completely, just a little bit, or are the dependencies a price I have to pay?

NOTE: This is a simplified view of my project. In real life, there are other objects in the model and more than just a JTable in my interface. Also, the linked list has other thigns that get updates other than the number of objects.

答:
A model is view-agnostic, so your feelings are pointing you into the right direction.

The controller decides, which model and which view to use. It injects the model into the view, and optionally registers the view as an Observer for the model. Then the controller passes control to the view.

Then the model is changed by the controller, usually invoked by an event in the view. If the Observer pattern is used, the model notifies the view directly, which re-renders itself without further controller interaction, otherwise the controller gives control back to the view.


答:
My first thought was some sort of publish/subscribe model and/or callbacks, but that violates your requirement to avoid bidirectional references.

An alternative might be to add a "cueIsAlive" flag to the Cue.  Set it to true in the constructor, have the RemoveFromLinkedList() call set it to false, and use it in your Cue.Fire() method:

```<code>public void Fire() {
    if (this.cueIsAlive) {
        ... execute Fire code ...
    }
}
</code>```

I'm not sure if this would be considered a zombie object or not - the basic idea is to make it harmless until such time that it can be garbage collected.

Title: How to delete an object when other things reference it (and not making the code full of inter-dependencies)

Body:
The situation:

In my program, there are a list of cues. To call a cue at a certain time, there are objects called Triggers. Cues have many public methods that allow them, among other things, to be "fired" (which causes them to perform an action). Triggers "fire" cues when they are activated. They do this by taking a reference to the Cue and then calling Cue.fire(). The triggers are all stored in a class called TriggerManager which keeps them in an array list. Cues are part of a linked list with eachother. So, in summery: Triggers know about Cues, but Cues don't know about triggers; Triggers call cues at certain times.

The problem:

When I remove a Cue from the linked list, it's still "alive"/hasn't been garbage collected because there's a Trigger with a reference to it. The natural thing would be to delete the Trigger, but that creates a host of issues that need to be solved:

The main one is this: Since, the Cue doesn't know about the Trigger that references it, how do I get it to be deleted. (Especially since its referenced by a TriggerManager class). There has to be a way to do this without making Cues dependent on Triggers and Triggers dependent on their TriggerManagers OR Cues dependent on TriggerManagers, which should have nothing to do with Cues (Giving everything a bidirectional reference to each other will make the code complicated and hard to keep track of)

Question: Is there a solution that will fix my problem while keeping the code manageable? Is my design inherently flawed? If so, how do I fix it?

Body:
My first thought was some sort of publish/subscribe model and/or callbacks, but that violates your requirement to avoid bidirectional references.

An alternative might be to add a "cueIsAlive" flag to the Cue.  Set it to true in the constructor, have the RemoveFromLinkedList() call set it to false, and use it in your Cue.Fire() method:

public void Fire() {
    if (this.cueIsAlive) {
        ... execute Fire code ...
    }
}

I'm not sure if this would be considered a zombie object or not - the basic idea is to make it harmless until such time that it can be garbage collected.


问:
Request - Reply vs Publish-subscribe
We are working on a integration between two large systems.
System A is a database with employee data, and System B is an external system that is used for the daily contact with the customers (i.e meetings, locationdata,work order,work status, and so on). We will deploy a ESB in the middle.

There are 3 instances of System A, and 1 instance of System B.
This is due to legal restrictions and we cannot have all System A data in the same database.

In System B we have 20-30 active contacts each day, where some of the data from System A is used continously.

We need to update meeting, location, and work status in System B throughout the day. And have two proposed solutions for integrating these systems.

Solution A:
Publish-Subscribe - System A sends out update messages (This is based on HL7 ADT Standards) and the instance of System B picks up the data that is for them. This is done as broadcast and will generate 1000-10000 messages pr day. It will send information from System A on all employees, thus generating a message for every employee in System A (1,2,3). There is only a subset of employees from System A that is "active" and interesting for updates in System B. But messages will flow on ALL employees since data is updated by other systems aswell.

Soltion B:
System B ask for updated information through a request-reply solution. Will generate empty calls, but will only ask for the employees "active" in System B on given day.

Comments on solutions? Pros - Cons?
What is the most infrastructure "heavy" solution between these two?

Hope there is someone out there who could give me som pointers  :)

答:
If updates only flow from A to B, then B could just cache data from A. B should only read data from A when it needs to and no need for A to send data (publish) without being asked. Then you have to manage what to do with stale cache (A has been updated since last time B updated). But what if B only needs data when A has been updated? B can periodically ask A if there's any update since B last check, and only get updated entities.

R. Fielding gave comment about why pub/sub isn't scalable here: http://roy.gbiv.com/untangled/2008/paper-tigers-and-hidden-dragons which where I get my answer from.

Title: Request - Reply vs Publish-subscribe


答:
Solution B only works if you request the data from System A every time it is required by System B. Otherwise you cannot guarantee the information is up to date. This is not as bad as it sounds and is in fact the basis of all SOA architectures.

The decision of whether to push (Solution A) or pull (Solution B) depends on the ratio of updates in system A to the number of queries in System B.

Where you have lots of updates in system A versus a few queries in System B then "pull" is the obvious choice.

Where you have relatively few updates in system A and lots of queries in System B then "push" is the way to go.

Where you have lots of updates and lots of queries either choice is equally good (or bad!).

Title: Request - Reply vs Publish-subscribe

Body:
We are working on a integration between two large systems.
System A is a database with employee data, and System B is an external system that is used for the daily contact with the customers (i.e meetings, locationdata,work order,work status, and so on). We will deploy a ESB in the middle.

There are 3 instances of System A, and 1 instance of System B.
This is due to legal restrictions and we cannot have all System A data in the same database.

In System B we have 20-30 active contacts each day, where some of the data from System A is used continously.

We need to update meeting, location, and work status in System B throughout the day. And have two proposed solutions for integrating these systems.

Solution A:
Publish-Subscribe - System A sends out update messages (This is based on HL7 ADT Standards) and the instance of System B picks up the data that is for them. This is done as broadcast and will generate 1000-10000 messages pr day. It will send information from System A on all employees, thus generating a message for every employee in System A (1,2,3). There is only a subset of employees from System A that is "active" and interesting for updates in System B. But messages will flow on ALL employees since data is updated by other systems aswell.

Soltion B:
System B ask for updated information through a request-reply solution. Will generate empty calls, but will only ask for the employees "active" in System B on given day.

Comments on solutions? Pros - Cons?
What is the most infrastructure "heavy" solution between these two?

Hope there is someone out there who could give me som pointers  :)


问:
How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?
I'm writing a small program that I want to be able to link with other programs.  I also intend to run it from a command line interface, and maybe later with a GUI interface.

How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?

Distribute it as a library and

Dynamically link for GUI and command line interfaces

Statically link for a stand alone binary

答:
I would write it as a library (eg, DLL or JAR) and write the console app to talk to it. That way in the future you could write a GUI for it.

Or for more flexibility you could write it as a web service and talk to it that way.


问:
Tic tac toe class diagram
I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP.

I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision.

("Joueur" means "Player", "PlancheDeJeu" means "Game board")

Given this diagram, according to the Expert, Low coupling and Strong cohesion design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea.

What would be the best way to go here ?

Thanks !

答:
I see no reason why the player themselves have to keep score of the game- in fact I think that the game board itself should keep score, otherwise which player keeps score? The human, or the computer? Do they both keep their own score? If so, that's duplication of data, which is never good, because you could end up with a case where those scores don't match and then you've got to figure out which one is right. I would keep the score on the actual game board, which then both the players and the system have access to!

If you really have some sort of objection with keeping the score on the board, you might have to create another class for storing data, which is very common in programs, which then all parties would have access to in a semi-static fashion, either through a singleton, or some sort of thread safe accessor/setter

Title: Tic tac toe class diagram


问:
Use case decomposition for class registration system
I am currently working on refactoring a summer camp registration system to include some new features and will also be using it as the basis for a new after-school class registration system.

For this new version of the system, I want to start out by writing use case descriptions for the registration process (and ultimately I plan to document all the use cases).

I understand that the purpose of a use case is to accomplish a user's goal, but I'm still not sure how the registration process should be divided into use cases.

Here are the options I've been thinking about:

One big "Register Student(s) For Classes" use case

Divide it into separate use cases: "Enter Student Information", "Select Classes", "Pay for Registrations"

Have separate use cases but also have a "Register Student(s) For Classes" use case which "includes" the more granular use cases

Another factor to consider is timing: parents may want to enter their students' basic information (name, age, etc.) prior to the time when registration begins, but of course some parents will complete the whole registration process in one sitting. Also, payment won't always immediately follow class selection; in some cases parents will be allowed to complete their payment later (within a 48 hour window).

I read some articles about use cases on Alistair Cockburn's website but I'm still confused as to what the guidelines are for dividing up use cases in a case like this.

My inclination is to go with option 3 since the system will have a wizard interface that could potentially guide the user through the registration from start to end, accomplishing the "user goal" of registering his/her student(s) for classes, but the "included" use cases could also be initiated on their own. I was also wondering if I should have a separate "Modify Class Selections" use case for the case when the parent logs back into the system later and changes class selections on behalf of the student, or whether that should just be an alternative scenario of the "Select Classes" use case.

What would you recommend, and why? What guidelines should be used in general when analyzing use case boundaries, beyond the idea of a "user goal"?

Update:

I found this quote from the first chapter of Alistair Cockburn's book to be helpful:

Depending on the level of view needed at the time, the writer will
  choose to describe a multi-sitting or summary goal, a single-sitting or
  user goal, or a part of a user goal, or subfunction. Communicating
  which of these is being described is so important that my students
  have come up with two different gradients to describe them: by height
  relative to sea level (above sea level, at sea level, underwater), and
  by color (white, blue, indigo).

It seems to me that "Register Student(s)" is a summary level goal, since it could potentially take multiple sittings to complete. The line is blurred in this case, but I think this idea of a summary use case suggests that my approach #3 above is a reasonable one.

答:
In short, there's no real right or wrong answer here: it's one of those things where its up to your work style and work flow. Personally, I like to take all the users that could possibly ever use my system, and then list them out.

Parent

Student

Teacher

Administrator

Then, I write ALL the different things those users would want to accomplish for my system

Parent

Register Child/Children (Could be more than one child)

Student

Register Themselves

Teacher

View student's who've registered for their class

Administrator

Register Students

Move student's to different sections

Finally, each one of those behaviors becomes a use case, with main flows, and alternate flows, such as a parent entering an invalid class, or an administrator trying to move a student into a full section. You may find that some of these use cases are very similair and that's fine, feel free to combine them. At least this way you know you aren't missing any!


答: If your "program" has two different processes you can use a named pipe.</p>

Body:
I'm writing a small program that I want to be able to link with other programs.  I also intend to run it from a command line interface, and maybe later with a GUI interface.

How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?

Distribute it as a library and

Dynamically link for GUI and command line interfaces

Statically link for a stand alone binary


答:
If you're wondering whether to link statically or dynamically you have to first determine how your application will be used.

Dynamic linking is less resource intensive, so this is a good option if your application will be used by many other processes.
Dynamic linking also allows you to propagate bug fixes without having to reship things.
Static linking is good for small applications running in limited environments, because they have larger resource footprints.

However, static libraries may be easier to deploy, since there are the application won't have file dependencies like will dynamically linked libraries.

To summarise, it really all depends what you want your code to be used for, how, by whom, and in what environment.
Also, the statically linked option gives you a slight performance increase at startup (but for all practical purposes that is negligible).

I would suggest for most scenarios you go with linking dynamically.

Hope this answers the question. If you need more information, there are plenty of resources on the differences between static and dynamic linking and the advantages/disadvantages of both.

Happy coding!

Title: How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
There's plenty of jobs for people doing COBOL, and .NET will stick around for similar reasons.  Whether you want to be the equivalent of a COBOL programmer in 2025 is, I suppose, up to you.

To you, is a career just a method of making money throughout your life, or is it at least partly a journey of exploration and learning?  Personally, I think life is short enough that I don't want to spend that much of it simply making money, and so I'm glad I'm in this business the way I am.


答:
You seem to have the dependency between your Model and your View the wrong way around. A Model does not know about the existence of a View, at most the model knows that some other component in the system might want to know about changes to the model.

In the MVC pattern, either the Controller informs the View that it should update itself, or the View asks the Model to notify it about changes. In the latter case, the communication from the Model to the View goes through a generic mechanism that allows a one-to-many communication without the Model knowing (or caring) about how many and which components it talks to. This mechanism is typically an event mechanism or an implementation of the Observer pattern.

Title: MVC seems to create dependencies that just "don't feel right"

Body:
I might be misunderstanding MVC, so forgive me if that is the case.

This is my program structure (Java/Swing): I have a JTable (View) that is pointed to by a custom linked list (Model). When the user tries to add something to the JTable, the action listener (Controller) updates the linked list (Model) which updates the JTable (View).

Here's my issue: The linked list should be able to function independently of the JTable, but it doesn't. Let's say I decided to get rid of the user interface and just use the linked list for internal stuff within the program (The linked list has other properties and functions outside the scope of MVC). That should be able to work, because the linked list's FUNCTION is independent of the JTable's function, yet I would have to edit a lot of code to do so (or have a bunch of code that no longer does anything) because of MVC.

So am I misunderstanding MVC completely, just a little bit, or are the dependencies a price I have to pay?

NOTE: This is a simplified view of my project. In real life, there are other objects in the model and more than just a JTable in my interface. Also, the linked list has other thigns that get updates other than the number of objects.


答:
Using pre-or suffixes in method names can in a few cases be used meaningful to express design intentions directly in code. I wouldn't recommend to use it though, since ideally there should be an extra document where among other things (e.g. different architectural views) design decisions are documented. One exception are widely accepted naming patterns, for example using +Factory for classes involved in Factory pattern.

In your case with the wrapper functions, you have in the first case actually two responsibilities in one method, namely establishing connection and saving customer. Why not naming the method accordingly bool ConnectDBandSaveCustomer(Customer cust). This is expressive for what the method actually does and you already see that it must be a wrapper method since you can derive the two responsibilities directly from the method name.

Sure it can lead to long method names and therefore to some kind of bloated code, but who cares if you are able to understand foreign code by a magnitude faster. Additionally, it makes you more productive in using other code for example in IDEs with autocompletion, because you won't have to look as often in the method definition as you would have to with poorly chosen method names!

Title: naming convention for different types of functions (use prefixes or suffixes?)

Body:
Does anyone have suggestions for naming conventions for different types of functions, particularly wrapper functions that need to connect to and disconnect from the database vs. wrapper functions that are passed a db link and don't need to connect and disconnect?

The project on which I am working has these types of functions (among other types):

wrapper functions that need to connect to the database, then call other functions, then disconnect

wrapper functions that are passed a db link and call other functions (these functions don't need to connect to the db, that has already been done)

Has anyone worked in a similar environment?  Did you follow any naming conventions to distinguish between these wrapper functions that need to connect vs. being passed a db link, such as using a particular prefix or suffix?


问:
Is the usage of internal scope blocks within a function bad style?
There are some (quite rare) cases where there is a risk of:

reusing a variable which is not intended to be reused (see example 1),

or using a variable instead of another, semantically close (see example 2).

Example 1:

```<code>var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
    this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.
}

// ...

foreach (var flow in data.Flows)
{
    // This shouldn't happen: given that ETL possibly altered the contents of `data`, it is
    // not longer reliable to use `data.Flows`.
}
</code>```

Example 2:

```<code>var userSettingsFile = SettingsFiles.LoadForUser();
var appSettingsFile = SettingsFiles.LoadForApp();

if (someCondition)
{
    userSettingsFile.Destroy();
}

userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe
                                  // destroyed. It's `appSettingsFile` which should have
                                  // been used instead.
</code>```

This risk can be mitigated by introducing a scope:

Example 1:

```<code>// There is no `foreach`, `if` or anything like this before `{`.

{
    var data = this.InitializeData();
    if (this.IsConsistent(data, this.state))
    {
        this.ETL.Process(data);
    }
}

// ...

// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.
</code>```

Example 2:

```<code>{
    var userSettingsFile = SettingsFiles.LoadForUser();

    if (someCondition)
    {
        userSettingsFile.Destroy();
    }
}

{
    var appSettingsFile = SettingsFiles.LoadForApp();

    // `userSettingsFile` is out of scope. There is no risk to use it instead of
    // `appSettingsFile`.
}
</code>```

Does it look wrong? Would you avoid such syntax? Is it difficult to understand by beginners?

答:
It is far easier for a beginner (and any programmer) to think of:

not using a variable that is not relevant

than to think of:

adding code structures aiming at preventing himself from not using a variable that is not relevant.

Moreover, from a reader's point of view, such blocks have no apparent role: removing them has no impact on the execution. The reader may scratch his head trying to guess what the coder wanted to achieve.


问:
Programming Style in Large Scale C++ Applications
Recently I've been browsing source code of large applications written in C++ to learn a bit but I couldn't help but notice that most if not all use a lot of IFDEFs and class-less functions (where they could have been class members/methods).

An example is Qt Creator IDE source code:

http://qt.gitorious.org/qt-creator/qt-creator/blobs/master/src/app/main.cpp

If you notice, it has a bunch of functions around the main() function; one of them, for example, is:

```<code>static inline void toHtml(QString &t)
</code>```

the above method is defined outside while I think it could have been part of some utility class maybe.

Also, I think IFDEFs make the programs messy (again my opinion).

My question is: is it just an accepted practice in C++ world to mix procedural and OO code like that?

答:
Like what birryree said, this is indeed a subjective question.  There are many ways to program in a large scale application.  The type of application can also play a big part on the way you want to program your application.

It is good to look into Component-based programming if the project is really big scaled.  This however should also be considered in a case-by-case basis to see if your project really needs it.

Google Component based programming for more info.

Here is the wiki page for it: http://en.wikipedia.org/wiki/Component-based_software_engineering


答:
I would have modeled it this way:

There are players as you modeled them

A class Game has a state {scheduled, running, finished}, it also stores pointers to two players, and Game also stores the score for player 1 and player 2

A System keeps track of all played/scheduled games (maybe it needs to provide a unique id for a new game, thus becoming a factory for games)

If you want to compute e.g. an average score for a specific player, you can introduce references from Player to Game. For easier access, I wouldn't go the other way and traverse through the list of games to find those player X participated in.

It's hard to analyse coupling and cohesion on such a small example, but I'd say that the score does not belong to a player, but to the game he participates in.

BTW:

In this diagram, Système would have to ask the PlancheDeJeu object
  about the score and it would itself have to get it from Joueur

Your model says Joueur can access PlancheDeJeu, but not the other way.

Title: Tic tac toe class diagram

Body:
I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP.

I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision.

("Joueur" means "Player", "PlancheDeJeu" means "Game board")

Given this diagram, according to the Expert, Low coupling and Strong cohesion design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea.

What would be the best way to go here ?

Thanks !


答:
First off i don't think it is an overkill.  To me it is a good way to visualise how you should start coding in an object oriented way.  And you are getting there.  Yay!

I am not an expert at this but this is how i would do it:

main for the flow of the game.

board for the logic for all the tic tac toe moves.

gameController to control the game. in this case which player's turn it is.

input to get the player's move

output to print out all relevant info including the board.

you might end up with some very short files but it is okie. you will need them when you move on to bigger games. :)

hope this helps.

Title: Tic tac toe class diagram


问:
What's with Delphi's support cycle?

This is a chart I whipped together showing the length of active (meaning ongoing bug fixes and service packs) support offered for each version of Delphi. It is based on the published support data obtained from Embarcadero's website. Delphi 2010 and XE are excluded because their active support is still ongoing so they can't really be compared accurately.

Ironically, Delphi 7, which was regarded by many to be the most stable until the release of Delphi 2009, had a support cycle three times as long as Delphi 2009. Granted, this chart spans three different companies with three different agendas. My question is why is Delphi 2009's support cycle so short? I understand Embarcadero has a business to run and they don't make money with service packs but really, 12 months? I would expect that of a $10 shareware title with low profit margins not a $900-$3500 world class development tool.

答: My guess is that the length of time for support is related to the stability and quality of the product.  Supporting a high quality product is easier than supporting a low quality one.</p>

Title: What's with Delphi's support cycle?


问:
Is there a comparative study of the memory consumption of programming languages runtimes, correlated with expressiveness and production bug ratios?
There are many comparative studies and available online when it comes to the runtime performance of applications built using one language or another. Some driven by corporations, some academic, some just personal experiment reports.

We also get a decent share of comparative studies on side-effects of a programming language and its tooling, like:

build times,

likelihood of post-production bug detection,

expressive power,

etc...

However, I've recently been more and more bummed out by the memory consumption of my programs more than anything else. This might come from the fact that while Moore's Law is on our side for raw performance, we have come to realize that other bottlenecks matter more. That, and I don't tend to update my hardware every so often, and I have some "old" (read 2005-2006 3.6GHz Pentium 4 with 4GB of RAM) that nowadays are hard-pressed to be useable for large applications without requiring me to go through great trouble to squeeze every bit of juice out of them (choice of OS, UI, tweaking of services and daemons, choice of applications to use for a task or another...). Quite honestly, sometimes I fire up top or procexp and weep at the sight of the memory used by the most innocent programs.

I can address this by keeping to push in the direction listed above, and essentially trying to limit myself and the programs I use (I have a dear love for cli programs for that reason, I guess), but I also cannot help but to think that maybe we're doing it wrong.

Modern Tools for Modern Needs

Of course, higher-level languages are arguably better and justify their worth of dead weight. Some design choices were made for good (or supposedly well-intended) reasons at the time, in many toolchains. Shared libraries, memory models, pre-processors, type-systems, etc... But some might be more viable than others with our modern hardware, and I'd be curious to read a few serious studies on the matter.

So, my question is, is there a pendant to the Benchmarks Game and others that focus on a comparison of the languages' base runtime memory consumption?

And even further, are there some studies that cross-reference this with other parameters (similar to what this article did, for instance, for other criteria, also based on the Benchmarks Game)?

答:
This is not answering the question per say, but perhaps changes the perspective a bit.  I am bearing in mind the transcript from chat, to set the tone of this answer-comment that is sure to be subject of many down votes.

There are people, hardware providers, tool providers, and programmers who are concerned about efficiency.  For the time being, it will be a growing concern for them and all of us.  Those concerns are rooted in mobile devices, particularly the high powered, battery gobbling monsters with the biggest screens and the strongest radios.

To take one more step back, part of the reason we find ourselves in the situation we are in today, with comparatively massive frameworks, and some slight disregard for general efficiency, beyond the hardware improvements is legacy.  Compatibility with legacy systems entrenches us with compatibility on top of compatibility.  It is not so much the fault of a top level run-times, as they essentially are the same runtime acting quite efficient and performant when used in a different operating environment (e.g. Xbox, windows mobile pre 7/8/surface, java micro framework, etc).

Compare the extent of the compatibility a desktop possesses with its legacy software to the extent of compatibility a mobile device possesses.

With the mobile devices, the device producers make some effort to ensure some compatibility, but they have not made compatibility a core fundament.  When the choice is between continuing to provide compatibility and moving the design of the mobile system forward, the mobile system moves forward.

For desktops, the opposite seems true.  If a significant breaking change strikes the marketers or early adopters wrongly, it pushes needed features and needed redesign to the back room many times over.  At some point I remember rumors to the effect that we as Windows users would find a completely and dramatically new file system with Windows XP, then in Vista, later the same for Seven, and finally again in Eight, but no, just incrementally improved since we first saw it on Windows2000?  The new file-system sat around for a long time, was scrapped, and however rumors decide the story after that, I cannot say.  That is probably the biggest known case, but I am positive it is not the only big case.

Even with the most recent tablets and mobile OS's, Microsoft who once shaped the market, is now intertwined in a death match with not only consumers, but a shadow of itself from the desktop department.  The tablet had to have significantly interoperability with the desktop counterpart.  No, it could not play perfectly with it, because of architecture differences, but also because of the archaic nature of the desktop underpinnings did it make significant sacrifices.

Now certainly, Windows is the easy target for any kind of criticism for this situation, but other platforms are far from "sin-free".  There are a lot of relics lurking in the Linux ecosystem that I am sure cause great consternation for systematic improvement.

Economics play a big part into this equation; how we finance our computing and applications on one, and how they are financed on the other follow astoundingly different patterns.  Where Wintel once strongly influenced obsolescence, Apple and Google have turned it into a near strict schedule.  This is further off course, than I intended, so I will leave as it sits and let the readers take it from there.

If and when big providers change their obsolescence and pricing models, then they can start to move forward with larger scale changes at a more even rate.  Those top-level frameworks that are driven by the highest order languages will shrink in a way, as they will be able to achieve their high-level task with a more low-level like efficiency because the inefficient intermediate compatibility and low-level layers will be drastically reduced, if not eliminated.


问:
Creating a separate project for JPA entities
Where I work it is a common practice to create a separate for JPA entities and a project for the web application (the WAR). So basically you have (at least) two project for each application - appJPA and appWEB.

The people who started this convention are no longer there, so I have been wondering about the benefit of having this separation. The only advantage I could think about is the Eclipse JPA facet which provides various tools for JPA. But if I am not mistaken, this facet can be applied to WAR projects as well.

So my question is: is this separation unnecessary?

答:
For big to mid level web projects, it is a good practice to separate your domain(model) from your presentational logic(view). You can go one step further and have an additional layer in between wherein business logic is placed (controller). This is a fairly common pattern in developing web applications known as MVC:

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

It helps adhering to the

http://en.wikipedia.org/wiki/Single_responsibility_principle.

Where each layer is responsible for doing its own thing, and with as little dependency on other layers as possible. For example, your domain (beans and such) most of the time doesn't need to know much about the business logic that operates on top of it:

(http://en.wikipedia.org/wiki/Anemic_domain_model)

This will help in refactoring, code maintenance and separation of concerns.

What JPA does for you is it gives you a common way of dealing with persistence, which is well known by most JEE developers. What support Eclipse provides and how JPA beans are packaged is mostly irrelevant as to why the developers choose to separate those projects, but that, of course, comes as a plus.

I think the developers that were working in your company were more concerned about following design patterns, separation of concerns, ease of maintenance when they made their decisions, rather than IDE support and packaging problems. And I also think you should stick with their decision, unless you are developing a very small project and in a very short time and you don't care about the benefits of having separate projects that I listed.


答:
This is actually quite subjective and it really boils down to what the individual prefers.  It also depends on the size of the project as well.

In bigger project that involves a group of people it is always good to standardise a coding standard for everyone within the group to follow (bug the tech director for it if you need to).

There are quite a number of astablished standards out there.  One of the better known ones is the Hungarian Notation that adds a prefix to everything.

Wiki: Hungarian_notation

Examples:

```<code>boolean bDone;
double * pdbPointerDouble;
</code>```

You can also create a whole new variety yourself (which i personally prefer) I personally just makes use of the camelCase and some self declared standards.  Like a HeadedCamel notation for functions and headlessCamel for variables. of cos you can add prefix or suffixes as well. but the main point of doing this is to keep it simple and easy to understand.

Wiki: CamelCase

Examples:

```<code>boolean isTriggered;
void TriggerFunction()
{
    // code here
}
</code>```

Find a notation that suits you (and your team mates) and you should be good to go.

Hope this helps

P.S. more info: http://en.wikipedia.org/wiki/Naming_convention_(programming)

Body:
This is actually quite subjective and it really boils down to what the individual prefers.  It also depends on the size of the project as well.

In bigger project that involves a group of people it is always good to standardise a coding standard for everyone within the group to follow (bug the tech director for it if you need to).

There are quite a number of astablished standards out there.  One of the better known ones is the Hungarian Notation that adds a prefix to everything.

Wiki: Hungarian_notation

Examples:

boolean bDone;
double * pdbPointerDouble;

You can also create a whole new variety yourself (which i personally prefer) I personally just makes use of the camelCase and some self declared standards.  Like a HeadedCamel notation for functions and headlessCamel for variables. of cos you can add prefix or suffixes as well. but the main point of doing this is to keep it simple and easy to understand.

Wiki: CamelCase

Examples:

boolean isTriggered;
void TriggerFunction()
{
    // code here
}

Find a notation that suits you (and your team mates) and you should be good to go.

Hope this helps

P.S. more info: http://en.wikipedia.org/wiki/Naming_convention_(programming)


答:
You could end up with something like this.

Two Factories

Polymorphism implementations

The two factories are based around:

1 - for converting the input type (Json/XML) to a concrete implementation of how to convert this data to an image/graph

2 - A second factory for deciding how render the output to a word Document/PDF Document

The Polymorphism uses a common interface for all rendered data. So an image/table can be moved around as an easy interface.

1 - Factory to convert JSON/XML data to a concrete implementation:

```<code>public enum DataTypeToConvertTo
{
    Image,
    Table,
    Graph,
    OtherData
}

public interface IDataConverter
{
    IConvertedData ConvertJsonDataToOutput(Json jsonData);
    IConvertedData ConvertXmlDataToOutput(XDocument xmlData);
}

public abstract class DataConverter : IDataConverter
{
    public DataConverter()
    {

    }

    public abstract IConvertedData ConvertDataToOutput(string data);
}
</code>```

The Factory below allows you to convert the xml Data or Json Data to the correct concrete type.

```<code>public class DataConverterFactory
{
    public static IDataConverter GetDataConverter(DataTypeToConvertTo dataType)
    {
        switch(dataType)
        {
            case DataTypeToConvertTo.Image:
                return new ImageDataConverter();
            case DataTypeToConvertTo.Table:
                return new TableDataConverter();
            case DataTypeToConvertTo.OtherData:
                return new OtherDataConverter();
            default:
                throw new Exception("Unknown DataTypeToConvertTo");
        }
    }
}
</code>```

The concrete implementations do all the heavy work of converted the data to the relevant type.
They also convert the data to the IConvertedData interface, which is used for the polymorphism.

```<code>public sealed class ImageDataConverter : DataConverter
{
    public ImageDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}

public sealed class TableDataConverter : DataConverter
{
    public TableDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new TableConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}

public sealed class OtherDataConverter : DataConverter
{
    public OtherDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new OtherConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new OtherConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}
</code>```

You can add these implementations as necessary, as your code expands.

The IConvertedData interface allows you to pass a single type into the next phase:
NOTE: You may not be returning voids here. It could by a byte[] for images or an OpenXml document for the WordDocument. Adjust as necessary.

```<code>public interface IConvertedData
{
    void RenderToPdf();
    void RenderToDocument();
    void RenderToOhter();
    void RenderToPowerPoint();
}
</code>```

Polymorphism:

This is used to convert the data to the relevant output type. i.e. the rendering to PDF for image data, may be different rendering image data for PowerPoint.

```<code>public sealed class ImageConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render Images
    }

    public void RenderToDocument()
    {
        //Logic to render Images
    }
}
public sealed class TableConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render Document
    }

    public void RenderToDocument()
    {
        //Logic to render Document
    }
}

public sealed class OtherConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render PDF
    }

    public void RenderToDocument()
    {
        //Logic to render PDF
    }
}
</code>```

2 - Factory to decide the output format:

```<code>public enum ExportOutputType
{
    PDF,
    PowerPoint,
    Word,
    Other
}

public interface IOutputExporter
{
    void ExportData(IConvertedData data);
}

public class OutputExporterFactory
{
    public static IOutputExporter GetExportOutputType(ExportOutputType exportOutputType)
    {
        switch(exportOutputType)
        {
            case ExportOutputType.PDF:
                return new OutputExporterPdf();
            case ExportOutputType.PowerPoint:
                return new OutputExporterPowerPoint();
            case ExportOutputType.Other:
                return new OutputExporterOther();
            default:
                throw new Exception ("Unknown ExportOutputType");
        }
    }
}
</code>```

Each concrete implementation exposes a common method that masks how the exporting is being thrown back to the IConvertedData implementations

```<code>public abstract class OutputExporter : IOutputExporter
{
    //Other base methods...
    public virtual void ExportData(IConvertedData data)
    {

    }
}

public sealed class OutputExporterPdf : OutputExporter
{
    public OutputExporterPdf()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to Pdf
        data.RenderToPdf();
    }
}

public sealed class OutputExporterPowerPoint : OutputExporter
{
    public OutputExporterPowerPoint()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to PowerPoint
        data.RenderToPowerPoint();
    }
}

public sealed class OutputExporterOther : OutputExporter
{
    public OutputExporterOther()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to PowerPoint
        data.RenderToOhter();
    }
}
</code>```

A sample client for all this would be:

```<code>public class Client
{
    public Client()
    {

    }
    public void StartExportProcess(XDocument data)
    {
        IDataConverter converter = DataConverterFactory.GetDataConverter(DataTypeToConvertTo.Graph);

        IConvertedData convertedData = converter.ConvertXmlDataToOutput(data);

        IOutputExporter exportOutputer = OutputExporterFactory.GetExportOutputType(ExportOutputType.PDF);
        exportOutputer.ExportData(convertedData);
    }
}
</code>```

Title: Designing a robust architecture for multiple export types?

Body:
I'm looking for patterns or architectural guidance for an upcoming feature I'm designing. Basically, it's an export feature with multiple export targets, and I'm looking to find a way to make it generic enough where plugging in new export targets don't require a lot of core changes. By export targets, I'm simply referring to different types of output, whether that be PDFs, PowerPoint presentations, Word documents, RSS, etc. I have a base set of data, which is represented in JSON and XML. This data are used to construct images (using any number or export types [e.g., PNG, JPG, GIF, etc), graphs, textual representations, tables, and more.

I'm trying to find a way to abstract all the rendering and layout into some kind of rendering or layout engine that handles the addition of further export targets. Any help/suggestions/resources as to how to approach this would be greatly appreciated. Thanks in advance.

For a pictorial representation of what I'm trying to achieve.

Body:
You could end up with something like this.

Two Factories

Polymorphism implementations

The two factories are based around:

1 - for converting the input type (Json/XML) to a concrete implementation of how to convert this data to an image/graph

2 - A second factory for deciding how render the output to a word Document/PDF Document

The Polymorphism uses a common interface for all rendered data. So an image/table can be moved around as an easy interface.

1 - Factory to convert JSON/XML data to a concrete implementation:

public enum DataTypeToConvertTo
{
    Image,
    Table,
    Graph,
    OtherData
}

public interface IDataConverter
{
    IConvertedData ConvertJsonDataToOutput(Json jsonData);
    IConvertedData ConvertXmlDataToOutput(XDocument xmlData);
}

public abstract class DataConverter : IDataConverter
{
    public DataConverter()
    {

    }

    public abstract IConvertedData ConvertDataToOutput(string data);
}

The Factory below allows you to convert the xml Data or Json Data to the correct concrete type.

public class DataConverterFactory
{
    public static IDataConverter GetDataConverter(DataTypeToConvertTo dataType)
    {
        switch(dataType)
        {
            case DataTypeToConvertTo.Image:
                return new ImageDataConverter();
            case DataTypeToConvertTo.Table:
                return new TableDataConverter();
            case DataTypeToConvertTo.OtherData:
                return new OtherDataConverter();
            default:
                throw new Exception("Unknown DataTypeToConvertTo");
        }
    }
}

The concrete implementations do all the heavy work of converted the data to the relevant type.
They also convert the data to the IConvertedData interface, which is used for the polymorphism.

public sealed class ImageDataConverter : DataConverter
{
    public ImageDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}

public sealed class TableDataConverter : DataConverter
{
    public TableDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new TableConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new ImageConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}

public sealed class OtherDataConverter : DataConverter
{
    public OtherDataConverter()
        : base()
    {

    }

    public override IConvertedData ConvertJsonDataToOutput(Json jsonData)
    {
        var convertedData = new OtherConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }

    public override IConvertedData ConvertXmlDataToOutput(XDocument xmlData)
    {
        var convertedData = new OtherConvertedData();
        //Logic to convert to necessary datatype

        return convertedData;
    }
}

You can add these implementations as necessary, as your code expands.

The IConvertedData interface allows you to pass a single type into the next phase:
NOTE: You may not be returning voids here. It could by a byte[] for images or an OpenXml document for the WordDocument. Adjust as necessary.

public interface IConvertedData
{
    void RenderToPdf();
    void RenderToDocument();
    void RenderToOhter();
    void RenderToPowerPoint();
}

Polymorphism:

This is used to convert the data to the relevant output type. i.e. the rendering to PDF for image data, may be different rendering image data for PowerPoint.

public sealed class ImageConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render Images
    }

    public void RenderToDocument()
    {
        //Logic to render Images
    }
}
public sealed class TableConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render Document
    }

    public void RenderToDocument()
    {
        //Logic to render Document
    }
}

public sealed class OtherConvertedData : IConvertedData
{
    public void RenderToPdf()
    {
        //Logic to render PDF
    }

    public void RenderToDocument()
    {
        //Logic to render PDF
    }
}

2 - Factory to decide the output format:

public enum ExportOutputType
{
    PDF,
    PowerPoint,
    Word,
    Other
}

public interface IOutputExporter
{
    void ExportData(IConvertedData data);
}

public class OutputExporterFactory
{
    public static IOutputExporter GetExportOutputType(ExportOutputType exportOutputType)
    {
        switch(exportOutputType)
        {
            case ExportOutputType.PDF:
                return new OutputExporterPdf();
            case ExportOutputType.PowerPoint:
                return new OutputExporterPowerPoint();
            case ExportOutputType.Other:
                return new OutputExporterOther();
            default:
                throw new Exception ("Unknown ExportOutputType");
        }
    }
}

Each concrete implementation exposes a common method that masks how the exporting is being thrown back to the IConvertedData implementations

public abstract class OutputExporter : IOutputExporter
{
    //Other base methods...
    public virtual void ExportData(IConvertedData data)
    {

    }
}

public sealed class OutputExporterPdf : OutputExporter
{
    public OutputExporterPdf()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to Pdf
        data.RenderToPdf();
    }
}

public sealed class OutputExporterPowerPoint : OutputExporter
{
    public OutputExporterPowerPoint()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to PowerPoint
        data.RenderToPowerPoint();
    }
}

public sealed class OutputExporterOther : OutputExporter
{
    public OutputExporterOther()
        : base()
    {

    }

    public override void ExportData(IConvertedData data)
    {
        //Functionality to Export to PowerPoint
        data.RenderToOhter();
    }
}

A sample client for all this would be:

public class Client
{
    public Client()
    {

    }
    public void StartExportProcess(XDocument data)
    {
        IDataConverter converter = DataConverterFactory.GetDataConverter(DataTypeToConvertTo.Graph);

        IConvertedData convertedData = converter.ConvertXmlDataToOutput(data);

        IOutputExporter exportOutputer = OutputExporterFactory.GetExportOutputType(ExportOutputType.PDF);
        exportOutputer.ExportData(convertedData);
    }
}


问:
Which Open Source License to choose for an ASP.NET MVC 3 OpenId StarterKit?
I've built a ASP.NET MVC 3 (RC at the moment) site that uses OpenID login system. I was still learning about OpenID while implementing this so I commented the code heavily. The result is a site that let's users login/register with OpenID, add other OpenIDs to their account and also remove them. This little project can be then used as a starting point for any new project that would use OpenID login system. It can also be used as a resource for people to learn OpenID with.

I decided to release this project as open source. This will be my first open source project and I need to decided what license to use. I want people to be able to use this for any purpose they wish for. They can learn from it, use it for commercial or non-commercial projects and make their own forks of the code. It would also be nice for others to be able to contribute back to the project with stuff like bug fixes on sites like GitHub. But I'd like to be the copyright owner of the code that is under my control. For example the code that is in my GitHub repository (I'll call this the main code base). I've heard that for this I need to get every contributor, that adds code to this code base, to give me the copyright for their contribution. How exactly does this work?

I also use other licensed (mostly open source) resources in my projects. Here's their list and their licenses:

DotNetOpenAuth (Ms-PL)

T4MVC (part of MvcContrib which is licesned using Apache License 2.0)

ASP.NET MVC (Ms-PL)

ADO.NET Entity Framework CTP4 (I couldn't find a license)

I of course want to use the main code base for any type of projects I want. Commercial, non-commercial, open source, ...

So I have some very important questions here:

Which license should I use? I think GPL or LGPL is not suitable here. I was looking at Apache 2, New BSD, MIT and Ms-PL. Ms-PL seems to be a good fit as, but I'm not sure.

What restrictions and/or obligations do I have towards the resources I use in this project? I think I read somewhere that I have to add -LICENSE.txt for Ms-PL resources. Is that true? How does this work for Apache 2 and other licenses? What do I have to do if I modify any of these resources' code and then use that in my project?

I'd also really like a "as-is" clause in the license, so people can't sue me if something goes wrong while they're using my code.

Do I need to add anything to my files to make clear what the license is? If so, how do I format that?

Also one last thing. If I decide to make a Visual Studio template out of this samples how do I license that?

答: Personally, if it's possible given the other components you mention, I would choose the AGPL (aka the Affero GPL) for a web application of any kind.</p>


问:
Will getting a degree in mathematics help in game development?
I'm two months away from getting my degree in systems engineering, which is to say, I learned how to code and code well using managed languages.

The only reason I got into this career was because I wanted to create video games. I know now that with my current skillset, I won't be able to create some of the things I have in my head.

Would getting a second degree in pure mathematics would help me with this goal?

答:
It does help for graphics programming.  But that has more to do with game engine programming rather than game programming (think more of the house for the game programming).  Engine programming can be just as interesting as game programming if you really like it.  It is up to the individual though.

But if your goal is game programming / development, get a game design degree instead.  You'll end up learning things that might not help with game design if you get a degree in maths (maths is a really big subject).  Some maths does help with board game design though (like discrete maths and combinatorial maths).

You will however need to know some algebra and trigonometry for calculations.  But, with the internet now, it is not hard to learn basic maths online if you really need it for game programming.

OwnerDisplayName: Sergio


问:
How can I translate my android app help and keep it up to date?
My Android application is almost done and I spend much time creating a set of very precise help pages in HTML that I display using WebViews. I am now ready for the next step, which is i18n.

Translating my app is no problem, the strings.xml is not that long and I can easily ask friends to translate it. My problem is about these help pages.

When I'll update my app, I'll probably have to update the help pages as well. I saw that it wasn't that simple, even with one language.

I need your opinion on how to perform such a massive work (which is not at all my job as a developer). Do I need to:

Manually update every language help page when I update the app, which means asking all of my translators to provide a new version of their work each time I change anything.

Provide help only in a default language (probably English, even though the default language is French. French people would still have the French help ;-D).

Google-translate the help pages, even if it "not well English is". I don't know any way to do it automatically.

Do something else, which you probably thought of long ago.

Thanks for your answers, tips and tricks.

答:
A few thoughts:

Do what is realistically possible.  Of course it would be nice if every Android app had help files in 29 languages, but realistically speaking, that is not going to happen in many cases.  You are a single developer working on a (presumably) small app.  You only have so much time, and your friends only have so much time to help you out.

While help is important, providing detailed help documents in many languages is probably going to be a big drain on your time.  Most of your users would probably be better served by you spending your time improving the app instead.  So don't try to do too much.

Furthermore, in general, people's expectations for help on a mobile app are fairly limited.  If you just offer the basics in a few languages, and full help in one language, that could be a good compromise.

Do what makes sense for your application.  Who do you expect to use this app?  Do you expect an international audience?  Is it international by design?  The languages in which it is important to offer help depend on your actual user base.

Many people understand at least some English, so it is not bad to stick with English if you expect a primarily English-speaking user base, with some users from other languages.  However, you do mention that French will be the "default language" of the app.  If so, I think you really need to have help available in French.  The French language is a matter of national or cultural pride for many people, and it would not look good if you have a French-focused app that only provides help in English.

Set up a good process for any translation you need - If you do decide to provide help in multiple languages, make sure you have a good process in place to minimize the work.  Use good version tracking so that you can send your translators only the content that changes.  Don't make them read through the whole manual and scan for changes each time.  This will make a huge difference from their perspective--instead of reviewing a whole document, they can quickly send you a sentence or two and the job is done.

Another option would be to build some form of open documentation or support forum, where users can contribute their own translations or other help.  This would probably be overkill at this point, but it might be a good option if your app really takes off.


问:
Would this development environment cover the bases for iOS and Windows 8/Windows Phone 8 apps?
I'm an experienced C# developer. I've created a couple Windows Phone apps and a Windows 8 app but have wanted to develop for iOS too. What I'm thinking is adding the following equipment and software to make this possible:

MacBook Air - necessary to compile/deploy to Apple's App Store and for some development tasks, as well as tools like PaintCode

iPad Mini - less expensive and able to do double duty testing for both iPhone and iPad screens (Ideally I'd have the budget for a phone too, but not in the cards)

Xamarin Studio Business Edition - pricier but integrates into Visual Studio, which is my primary dev environment and also home to Win8/WP8 app code

Basically, I'm just looking for a reality check. Is this overkill? Not enough? I know I could save a few hundred getting a Mac Mini, but have other uses for a laptop. Can I get by with the Indie version of Xamarin or am I crippling productivity by constantly switching environments? (As soon as I get the hardware I'll start by testing the free version to help answer that question).

答:
Using an iPad mini as a stand-in for testing all different versions of iPads and iPhones is questionable.  I would not want to build an app for both platforms without constant testing on both an iPhone and iPad--and then I would want to have at least a quick round of testing on as many different versions of each as I could find as well.  Though you could potentially borrow devices for this step.

If purchasing both is a problem, I suggest developing an app exclusively for either iPhone or iPad to start out, then expand to the other later when you can afford to purchase another device.

The power of the laptop is far less important.  A slower laptop may be slightly less pleasing to use, but it will work.  But if it isn't tested on the devices you want it to run on--well, as my former boss always said:

If it's not tested, it doesn't work.


问:
Can I use a LGPL licensed library for my web project
I am looking to use a javascript libray licensed under the LGPL license v3.

From what I have read so far, I understand that

If I do not make any modifications to the library, I can use the library without any restrictions.

But if I modify the library, I need to make the modified version available to the end users and also enable them to link the library dynamically.

Since I am using javascript, my code is anyways open to the end user. Also the user can dynamically link to library through the debug console.

So my question is, do I need to do anything explicitly since javascript is already open to users ?

Also, are there any other restrictions that apply which I may have missed out ?

Note: I found other answers that describe LGPL with respect to any application. But I am looking for an answer that describes how LGPL applies to javascript specifically.

答:
As far as I understand LGPL you have to supply a way to receive the library (and only the library). Using technics to view the code is not enough.

BTW IANAL.