问:
Heterogeneous Associations - Data Modeling When an Object that Must Relate to One of Many Classes
Suppose you have 3 classes: ClassA, ClassB and ClassC. Now suppose you have a class Message. You want a one-to-many relationship between each one of those three classes and the Message.

The goal is that a Message must 'belong' to either a ClassA, ClassB or a ClassC object. A ClassA/ClassB/ClassC object can have zero or many Messages. The Message class is the same for any of the three classes (i.e. there shouldn't be a different class of Message for each of the three Classes A, B and C).

Now thinking about data-modeling on a relational DB (also, I'm using ORM, in this case Entity Framework Code First), I'll map each one of those 3 classes and the Message class to a table.

But then, the issue is trying to apply the relationships I explained above. I see a few ways to do this:

Add three nullable Foreign Keys (ClassAID, ClassBID, ClassCID) to the Message table. e.g. If a message belongs to a ClassA object, then ClassAID will have that obect's ID as a value and ClassBID and ClassCID will be null. This will force me to write a constraint/trigger to make sure that the Message object only has a value in one of those FK's. It also makes it a bit ugly on the Business Logic and Presentation layers whenever I want to know to which object does a message belong to: the MessageObject would have a nullable reference to a ClassA, ClassB and a ClassC object and I would need to check it before presenting it in the UI (e.g. a link from the Message to its object).

Implement inheritance and generalize ClassA, ClassB and ClassC. The Message has a FK for the generalized class' ID. This adds complexity and doesn't really solve the problem of easily figuring out to which ClassA/B/C a Message is related to.

Add a ClassToMessage table (similar to a link-table) that connects the 3 tables to the Message one, again, via nullable FK's. Sort of a combination of the previous two, but still not exactly a good solution for the same reasons.

I'd like to know if there's an elegant way to achieve the desired scenario, preferably having the Entiy Framework approach in mind. Thanks in advance.

EDIT 1:

Imagine the Message objects as being comments (or files) in a tree-like structure of objects (ClassA objects can have ClassB's and ClassB's can have ClassC's...). You want objects from all of those classes to have zero or many comments. You want the same Comment table for all of the comments (doesn't matter if they're belong to a ClassA or ClassB... instance). You also want it to be easy to find out the comments for a given object or the object a comment belongs to.

EDIT 2:

Two other alternatives:

Implement table per hierarchy (TPH) by having a ClassAMessage, ClassBMessage... that still doesn't quite solve the problem...

The Message stores the ID of the object that owns it and the object Type (whether it was a ClassA, ClassB...). No actual relationship: service layer or business logic does the rest (ouch).

I have seen this issue being addressed in StackOverflow, but I can't seem to find a good solution:

Entity Framework Code First - Entity maps to one or the other

Multiples Object Relationship in Code First

Database design - articles, blog posts, photos, stories

EDIT 3:

I'm pursuing alternative #4 (Table per Hierarchy / Class Table Inheritance) and have evolved this into a more specific S.O. question: Entity Framework 6 Code First - Comments on a Tree Structure

答:
Going with that last option in your edit but altering it a little.

In this, you abstracted away any changes in concrete class.

In your database however, you are saving the value of an enum that saves which kind of concrete class you are referring to, and what that concrete class' id is.
This info can be passed to the factory, which should provide a method returning a genericClass which can be any of the concrete classes based on that previous enum and id.

```<code>- Message
   + int Id
   + int TypeEnum
   + int ClassId

- Class
   + int Id
   + int TypeEnum
</code>```

Class.TypeEnum would the the "loose" constaint on Message.TypeEnum.

This way you don't need to worry about needing to add columns for additional nullable foreign keys.

As I've pointed out: you will have to take into account that the database constraints (Foreign Keys) between the Message-class and ClassA, ClassB, ... ClassX cannot be used and should be taken care of manually.

Body:
Going with that last option in your edit but altering it a little.

In this, you abstracted away any changes in concrete class.

In your database however, you are saving the value of an enum that saves which kind of concrete class you are referring to, and what that concrete class' id is.
This info can be passed to the factory, which should provide a method returning a genericClass which can be any of the concrete classes based on that previous enum and id.

- Message
   + int Id
   + int TypeEnum
   + int ClassId

- Class
   + int Id
   + int TypeEnum

Class.TypeEnum would the the "loose" constaint on Message.TypeEnum.

This way you don't need to worry about needing to add columns for additional nullable foreign keys.

As I've pointed out: you will have to take into account that the database constraints (Foreign Keys) between the Message-class and ClassA, ClassB, ... ClassX cannot be used and should be taken care of manually.


问:
How Best Can I Use Git When My Employer Uses VSS?
I am going to be working with VSS but I am much more productive and diligent with GIT.

I have to fit within the workflow of VSS and keep good history in VSS. The standard work flow here with VSS is

get working copy

do work

right click on folder -> show differences

in that view:

checkout (without overwriting local changes)

checkin (keeping write access)

Add comment with specific template

Personally I think this is already side-stepping the intended workflow of VSS and potentially overwrites any changes made by other people.

I think I can prevent the possible overwrite, but are there any other potential problems  that I should be aware of with this workflow?

--EDIT--

It's worth mentioning that in this case VSS is only used on legacy projects, and its largely treated with scorn by both the people that use it and the people that maintain it.

80% of the people that use it, use it alongside another version control system (some git, most mercurial)

When I asked the sys admin what my workflow should be, I was told "whatever your preference". I have kept them up to date with my thinking and they are interested in the results.

I would not recommend using any extreme methods (such as my script below) unless you have discussed it with whoever maintains VSS

答:
--UPDATE--

I have been using this bash script with a lot of success :)

Also I would now recommend 2 directories instead of 2 branches. It's a lot cleaner :)

If you have the support of your VSS admin, then you can follow something like below.

Otherwise you can use git for your own branches and general workflow and use VSS as intended, but in that case I would recommend a clean separation, not the interop solution I have gone for. My solution is more suitable as a migration step but even then I would use with caution.

Get working copy from VSS

git init

create a "vss_branch" branch

branch a "dev" branch from master

branch dev for each individual feature/bug

on feature completion, rebase to clean up comments (if I have been naughty)

merge into dev when features/bugs are ready

test dev

if all good merge dev into master

Synchronize my master branch with VSS

switch to vss_branch

get working copy from Visual Source Safe

commit into vss_branch with "ss history" as comment

pull vss_branch onto master

test master
Synchronise VSS with master

"ss checkout" files I have changed (don't overwrite working copy)

"ss checkin" files I have changed (adding git comment as label)

pull master into dev

I have attempted to stick to our VSS workflow but be a little more robust with the separate VSS git branch which I never push to.

ContentLicense: CC BY-SA 3.0


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
Know your OS/Platform before you start coding.

If you code Windows/Linux/Android/iOS etc. start by learning the OS.
If you target something else such as Web the same goes there.

ContentLicense: CC BY-SA 2.5


问:
Should jars that are only gonna be used in one project be deployed to Nexus server
I guess the title says it all. There is a debate at our firm, weather we should deploy internal jars, which are only going to be used in one specific project, to Nexus or is there any better solution? The argument for not deploying it to Nexus is that it will not be reused so there is no point in having it there.</p>

答: You are reusing it everytime you compile the one specific project from a cleanly installed machine (i.e. one that does not have the jar in its .m2 repo). Keeping it in Nexus makes sure it's available when you need it.</p>


答:
What you have called "Table Per Hierarchy" resembles what Martin Fowler and others have called "Class Table Inheritance".  See Diagram.  I would call this mimicking inheritance rather than implementing inheritance.

One technique that can be used to good advantage in some cases of class table inheritance is called "shared primary key".  See tag wiki in SE.

The advantage if shared primary key is that an FK reference that references the shared primary key can reference both the entry in the generic class table and the entry in the appropriate specialized class table.  This turns out to be really handy, and can justify the extra programming needed to implement shared primary key.

Title: Heterogeneous Associations - Data Modeling When an Object that Must Relate to One of Many Classes

Body:
Suppose you have 3 classes: ClassA, ClassB and ClassC. Now suppose you have a class Message. You want a one-to-many relationship between each one of those three classes and the Message.

The goal is that a Message must 'belong' to either a ClassA, ClassB or a ClassC object. A ClassA/ClassB/ClassC object can have zero or many Messages. The Message class is the same for any of the three classes (i.e. there shouldn't be a different class of Message for each of the three Classes A, B and C).

Now thinking about data-modeling on a relational DB (also, I'm using ORM, in this case Entity Framework Code First), I'll map each one of those 3 classes and the Message class to a table.

But then, the issue is trying to apply the relationships I explained above. I see a few ways to do this:

Add three nullable Foreign Keys (ClassAID, ClassBID, ClassCID) to the Message table. e.g. If a message belongs to a ClassA object, then ClassAID will have that obect's ID as a value and ClassBID and ClassCID will be null. This will force me to write a constraint/trigger to make sure that the Message object only has a value in one of those FK's. It also makes it a bit ugly on the Business Logic and Presentation layers whenever I want to know to which object does a message belong to: the MessageObject would have a nullable reference to a ClassA, ClassB and a ClassC object and I would need to check it before presenting it in the UI (e.g. a link from the Message to its object).

Implement inheritance and generalize ClassA, ClassB and ClassC. The Message has a FK for the generalized class' ID. This adds complexity and doesn't really solve the problem of easily figuring out to which ClassA/B/C a Message is related to.

Add a ClassToMessage table (similar to a link-table) that connects the 3 tables to the Message one, again, via nullable FK's. Sort of a combination of the previous two, but still not exactly a good solution for the same reasons.

I'd like to know if there's an elegant way to achieve the desired scenario, preferably having the Entiy Framework approach in mind. Thanks in advance.

EDIT 1:

Imagine the Message objects as being comments (or files) in a tree-like structure of objects (ClassA objects can have ClassB's and ClassB's can have ClassC's...). You want objects from all of those classes to have zero or many comments. You want the same Comment table for all of the comments (doesn't matter if they're belong to a ClassA or ClassB... instance). You also want it to be easy to find out the comments for a given object or the object a comment belongs to.

EDIT 2:

Two other alternatives:

Implement table per hierarchy (TPH) by having a ClassAMessage, ClassBMessage... that still doesn't quite solve the problem...

The Message stores the ID of the object that owns it and the object Type (whether it was a ClassA, ClassB...). No actual relationship: service layer or business logic does the rest (ouch).

I have seen this issue being addressed in StackOverflow, but I can't seem to find a good solution:

Entity Framework Code First - Entity maps to one or the other

Multiples Object Relationship in Code First

Database design - articles, blog posts, photos, stories

EDIT 3:

I'm pursuing alternative #4 (Table per Hierarchy / Class Table Inheritance) and have evolved this into a more specific S.O. question: Entity Framework 6 Code First - Comments on a Tree Structure


问:
Will there be a memory or processing time difference between a class member function and a global function
I'm writing a neuron network simulation program and every operation or additional byte per neuron scales insanely. I prefer C++ as a language over the others, but now I'm wondering if the class structure takes additional space or resources after compilation in comparison to C for example. If I have a :

```<code>class Neuron{
float some,variables,foo,bar;
//And some functions to compute the changes
void foo();
void bar();
}
</code>```

will it be leaner to have a :

```<code>struct Neuron{
float some,variables,foo,bar;
}
void foo(Neuron*);
void bar(Neuron*);
</code>```

or is it the same after compilation?

答:
If you don't use virtual functions, then there should be no (negative) performance or space impact on using C++ classes when comparing to C structs. The two snippets you gave as example should compile to (nearly) the same assembly code.1

If you add virtual functions to your classes, then there will be a slight memory overhead per object (about the size of a pointer) and a time overhead per call to a virtual function, because the call has to go through a dispatch table. It will also be an indirect jump, which might be slightly more costly on some processor architectures (in the order of a few clock cycles).

Note 1: The compiler may use a different method for passing the implicit this parameter than what is used for the other parameters, but that difference is in the order of choosing register A instead of B or passing in a register instead of on the stack.


问:
NodeJs website webapp architecture
I would like some advice on how best to architect a website comprising the following:
tool

a landing page, open to the public, main marketing tool

the main website/app, that people can access only if registered, where users can access certain modules depending on their level of registration (free/casual/premium user)
I'm thinking of using AngularJS for front-end for the double-binding and to bring UI interaction

an admin part:

where we can either interact with the database

check user analytics

I'm afraid that if I use Angular for the 3 parts, the admin part might be accessible to even the public/free users as basically everything is stored as static files on the client.
Is it just a routing problem on the server side? should I use Jade/handlebars for the admin part/landing page (helps for the SEO) and Angular just for the app? is there a best practice in this regard?

答:
When building angular apps, here's my general philosophy in a nutshell. I can add more clarification if necessary.

All actual security must be implemented server-side. Any security logic you put in the angular app (and it should be there) is for convenience and usability only, not actual security.

You must gate your REST api calls in nodejs using some kind of authentication and authorization scheme, and you should return a 401 to any client asking for data or trying to save data they don't have access to.

At the same time, it's a bad idea to show users functionality that will not work (ie, will return a 401). So if there's a button that does something a user isn't allowed to do, you should hide it from them before they have a chance to click on it and receive an error.

To do this, you'll need to send the client information about the currently authenticated users access-level, and drive visibility of features/behavior off of that. But understand that this is easily circumvented by a sophisticated user (using the F12 Developer Tools, for example). So this is not something that secures your application, per se, but something that makes your application more user-friendly.

You have to decide how important it is to keep the admin functionality secret. Is it a secret that there exists an admin function that your users can't use? Or do you need to just secure the functionality itself? If you are serving static files, then a clever user can get any of those files from the server. But of what value is that? Those files will not contain any actual data, and clicking the buttons won't do anything (because you secured your api calls on the server). All our hacker can see is an angular html template. That's not worth very much. Some sucker spent all that energy trying to figure out the names of the files to download and all s/he sees are a bunch of mustaches and ng-* directives. Whoopdedoo.

But if you want to secure even that, you'll need to gate access to the static files. There's no reason you have to serve those to freely. You can implement security on the server and check authorization before returning html and js. It's a bit more work to do this, so it isn't worth it unless it's necessary, but it's possible.

One final thought: there's no reason you are limited to a single angular app for your application. You might want to try a setup that looks like this:

Landing Page (rendered server-side, public)

About Page (rendered server-side, public)

Any other server-side pages to market your app

App (index.html, the entry point to your main angular app)

Admin App (index.html, the entry point to your admin angular app)

Here you have two SPAs being served from the same webserver. This structure separates your admin functionality cleanly. From a security standpoint, you still have all the same considerations, but this might make it easier to implement your security rules.

Title: NodeJs website webapp architecture


答:
If I remembr well all global will be write on http://www.geeksforgeeks.org/memory-layout-of-c-program/ on Uninitialized Data Segment.

Class function member section will be exist only if you have create new instance of the class. So It wil be store in heap.

So i think Global function is faster than Class member function.

To me choose a address of global is faster than ask a first address memory (object) for look if it contains another address memory (member).

Title: Will there be a memory or processing time difference between a class member function and a global function

Body:
I'm writing a neuron network simulation program and every operation or additional byte per neuron scales insanely. I prefer C++ as a language over the others, but now I'm wondering if the class structure takes additional space or resources after compilation in comparison to C for example. If I have a :

```<code>class Neuron{
float some,variables,foo,bar;
//And some functions to compute the changes
void foo();
void bar();
}
</code>```

will it be leaner to have a :

```<code>struct Neuron{
float some,variables,foo,bar;
}
void foo(Neuron*);
void bar(Neuron*);
</code>```

or is it the same after compilation?


答:
Unless you have powers we're not aware of, all you really know is that you're not planning on reusing that jar. The whole point of object-oriented development is re-use. Even if you don't have a case where another application could use that jar, and can't think of one right now, doesn't mean that there will never come a time where that code wouldn't come in handy in another application. If it's useful in 1 app, it could be useful in another, so go ahead and deploy it to Nexus.

Anything that should never be used outside of a specific project should be in that project and not a separate jar. The fact that this code is in its own jar file implies that you thought it could be useful to something else, which should answer the "to deploy to Nexus or not to deploy to Nexus" question for you.

Title: Should jars that are only gonna be used in one project be deployed to Nexus server

Body: I guess the title says it all. There is a debate at our firm, weather we should deploy internal jars, which are only going to be used in one specific project, to Nexus or is there any better solution? The argument for not deploying it to Nexus is that it will not be reused so there is no point in having it there.</p>


问:
How was the system clock first used in early computers?
This question is about the clock that keeps current time, not about the signal that sequences the circuitry (the wall clock, not the metronome).

First computers were pure calculators, just very large, so I'm pretty sure they did not have system clock (simply because that's a lot of extra circuitry). Modern computers use the system clock for lots of stuff so that there's even an API for obtaining current time which is used when dealing with emails and IM messages, creating new log records, creating and changing filesystem objects, etc.

So clearly at some point someone decided that system clock is useful for something inside computer and clock was added.

What was the earliest use case for the system clock?

答: Many early time-sharing services would charge you by the millisecond for things like CPU time and memory time, and even dedicated data-processing systems (think company payroll and accounting systems) would have batch runs scheduled to run at certain times. I think large computer systems started having real-time clocks around the time they stopped being experimental toys and began to be used for "real work".</p>


答:
Yes, adding a clock was complex for first computers, that's right. But some of the first computers simply WERE clocks. http://en.wikipedia.org/wiki/Antikythera_mechanism.

What is interesting, the first universal computers were not afraid of clock using.
ENIAC (1946) had a special cycling unit for synchronization of all its operations. It was not named "system clock", but it was separate and it counted time, so, it was a clock. And the whole machine could work with it, not by API, of course, (there were no APIs these times).

ENIAC was one of the first universal programming machines, but not the first... But even the German Z1 (1941) had its clock, too. For the same use - synchronizing.

Title: How was the system clock first used in early computers?

Body:
This question is about the clock that keeps current time, not about the signal that sequences the circuitry (the wall clock, not the metronome).

First computers were pure calculators, just very large, so I'm pretty sure they did not have system clock (simply because that's a lot of extra circuitry). Modern computers use the system clock for lots of stuff so that there's even an API for obtaining current time which is used when dealing with emails and IM messages, creating new log records, creating and changing filesystem objects, etc.

So clearly at some point someone decided that system clock is useful for something inside computer and clock was added.

What was the earliest use case for the system clock?


问:
Hexagonal architecure - handle multiple returns from domain logic
I'm looking at using hexagonal/ports & adapters design in some code I'm working on and for the most part I'm happy but there is one part that I'm struggling with which how to handle the need for different return values from a single call.

I'll use an example to better illustrate, this is pseudo code so names aren't represntative of real code.

If I have a domain "service" which has a method AddEntity I can have 3 returns:

Newly added object

Invalid Data

Entity already exists

The adapter that uses this "service" will then take the return and will send the data in the object back (it may transform it to a "view model" first).

In C# the adapter maybe a WebApi controller with code something like this:

```<code>public IHttpActionResult Post(DataViewModel entityData)
{
    var item = this.service.AddEntity(entityData.Name, entityData.Description);

    if (item == null)
    {
        return this.StatusCode(HttpStatusCode.Conflict);
    }

    var viewModel = Mapper.Map<EntityDTO, DataViewModel>(item);
    return this.Created(this.Url.Link("DefaultApi", new { controller = "Entity", id = viewModel.Id }), viewModel);
}
</code>```

The problem as you can see is at the moment it can only deal with 2 returns, either it gets the entityDTO which it maps and returns to the client or it gets null and just returns a Conflict HttpStatus code.

What I'm trying to work out is how I could get back to the adapter, controller in example above, is either the object or one of the two messages.

The approaches I've considered are:

extending the entityDTO class to have additional information which would allow me to pass something indicating a problem (an enum maybe?)

raising typed exceptions and handling the exceptions

raising events

if I used the enum then the controller code would look something like this:

```<code>public IHttpActionResult Post(DataViewModel entityData)
{
    var item = this.service.AddEntity(entityData.Name, entityData.Description);

    if(item.result == Result.Conflict)
    {
        return this.StatusCode(HttpStatusCode.Conflict);
    }

    if (item.result == Result.Invalid)
    {
        return this.StatusCode(HttpStatusCode.Invalid);
    }

    var viewModel = Mapper.Map<EntityDTO, DataViewModel>(item);
    return this.Created(this.Url.Link("DefaultApi", new { controller = "Entity", id = viewModel.Id }), viewModel);
}
</code>```

Of these extending the DTO seems the least bad option but I'm unsure if I've just missed something in the pattern which gives an easy way to do this.

Is there any specific way to do this I've missed? or is one of the options for sorting this I mentioned above a better way than the others?

答:
There are a couple of principles to bear in mind.

The first is command-query separation here (CQS). Either you are updating, or you are querying, but not both, because this creates an issue of side-effects. Adding a new X should be a write operation, and so not return a value.

The pragmatic issue here is that you might not be able to use a Guid or Hi-lo algorithm  to create the identity for the X you are about to add. In that case you need to either provide a return type, or add an out parameter to retrieve it. That should be the Id not the instance.

In this case, with a hierarchical architecture style, I might use a command pattern anyway and consider adding a property on the command that can be updated for the created id if required. That's essentially a hack to get around an inability to create the id here. See my discussion here: http://iancooper.github.io/Paramore/CommandsCommandDispatcherandProcessor.html

Then I would use some kind of retrieve to return the instance of X if I needed it for my response i.e. a separate query. Again, I would not return the instance of X on the command or as an out parameter or return type. That minimizes your exposure to side-effects if you have to do this.

When considering error codes vs exceptions, bear in mind that an error code is effectively a query - what was the state of that operation? In many cases you could perform the command and then run the query to determine the result. For example if it is common that folks will try to recreate an existing X, query for it before the operation happens can be an alternative to throwing an exception.

Once you understand our reads and writes as all using a port layer to a model, you can appreciate calling either of them from your adapter layer.

In other cases think about the invariants you stating - the pre-conditions and the post-conditions.

There is not already an X.

X was created successfully

If you violate those conditions, I would throw an exception, to indicate that one of the invariants has failed.


答:
It's interesting to separate out system clocks, that provide the basic drumbeat for keeping gating circuits in synch with each other, and calendar clocks, that are used for tracking elapsed time over longer periods.

The simplest form of calendar clock is driven off the alternating current power supply.  This provides 60 cycles per second in the US, generally 50 in Europe.  The circuitry for this is simple and inexpensive,  and it's suitable for a lot of purposes, such as providing the time last modified for a file.  It's reasonably accurate because the power grid requires all power providers to be in synch with each other.  AC clocks go back at least to the UNIVAC computers, and probably earlier.

The speed and accuracy of the system clock depends somewhat on the technology used to drive your gates.  Relays, vacuum tubes, transistors, integrated circuits, and microchips operate at vastly different speeds, and require very different clocks.

In addition, many early systems were completely synchronous, and a component had to deliver the correct result on a given clock tick, or else it was out of spec.  Other systems were designed to be somewhat or completely asynchronous, where a signal would be provided whenever it was ready, and the receiver of that signal had to check on some control circuit to tell it whether to use the signal or to wait.

In the heydey of timesharing systems (late 1960s, early 1970s), the AC clock provided a source of interrupts that would allow the operating system to reconsider its scheduled jobs, if necessary, on each interrupt. Timesharing system designers wanted to keep scheduling overhead within limits, and also to make the system responsive to changing loads and demands.

Today's desktops typically use the AC clock for calendar purposes, except when power is cut off, when  they use a button battery that may last between five to ten years.  The battery powered clock gains or loses up to a few seconds a day.


问:
What is the simplest way to broadcast data from application to other applications in .Net
I want to send information from one .Net application to multiple other .Net applications. I want the applications to be loosely coupled. The number of applications receiving the information could change at run time.  What is the simplest way to do this?

I thought about using MSMQ, but from what I can tell, there the broadcasting application has to know how many receivers there are or each message only gets processed by one of the receiving applications. Neither options is acceptable.

答: Whether it's applicable to your specific scenario is a different question entirely, but writing to a text file and reading it from the other applications is probably the 'simplest' way to transfer data.


问:
What are your decision critera in C++ to make something a data member or virtual method?
(Figured this was too subjective for SO, so posting here...)

I have some behavior that I can implement in various ways.  At least two methods are shows in the code snippet below.  Presume that the m_well data member is correctly set somehow at object construction time.

```<code>struct Behavior
{
    virtual bool behavesWell() { return true; }

private:
    bool m_well;
public:
    bool behavesMemberWell() { return m_well; }
};

struct OtherBehavior : public Behavior
{
    virtual bool behavesWell() { return false; }
};
</code>```

Obviously the one relies upon virtual dispatch, and the other merely the return of a data member.

A third, non-shown method would likely have the non-virtual public member function not return a fixed data member, but instead call a virtual - lets leave that aside for the purpose of this please.

What would lead you to one or other other of these two methods of implementing functionality, such that a user of this class can interrogate an object's behavior?

答:
The rule of thumb is that all your data members should be private.  There are exceptions to this rule, such as simple POD (plain old data) structs that are only passed around or stored, but more often than not it makes sense to keep all data members private.

If you need to give other objects access read access to a data member, then you write a getter.  If your class will not have any child classes derived from it, then there is no need to make the getter virtual.  The only time you need to make any member function virtual, is when you want to allow a derived class to override it.


答:
You might be best served by letting the apps pull the information rather than pushing it out -- that is a much simpler model as all you need to do is expose an API. The default choice in 2014 is probably an RESTful ASP.NET web api but there are tons of options depending on what you are doing.

As for the push model, MSMQ is a pretty raw tool but it is usable. You might want to look at something like rabbit MQ which is a bit more feature-complete and has a pretty handy pub/sub model.

The bottom line is that there are lots of ways to solve this problem -- the best way really depends in specific requirements here.

Title: What is the simplest way to broadcast data from application to other applications in .Net

Body:
I want to send information from one .Net application to multiple other .Net applications. I want the applications to be loosely coupled. The number of applications receiving the information could change at run time.  What is the simplest way to do this?

I thought about using MSMQ, but from what I can tell, there the broadcasting application has to know how many receivers there are or each message only gets processed by one of the receiving applications. Neither options is acceptable.


问:
DDD: How to refer/select a value object inside aggregate?
We have an aggregate of:

entity: Poll (representing a question)

two or more value objects Choice

Adding choices is done through Poll, repository stores only the aggregate, i.e. everything is done as expected.

Now, I need to select specific Choice that user chose. From the UI I will have only the choiceId of selected choice. So would my Poll.voteForChoice() method be:

voteForChoice(choiceId) - where I pass the choice id to the aggregate root, so he iterates it's choices and finds the target choice so to increment the count. However, we are using ID here for the choice, and choice is value object.

voteForChoice(Choice) - where we are sending the full value object, meaning I need to create it first before I do the voting. That also means I will need to have a Repo for choices, and they are value objects, so that clashes with all what I've learned ;)

or it should be: Poll.getChoice(choiceId).vote().

or the Choice is actually an entity, so we would use Repository to fetch choice: ChoiceRepo.find(id).vote().

Simple case, but what is the correct answer in DDD world?

答:
Depending on the collaborative degree of your application, you might find yourself in trouble if 2 or more users try to increment the same Choice concurrently. That will happen whether it's a VO or an Entity in the same Aggregate as the Poll.

To me the natural consistency boundary implied by the domain action of voting includes the user. So I would suggest a full fledged PollChoice Aggregate Root with a link to the User, or if there are multiple choices per poll, a PollResponse AR containing all choices (which can then be VO's) made by a particular user to a specific poll.

Edit : something along these lines

```<code>class PollResponse {

  int pollId;
  int userId;
  Choice choice;
  Datetime dateResponded;
}
</code>```

Body:
Depending on the collaborative degree of your application, you might find yourself in trouble if 2 or more users try to increment the same Choice concurrently. That will happen whether it's a VO or an Entity in the same Aggregate as the Poll.

To me the natural consistency boundary implied by the domain action of voting includes the user. So I would suggest a full fledged PollChoice Aggregate Root with a link to the User, or if there are multiple choices per poll, a PollResponse AR containing all choices (which can then be VO's) made by a particular user to a specific poll.

Edit : something along these lines

class PollResponse {

  int pollId;
  int userId;
  Choice choice;
  Datetime dateResponded;
}


问:
Should I store images in my database or file system in this application?
I'm using ASP.NET MVC 4 and SQL Server 2012. I have no problem going for either of these solutions but I want to know which one would fit better in the particular application I'm creating now.

I'm making a sort of a library system application. The only images the application will store are:

Users' profile pictures (1 per user)

Libraries' profile pictures (1 per library)

Book authors' pictures (1 per author)

Book cover images (1 per book)

None of the images stored will need to be of high quality. So obviously the images are not a big part of the application and considering this, I am currently storing the images in my database. Though I noticed something that I think makes for a major con.

The images are retrieved using a Url.ActionLink which leads to a Controller action method that accepts (for example) a bookId parameter before reaching to the database, retrieving that book's image and sending it back. So if a user were to search for books and he ends up getting a list of books along with their images before him, there will be a new call to the action method that retrieves images and a new query to the database for each image listed.

Is there a better way of handling this? Should I reconsider keeping my images in the database or is it not a big issue?

EDIT: Wouldn't consider this question a duplicate because it pertains to a specific type of an application that handles very little image data as as opposed to any type of an application (like in the linked question). Of course when you're not sure how much image data you're gonna be storing it's always best to store images on the file system. This is not such a case. The nature of the answers here versus the answers there shows this.

答:
Why not do both? Database is the backing, ultimate store for the image. The public side can be a simple read from db but you can easily extend that into a read-through disk cache and also take advantage of numerous infrastructure tricks to better enhance performance.

The wins here are:

simpler data backup -- database backups are fun and easy, no file system touching necessary

simpler dev story -- you don't need to handle a bunch of files, just get the dev team a copy of the database

easier to write the image -- file systems are a PITA, from permissions, to changing locations from dev->qa->production, to contention to lack of transactions. If the writes are going to the db then you solve 90% of those problems.

modern databases can handle it -- presuming we are talking fairly typical image file sizes measuring under a few megabytes most modern database systems can handle them very well. It is not the database murdering issue that some older articles would have you believe.


答:
So if a user were to search for books and he ends up getting a list of books along with their images before him, there will be a new call to the action method that retrieves images and a new query to the database for each image listed.

I would suggest that's a Good Thing. Images take much longer to transfer than text so, rather than making the user wait for both to load from the DB, you can show the text and then load the images separately.

Also, should your application ever become successful, you may want to make your web application run on multiple servers. Each server will, at that point, have access to the database, but not to the other server's file system.

However, you should consider isolating images in their own image table. Don't store an image in the same table as the book; simply store an image ID and use that to retrieve the image later. This is much more efficient, considering the way databases manage data on the disk. This statement is considerably more important if you plan to change the image associated with a book at any point.

Finally, my experience with these things is that you'll very quickly hit a situation where you want to use a Content Delivery Network for image storage (see AWS CloudFront or Azure CDN or CloudFlare), which really is the best of both worlds -- a secondary storage that can be accessed directly by URL, without even troubling your app -- and not that much extra work. Moving to a CDN is a very easy change if you've isolated your images into their own table.

Or, you could just go for a CDN solution now and never worry about it again.

Title: Should I store images in my database or file system in this application?

Body:
I'm using ASP.NET MVC 4 and SQL Server 2012. I have no problem going for either of these solutions but I want to know which one would fit better in the particular application I'm creating now.

I'm making a sort of a library system application. The only images the application will store are:

Users' profile pictures (1 per user)

Libraries' profile pictures (1 per library)

Book authors' pictures (1 per author)

Book cover images (1 per book)

None of the images stored will need to be of high quality. So obviously the images are not a big part of the application and considering this, I am currently storing the images in my database. Though I noticed something that I think makes for a major con.

The images are retrieved using a Url.ActionLink which leads to a Controller action method that accepts (for example) a bookId parameter before reaching to the database, retrieving that book's image and sending it back. So if a user were to search for books and he ends up getting a list of books along with their images before him, there will be a new call to the action method that retrieves images and a new query to the database for each image listed.

Is there a better way of handling this? Should I reconsider keeping my images in the database or is it not a big issue?

EDIT: Wouldn't consider this question a duplicate because it pertains to a specific type of an application that handles very little image data as as opposed to any type of an application (like in the linked question). Of course when you're not sure how much image data you're gonna be storing it's always best to store images on the file system. This is not such a case. The nature of the answers here versus the answers there shows this.


问:
Balancing between performance, convenience & separation
Consider a web application that works with somewhat sensitive data on reliable, high performance clients.

The data needs to be processed and manipulated. So far I have learned that when possible, data processing should be a serverside concern because of the following reasons (amongst others)

There is no data exposed that shouldn't be

You can't rely on client performance

Nevertheless, I would like to to processing clientside because of the following reasons:

There are a lot of operations that need to be done on the same set of data. If i would do them serverside, I would have to do a lot of requests which will cause ugly & bloated client side code. If I do things on the client, I can use a convenient service which exposes a neat API. This is the main reason for me.

If I load the data on initialization, I don't have to rely on the server further.

The application is used in-house only. I know the clients and don't have to burden the server with operations I know the client is perfectly capable of doing.

So, when can I do data operations client side with good conscience?

答:
Yes, you can.

If the your data operations are about a set of data specific for a client, they should be done on the client.

They are not "data operations" as usually meant. Work on data obtained belong not to data server, but to application server. And the last can easily be done more thin making clients a bit thicker. It is not against some common rules. Finding the correct balance is wholely on you.


答:
One solution would be to publish the information via UDP. Open a specific port for broadcasting, send your data. There is nothing else to do on the provider/server side.

On the client side, open the same port for receiving.

The only downside that I am aware of with this method is that if you miss the broadcast message, you will never see it again. There is no guaranteed delivery.

One upside is that you can have unlimited clients with no additional overhead for the server.

Microsoft has a working example using the UDPClient class.

If you need guaranteed delivery, you can use (among other options) the TCPListener class for your server. You will have to use the TCPClient class for the client. This technique will (more or less) recreate a web server and clients. Writing a RESTful interface would be easier.

One downside is that every client opens a connection (more overhead) to your server.


答:
For windows .net processes to pipe data between themselves they can do so in different ways using WCF using transport layers such as http or named pipes.

Good tutorial for this:
http://tech.pro/tutorial/855/wcf-tutorial-basic-interprocess-communication

Another question you may find helpful: https://stackoverflow.com/questions/7353670/wcf-named-pipe-minimal-example


答:
I've been using Rebus which makes it pretty simple to push messages between applications. It is a .NET library that sits as a layer on top of an underlying transport layer, which could be MSMQ, RabbitMq, or something else.

It does support publish/subscribe. In the case of MSMQ, this is simply implemented that Rebus handles publishing the message to multiple queues. Rebus just needs somewhere it can store a configuration about which subscribes have subscribes to which types of messages.

If you want to step up, you can use NServiceBus, which is a paid product. But I have no experience with that. But it should be easy to migrate an app from Rebus to NServiceBus.


问:
Is it possible to apply Master Theorem for finding the square and cube root
I was asked to calculate the running time of an algorithm which finds the square root and cube root of a given number.

Is it possible to apply Master theorem with regards to this? First, I need to build the recursive relation to it.

Recursive algorithm : (for square root)

The cube root  is also similar  with slightest modification

```<code>float sqrt_recursion(float n, float low, float high) {
    int mid = (low + high) / 2;
    if (Math.abs(mid*mid-n)<0=0.00001) {
        return mid;
    } else {
        if ((mid * mid) > n)
            return  sqrt_recursion(n, low, mid - 1);
        else
            return  sqrt_recursion(n, mid + 1, high);
    }
}
</code>```

Recursive algorithm : (for cube root)

```<code>float cbrt_recursion(float n, float low, float high) {
    int mid = (low + high) / 2;
    if (Math.abs(mid*mid*mid-n)<0=0.00001) {
        return mid;
    } else {
        if ((mid * mid *mid) > n)
            return  cbrt_recursion(n, low, mid - 1);
        else
            return  cbrt_recursion(n, mid + 1, high);
    }
}
</code>```

Above code uses the Newton-Raphson method to calculate the square root.

My Analysis :

I could not exactly determine in which order the loop is executed. It is not exactly as O(log n) , because the mid value is not always reducing rather it moves up and down.

Accodring to me , it do not converge to result as qucikly as binary search does.

Is above analysis correct ?

Please help me in finding the exact running time

答:
Your current recursive code is slightly incorrect, because the type of mid is int and not float. Once corrected, a recursive version of the iterative algorithm is:

final static float EPSILON = 0.00001;

static float sqrt(float n) {
    // Here, I use high = n for simplicity's sake.
    // In a real application, I'd special-case n = 0, …, 4
    // and start with high = n/2
    return recursiveSqrt(n, 0, n);
}

static float recursiveSqrt(float n, float low, float high) {
    float mid = (low + high) / 2;
    float midSquare = mid * mid;

    // This is the base case of the recursion
    // which corresponds to a loop condition.
    if (math.abs(midSquare - n) < EPSILON) return mid;

    // Anything that's not the base case recurses.
    // Here, we recurse either into the left or right half
    // of the currently processed interval
    if (midSquare > n) return recursiveSqrt(n, low, mid);
    else               return recursiveSqrt(n, mid, high);
}
```

Now, the Master Theorem is interested not in the specific implementation of the recursive function, but in three properties:

What is the running time at each step, excluding the recursion?

How often do we recurse per invocation?

How does the problem size shrink with each invocation?

Together, these define the parameters f(n), a, and b in the Master-Theorem equation

T(n) = a · T(n/b) + f(n)

that describes the complexity of some recursive functions. Note that the f(n) function is also a complexity expression. It describes the per-iteration overhead, which may depend on the problem size in each iteration.

The answer to the first question is that each invocation has constant running time (recursion excluded), because arithmetic operators, comparison operators, and Math.abs() take constant time. The only way to have non-constant time is to use loops or to invoke a function or method that has non-constant time – and we don't do any of that. Therefore, f(n) = O(1).

Next, we have to determine how often we recurse. While the code contains two invocations of the recursive function, only one of them will be executed in any iteration. So a = 1.

Finally, we have to look at the problem size. The problem size of each iteration is not our parameter n. Instead, it is the range high - low. At each iteration, you halve this range by calculating the midpoint. Therefore, b = 2. It doesn't matter where this range is and whether an iteration picks the lower or upper half. Only the size of the range matters. The initial size of the range is n.

Now we have determined all parameters necessary to apply the Master Theorem.

Our parameters do not match the first case where f(n) = O(nc) for some parameter c with c < logb(a): Here we have c = logb(a) = 0.

However, it immediately matches the second case where f(n) = Θ(nc · logk(a)) with k ≥ 0 and c = logb(a) (The character Θ that looks like a zero is actually the Greek letter uppercase Theta). Here, c = k = 0.

Then, the total complexity is T(n) = Θ(nc · logk + 1(n)) = Θ(log n).

Interpretation: This method for approximating a square root is essentially a binary search over the ordered sequence of all numbers between zero and n. This sequence is discrete, and all numbers in the sequence are 2·epsilon apart. At each iteration, we have lower and upper bounds delimiting a sublist which must contain the wanted list item. Because the sequence is ordered, we look at the item in the middle of the sub-sequence and then continue searching in the left or right sublist, depending on whether the middle item was larger or smaller than the wanted item. Consequently, this algorithm must have the same time complexity characteristics as a binary search.

Body:
Your current recursive code is slightly incorrect, because the type of mid is int and not float. Once corrected, a recursive version of the iterative algorithm is:

final static float EPSILON = 0.00001;

static float sqrt(float n) {
    // Here, I use high = n for simplicity's sake.
    // In a real application, I'd special-case n = 0, …, 4
    // and start with high = n/2
    return recursiveSqrt(n, 0, n);
}

static float recursiveSqrt(float n, float low, float high) {
    float mid = (low + high) / 2;
    float midSquare = mid * mid;

    // This is the base case of the recursion
    // which corresponds to a loop condition.
    if (math.abs(midSquare - n) < EPSILON) return mid;

    // Anything that's not the base case recurses.
    // Here, we recurse either into the left or right half
    // of the currently processed interval
    if (midSquare > n) return recursiveSqrt(n, low, mid);
    else               return recursiveSqrt(n, mid, high);
}

Now, the Master Theorem is interested not in the specific implementation of the recursive function, but in three properties:

What is the running time at each step, excluding the recursion?

How often do we recurse per invocation?

How does the problem size shrink with each invocation?

Together, these define the parameters f(n), a, and b in the Master-Theorem equation

T(n) = a · T(n/b) + f(n)

that describes the complexity of some recursive functions. Note that the f(n) function is also a complexity expression. It describes the per-iteration overhead, which may depend on the problem size in each iteration.

The answer to the first question is that each invocation has constant running time (recursion excluded), because arithmetic operators, comparison operators, and Math.abs() take constant time. The only way to have non-constant time is to use loops or to invoke a function or method that has non-constant time – and we don't do any of that. Therefore, f(n) = O(1).

Next, we have to determine how often we recurse. While the code contains two invocations of the recursive function, only one of them will be executed in any iteration. So a = 1.

Finally, we have to look at the problem size. The problem size of each iteration is not our parameter n. Instead, it is the range high - low. At each iteration, you halve this range by calculating the midpoint. Therefore, b = 2. It doesn't matter where this range is and whether an iteration picks the lower or upper half. Only the size of the range matters. The initial size of the range is n.

Now we have determined all parameters necessary to apply the Master Theorem.

Our parameters do not match the first case where f(n) = O(nc) for some parameter c with c < logb(a): Here we have c = logb(a) = 0.

However, it immediately matches the second case where f(n) = Θ(nc · logk(a)) with k ≥ 0 and c = logb(a) (The character Θ that looks like a zero is actually the Greek letter uppercase Theta). Here, c = k = 0.

Then, the total complexity is T(n) = Θ(nc · logk + 1(n)) = Θ(log n).

Interpretation: This method for approximating a square root is essentially a binary search over the ordered sequence of all numbers between zero and n. This sequence is discrete, and all numbers in the sequence are 2·epsilon apart. At each iteration, we have lower and upper bounds delimiting a sublist which must contain the wanted list item. Because the sequence is ordered, we look at the item in the middle of the sub-sequence and then continue searching in the left or right sublist, depending on whether the middle item was larger or smaller than the wanted item. Consequently, this algorithm must have the same time complexity characteristics as a binary search.


问:
Remake old web forms application in asp.net mvc
I've inherited the code maintenance of a complex web site for a customer that continuously requests enhancements for it. This application took years to develop and I'm facing increased difficulties to enhance it. It's organized but at the same time the .net code is mixed with ajax, javascripts and old school html that it takes me days to figure out how some pages work.

First off, I not new to asp.net but I'm not familiar with the new MVC stuff but from what I've read it seems to be a step in a better direction.

The current code is all in one big dll. The application code is divided into multiple folders representing the different departments and each department has it's own pages for handling general stuff like employee management, reports, budget and also their own information.

For example, even though each department uses a different webpage for employee information handling, they want different fields and so it was simpler to create different pages than to use a single page that adapts to each department.

But it is really a nightmare to maintain right now and I would like to create a parallel project where I could start a fresh project, create a better structure and from there start migrating the old code to this new environment and refactor it as I go.

The idea is to migrate the old application to a new web site that has a similar look while maintaining both operating until everything is running in the new site.

It may sound insane but it really is used extensively for hundreds of people everyday and it bugs me that I have to modify crappy code to make it work.

How would you go about this issue?

[edit]
If found this link Things You Should Never Do on another post, very much to the point of my question.

答:
I answered a similar question (which I don't think is a duplicate). My answer has some good, practical tips on taming a WebForms application.

For you, I would recommend creating a Test project in Visual Studio. Utilize SpecFlow and Coded UI Tests, Selenium or Watin, then test the crap out of the site. Once you've got the site pretty well covered with tests, start refactoring code, one User Control at a time. Follow best practices. The ones below I've used with success in this situation:

Organize your database access code using the Repository Pattern

Don't use DataSets in your User Controls. Use Domain Models instead.

Move all business logic into the domain models. Watch Crafting Wicked Domain Models for some good tips.

Create helper classes that initialize common controls, such as drop down lists

This is a marathon, not a sprint.

OwnerDisplayName: Hfux


问:
Pair programming via mailing list
I've started work on a large, open-source project recently. This project uses a mailing list for development, thus all patches must be mailed to this mailing list. This marks a change from my previous work where I used Gerrit or GitHub pull requests.

One of the biggest issues I'm finding is how to collaborate on these patches. I have my local copy of the upstream repo, which I work on, but there isn't a "shared repo". This means I can't work on a features with teammates via feature branches or Gerrit topics (my previous workflow). The best I can do is submit patches back and forth via email, which is painful.

Given the prevalence of projects using this style of development, I imagine it's a "solved" problem. As such, could anyone recommend a general practice to follow for this kind of development?

答:
The fact that the central repo isn't shared does not stop you from sharing your repo.

When you want to work on something closely with somebody else, just set up a clone on github, gitorious or similar and share there. When time comes to push it to master you still submit via the mail process, but while cooking the changeset, you can share in another way.

In fact there is little difference between this and github pull requests. With pull requests you are still publishing your clone and requesting merge from it. So do everything the same, just the request goes through another channel (ok, there will be rebase instead of merge as the mailed patches don't preserve commit identity, but that shouldn't be big problem; you know the old versions are obsolete when it's integrated).

Title: Pair programming via mailing list


问:
Are there any benefits to removing unused using statements in a VS project?
Are there any benefits to removing unused using statements in a VS project (such as can be done using Resharper), or will VS automatically take care of that when building/deploying?</p>

答:
Removing unused code, is just extra baggage and hard to measure the efficiencies gained.

Removing unused code, brings down the compilation time, I am working on a project which takes anywhere from 15 to 20 minutes, there is tons of unused code. Eliminating unused code decreased the compile time to ~7 minutes. This makes a diff when there are many developers on the team, this saves everyone time to quickly build and test.

If you have automated your build and unit tests, you have now removed unit tests you do not need. again this is reduced time taken to run unit tests. Just increased efficiency in your Continuous Build management process.

Unused code results in bigger foot print of your binaries. Having a smaller code foot print will reduce the time taken to load/start up initially. Though the gains may be very meager and subjective.


问:
Database schema for a ToDo list
I am trying to make a very simple todo list application with PHP, MySQL, Jquery templating and JSON... However, my schema seems to complicate things in JSON.

What's the best way to do it?

A new table for each list, containing the items.

or

a table for lists, and a table for items that are joined somehow? Because I have tried this and it doesn't seem like the right way to do it? Example http://jsfiddle.net/Lto3xuhe/

答:
Option 2 is a traditional master/detail setup.  That is probably what you want here.  Put the list id in the items table, and join on that.  The schema shouldn't impact the JSON.  Your query might look something like:</p>

```<code>select lists.name as list_name, items.name as item_name
from items
join lists on (lists.id = items.list_id)
</code>```

Title: Database schema for a ToDo list

Body:
Option 2 is a traditional master/detail setup.  That is probably what you want here.  Put the list id in the items table, and join on that.  The schema shouldn't impact the JSON.  Your query might look something like:

select lists.name as list_name, items.name as item_name
from items
join lists on (lists.id = items.list_id)


问:
Object in Business layer same as DTO with logic?
Let's say I have a Spring MVC project, in which I'm using DTO to get data from a database and to pass data to the UI. Let's suppose that I have a UserDTO and in my business layer I have to do something with that, but I need to put logic in the User and the DTO pattern says that no logic is allowed (or just simple logic).

Should I transform this UserDTO to a User object in order to have the logic and then make a UserDTO to give it to the UI? Or just use the UserDTO and process it in the business layer?

Thanks

答:
Your data layer should be giving you domain objects, not data transfer objects.

The database query would return User class instances which class houses the domain logic. Your business service that is calling the data layer should be where you do whatever steps that are needed for your use case, such as calling multiple data access objects and obtaining all necessary domain information, invoking all appropriate business functions and finally mapping that data into your data transfer object for the UI rendering process.

There are use cases where your data layer may return value objects that may not necessarily be entities as they are stored in the datastore.  For example, if you have a table with a large number of columns but you are only interested in a small subset of the columns or a specific view across several entities, you may have your ORM return you a list of instantiated objects that aren't managed entities. These value objects are often immutable but aren't necessarily required to be.


答:
There's a joke I heard awhile back:

Q How does a BASIC coder count to 10?

A 1,2,3,4,5,6,7,8,9,10

Q How does a C coder count to 10?

A 0,1,2,3,4,5,6,7,8,9

Q How does a DBA count to 10?

A 0,1,many

The truth behind this joke is that once you have two (or more) of the same thing in a database structure (columns or tables), you're doing it wrong.

A schema that looks like:

```<code>+----------+
| id       |
| name     |
| phone1   |
| phone2   |
|          |
+----------+
</code>```

Is wrong because where will you put a third phone number if someone has it?

The same applies to tables themselves.  Its also a Bad Thing to be modifying the schema at runtime, which the "new table for each list" seems to imply.  (Related: MVC4 : How to create model at run time?)

And thus, the solution is to create a todo list that is comprised of two tables.  There are two things you have - lists and items.

So, lets make a table structure that reflects this:

```<code>+----------+       +-------------+
| List     |       | Task        |
+----------+       +-------------+
| id (pk)  <---+   | id (pk)     |
| name     |   +---+ listid (fk) |
|          |       | desc        |
|          |       |             |
+----------+       +-------------+
</code>```

The list has an id (the primary key for the list), and a name.  The task has an id (the primary key) a listid (a foreign key) and the description of the task.  The foreign key relates back to the primary key of another table.

I will point out that this doesn't begin to encompass all the possibilities in various requirements for the software and the table structure to support it.  Completed, due date, repeating, etc... these are all additional structures that will likely need to be considered when designing the table. That said, if the table structure isn't one that is appropriately normalized (or realizing the tradeoffs that you've made because it's not normalized), you will have many headaches later.

Now, all that relates to writing this as a relational database.  But thats not the only type of database out there.  If you consider a list to be a document the document styled nosql databases may also offer an approach that isn't wrong.

While I'm not going to delve into it too far, there are numerous tutorials out there for todo lists in couch.  One such that came up with a search is A simple Task-list application in CouchDB.  Another shows up in the couchdb wiki: Proposed Schema For To-Do Lists.

In the approach appropriate for a couch, each list is a JSON document stored in the database.  You would just put the list in a JSON object, and put it in the database.  And then you read from the database.

The JSON could look like:

```<code>[
 {"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
 {"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
 {"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
 {"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}
]
</code>```

(from creating a shopping list with a json file on Stack Overflow).

Or something approaching that.  There is some other record keeping that couch has as part of the document.

The thing is, its not the wrong way to approach and a todo list in a document database may be perfectly suited to what you are trying to do with less concept overhead for how to do it.

Title: Database schema for a ToDo list

Body:
I am trying to make a very simple todo list application with PHP, MySQL, Jquery templating and JSON... However, my schema seems to complicate things in JSON.

What's the best way to do it?

A new table for each list, containing the items.

or

a table for lists, and a table for items that are joined somehow? Because I have tried this and it doesn't seem like the right way to do it? Example http://jsfiddle.net/Lto3xuhe/

Body:
There's a joke I heard awhile back:

Q How does a BASIC coder count to 10?

A 1,2,3,4,5,6,7,8,9,10

Q How does a C coder count to 10?

A 0,1,2,3,4,5,6,7,8,9

Q How does a DBA count to 10?

A 0,1,many

The truth behind this joke is that once you have two (or more) of the same thing in a database structure (columns or tables), you're doing it wrong.

A schema that looks like:

+----------+
| id       |
| name     |
| phone1   |
| phone2   |
|          |
+----------+

Is wrong because where will you put a third phone number if someone has it?

The same applies to tables themselves.  Its also a Bad Thing to be modifying the schema at runtime, which the "new table for each list" seems to imply.  (Related: MVC4 : How to create model at run time?)

And thus, the solution is to create a todo list that is comprised of two tables.  There are two things you have - lists and items.

So, lets make a table structure that reflects this:

+----------+       +-------------+
| List     |       | Task        |
+----------+       +-------------+
| id (pk)  <---+   | id (pk)     |
| name     |   +---+ listid (fk) |
|          |       | desc        |
|          |       |             |
+----------+       +-------------+

The list has an id (the primary key for the list), and a name.  The task has an id (the primary key) a listid (a foreign key) and the description of the task.  The foreign key relates back to the primary key of another table.

I will point out that this doesn't begin to encompass all the possibilities in various requirements for the software and the table structure to support it.  Completed, due date, repeating, etc... these are all additional structures that will likely need to be considered when designing the table. That said, if the table structure isn't one that is appropriately normalized (or realizing the tradeoffs that you've made because it's not normalized), you will have many headaches later.

Now, all that relates to writing this as a relational database.  But thats not the only type of database out there.  If you consider a list to be a document the document styled nosql databases may also offer an approach that isn't wrong.

While I'm not going to delve into it too far, there are numerous tutorials out there for todo lists in couch.  One such that came up with a search is A simple Task-list application in CouchDB.  Another shows up in the couchdb wiki: Proposed Schema For To-Do Lists.

In the approach appropriate for a couch, each list is a JSON document stored in the database.  You would just put the list in a JSON object, and put it in the database.  And then you read from the database.

The JSON could look like:

[
 {"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
 {"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
 {"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
 {"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}
]

(from creating a shopping list with a json file on Stack Overflow).

Or something approaching that.  There is some other record keeping that couch has as part of the document.

The thing is, its not the wrong way to approach and a todo list in a document database may be perfectly suited to what you are trying to do with less concept overhead for how to do it.


答:
I wouldn't try to tie your UI representation  or transmission of data to the UI directly to how you intend to store the data.  By keeping the two separate and using some middleware logic to marry the two allows you to easily alter either side without possibly impacting the other in a critical way.

From a data storage perspective, you would likely use option 2 which follows the typical normalized data pattern where common parts are factored out into their own tables to avoid repetition and to minimize database bloat.

From a view perspective, you simply need to use a database query to join the pertinent data into a result set and then iterate that result and generate a json response applicable to your UI needs.  What you likely want to do is feed the data into JSON so that it fits your UI needs as best as possible, often eliminating the need for additional scripting logic in your web pages.

Title: Database schema for a ToDo list


问:
Is a newline convention not part of an encoding?
There are different conventions of representing the new line character in different types of OSes.

Does the newline convention have nothing to do with what encoding is used?

Is the newline convention not part of any(most) encoding method (e.g. ASCII, utf8, cp1253, ...)?

答:
While the said encodings specify the code for new line and carriage return, it is not part of the encoding whether or not you should use both, as is normal in a Windows environment, or just new line which is normal in a Unix environment.

Also worthy of note is that on Unix, the newline is treated as a sort of "end of line" marker, and thus the last line in the file should also end with a newline. It is not common in Windows applications* to follow this practice, and thus normally text files created by a Windows application do not have an end-of-line marker after the last line.

* unless that application is in fact an application written for a Unix environment, and ported to Windows, e.g. vim.


答:
Encoding methods deal with how to represent characters as binary data. For example, the letter "A" has a particular bit sequence that describes it. Unicode defines several methods to translate between code points and their bit representation. Code pages do the same but with only 8 bits. This is the purpose of encoding schemes.

Which newlines are used (CRLF, LF) is completely irrelevant to how those nonprintable characters are represented in a particular encoding.

Title: Is a newline convention not part of an encoding?

Body:
There are different conventions of representing the new line character in different types of OSes.

Does the newline convention have nothing to do with what encoding is used?

Is the newline convention not part of any(most) encoding method (e.g. ASCII, utf8, cp1253, ...)?


答:
SignalR might be a good candidate if you don't need guaranteed delivery, and you're simply looking to periodically send relatively small amounts of data to/from N* clients and servers (e.g. real-time dashboard, instant messaging, multiplayer game, etc...). It can also scale quite well using backplanes (currently supports Redis, Azure Service Bus, SQL Server, or writing your own).

While SignalR is focused towards ASP.NET development (it abstracts the implementation of WebSockets), you can also use it in non-web applications (i.e. WinForms, WPF, Windows services, etc...).

Plus, SignalR operates over standard HTTP/S ports (80, 443), so you typically don't need to create firewall exceptions to get things talking correctly.

Another bonus is that you can have two way communication between clients and/or server(s).

Here's a few links you might find useful:

Using SignalR in WinForms and WPF

Microsoft Virtual Academy - SignalR Courses


问:
Should jars that are only gonna be used in one project be deployed to Nexus server
I guess the title says it all. There is a debate at our firm, weather we should deploy internal jars, which are only going to be used in one specific project, to Nexus or is there any better solution? The argument for not deploying it to Nexus is that it will not be reused so there is no point in having it there.</p>

答:
The jar exists.  Its out there.  Trying to ignore that reality by sticking it in a lib directory as a binary leads to problems down the road.

Now, if you've got Nexus, you've got Maven.  This jar is a dependency of the project.  If you are putting the jar in a path and bypassing maven, you are going to find that you are fighting against the tool itself which will lead to problems.

In particular, the biggest problem you will encounter is that it means the jar will be difficult to update.  You've checked in a binary into that application's source tree.  This means that if you need to update the jar with a new value for something, you need to build the jar, copy it to the proper spot, check that in too.  Woe if you ever find that you need another dependency for the jar (which then becomes a dependency to the application).

If the jar is 'only used in one spot', why is it even a separate library?  Why isn't it part of the class structure of that application instead?  Building the jar and then copying the jar into the lib path of the application seems like a lot of work.

Instead, having the jar deployed to nexus means that the jar is also part of Maven's structure.  It has its dependencies.  It has its version. It can be snapshotted to work with. It has its plugins to build.  In short, when you work with the tool, the toolchain ideally supports and aides you to make it easier.  When you try to bypass the toolchain, you get specific setups that become fragile and possibly harder to test and deploy consistently.

Put the jar in maven.  Deploy the jar to nexus and have it be part of the dependencies.  It will make source control easier and builds easier.


问:
Strategy for creating a websocket relay?
I own a Raspberry Pi and would like to use it as some sort of websocket relay, so that all people who visit a specific webpage would be able to communicate with each other. The key thing about this is that I want to define my communication protocol in Javascript on the client side. (IE: The messages that clients send to each other)

Are there any strategies for accomplishing this? Is such a relay already available via some sort of Apache extension (or similar)? Knowing C#, my first thought is to develop a C# service application that would run on top of Mono on the Pi. Does that sound like a good idea?

In my specific case, I'm looking to create a HTML5 multiplayer game. I know there are blindingly obvious cheating issues with my proposed implementation, but please keep in mind that this is an experiment, not something serious.

答:
Not sure if it will help you but I have been developing a multiplayer HTML5 game for about 6 months now and I use C# as a server with Alchemy websockets. Alchemy seems like a stable library only gotcha I have found is it uses a timeout value that if set too low will disconnect the clients but not tell the client they have been disconnected which will throw an exception if that client tries to send data after that. The C# client actually uses a ping/pong and doesn't have this glitch only the Javascript clients do. I got around this glitch by setting the alchemy timeout to 10 minutes and running a background thread on the server that goes through all connected clients and sends a "ping" packet that the client watches for and responds to and it keeps the connection open with no exceptions (have tested this on a server running for a week with 3 clients connected for a week)

Alchemy does run fine under mono which is why i chose it as I'm not decided yet wether the game server will run on a linux server or windows server yet.

Just my 2 cents on your idea.


问:
How would you go about compressing a list of integers that are non unique and retain the original order?
Let's start out with an example

```<code>[1,1,1,5,3,1,1,2,78,2,3,1,1,...,1]
</code>```

As you can tell by the example, 1 is repeated a lot, but there will be outliers (like 78, and really anything that isn't 1).

The catch to my question is, when I uncompress the numbers, they must retain the original order. The algorithms that I have found generally deal with unique numbers, either sorted or unsorted. I wouldn't mind using one of those, but since my integer list is not unique, I'm wondering if there is anything currently out there that is optimized for this sort of thing.

Quickly thinking, My first idea was to do a normal compression tree and just map in values for patterns.

My second Idea was to just describe repeating numbers like so: 3->1, 1->5, 1->3, 2->1, 1->2, 1->78, 1->2, 1->3, x->1.

Of course this only works if values are constantly repeated, which generally the lower numbers will be repeated a lot, but I can't be 100% positive that that will be the case every time.

答:
The simplest approach to this is simple run length encoding.  This is part of what you describe in "My second Idea was to just describe repeating numbers like so: 3->1, 1->5, 1->3, 2->1, 1->2, 1->78, 1->2, 1->3, x->1."

This works for a lot of data and you will frequently see it in bitmaps (where every value is a 0 or a 1 - thats why its in the 'image' section of the Data Compression Template on Wikipedia).  The difficulty with this method is that the more irregular the data, the the smaller the runs and the more bookkeeping necessary.  Essentially with RLE, the book keeping is with each block.

You could also look to Huffman coding.  Its quite a bit more work to do than simple RLE, but it also can save quite a bit more space.

The thing is that your numbers, they're still fixed sized.  Lets say they're all bytes (8 bits) rather than ints or longs.  Now, the 1 is actually 0000 0001 and 78 is 0100 1110.  The trick with huffman encoding is that we can make 1 take up 1 bit instead because it is so common.

For the sequence [1,1,1,5,3,1,1,2,78,2,3,1,1,1] we have 1, 5, 3, 2, 78 as symbols - 5 symbols total.

This could give us a Huffman encoding table that looks like:

```<code>1  => 1
2  => 01
3  => 0010
5  => 0011
78 => 0001
</code>```

This would allow us to encode the above data from:

```<code>0000 0001, 0000 0001, 0000 0001, 0000 0101, 0000 0011, 0000 0001,
0000 0001, 0000 0010, 0100 1110, 0000 0010, 0000 0011, 0000 0001,
0000 0001, 0000 0001
</code>```

To:

```<code>1, 1, 1, 0011, 0010, 1, 1, 01, 0001, 01, 0010, 1, 1, 1
</code>```

Which should be clear is much less information.  Yes, you will still need to pass the book keeping information about what those numbers actually mean with it too.  You've got something that compresses a bit tighter than RLE does in most cases because of the common bookkeeping information than it would with the information being stored with each run.

Body:
The simplest approach to this is simple run length encoding.  This is part of what you describe in "My second Idea was to just describe repeating numbers like so: 3->1, 1->5, 1->3, 2->1, 1->2, 1->78, 1->2, 1->3, x->1."

This works for a lot of data and you will frequently see it in bitmaps (where every value is a 0 or a 1 - thats why its in the 'image' section of the Data Compression Template on Wikipedia).  The difficulty with this method is that the more irregular the data, the the smaller the runs and the more bookkeeping necessary.  Essentially with RLE, the book keeping is with each block.

You could also look to Huffman coding.  Its quite a bit more work to do than simple RLE, but it also can save quite a bit more space.

The thing is that your numbers, they're still fixed sized.  Lets say they're all bytes (8 bits) rather than ints or longs.  Now, the 1 is actually 0000 0001 and 78 is 0100 1110.  The trick with huffman encoding is that we can make 1 take up 1 bit instead because it is so common.

For the sequence [1,1,1,5,3,1,1,2,78,2,3,1,1,1] we have 1, 5, 3, 2, 78 as symbols - 5 symbols total.

This could give us a Huffman encoding table that looks like:

1  => 1
2  => 01
3  => 0010
5  => 0011
78 => 0001

This would allow us to encode the above data from:

0000 0001, 0000 0001, 0000 0001, 0000 0101, 0000 0011, 0000 0001,
0000 0001, 0000 0010, 0100 1110, 0000 0010, 0000 0011, 0000 0001,
0000 0001, 0000 0001

To:

1, 1, 1, 0011, 0010, 1, 1, 01, 0001, 01, 0010, 1, 1, 1

Which should be clear is much less information.  Yes, you will still need to pass the book keeping information about what those numbers actually mean with it too.  You've got something that compresses a bit tighter than RLE does in most cases because of the common bookkeeping information than it would with the information being stored with each run.


答:
If you are using sql server (2008 or beyond) you can store them in the database as blobs or using FILESTREAM.  As other commentors have pointed out, I would not go with a propertiery store the file on disk approach as you will have to manage consistency in that scenario.

A good link on FILESTREAM can be found here:

FileStream Guidelines

Some general rules:

In SQL Server, BLOBs can be standard varbinary(max) data that stores
the data in tables, or FILESTREAM varbinary(max) objects that store
the data in the file system. The size and use of the data determines
whether you should use database storage or file system storage. So, in
a nutshell, these are the typical scenarios where this feature is best
suited:

If you are storing BLOBs with an average size of 1MB or
more.

When fast read access is adamant.

When you must access BLOBs from your application's middle tier code.

Overall, the main advantages of using FILESTREAM over other options are:

Storage and retrieval of BLOBs is made together with relational data in a single
data store.

Yes, the BLOBs are included in database backups and restores.

Inserting, updating and deleting BLOBs and your relational data happens in the same database transaction.

The 2 GB max size for a varbinary(max) column does not apply; you are only limited by the available space on the NTFS file system.

The SQL Server buffer pool memory is not used to operate on BLOBs; in previous versions large BLOBs could consume a lot of this memory.

All BLOB access can be performed from .NET code, allowing your middle tier code to easily work with these objects.

The NTFS file system can save and retrieve large BLOBs more efficiently than SQL Server.

Still, a few restrictions apply to FILESTREAM implementations:

FILESTREAM feature is not supported with Database Mirroring.

FILESTREAM data containers cannot share the same directory or be nested.

FILESTREAM data is not encrypted even when transparent data encryption (TDE) is enabled.

ContentLicense: CC BY-SA 4.0


问:
How can I run a script/subroutine on a Web Server and have that subroutine remain private (eg. Key Generator)?
My Problem: I have been tasked with re-implementing a software key generator routine on an external web server running cPanel v.11.44.1.18. Currently, the key generator is implemented using a proprietary Database Management System (DBMS) which we run on a local server.

We want to relegate the key generator functionality to an external web server so that we can use our local server some something entirely different. So essentially, I have the algorithm written in a proprietary language, and I need to choose a cPanel supported environment on our external webserver to re-implement the algorithm in such a way that it can be called by the client's browser, updating a database, without the client being able to download the subroutine and view the code.

Our cPanel Hosting Package Offers Support For:

MySQL Databases

Ruby on Rails

Ruby Gems

Perl

CGI

PHP

My Research Shows:

I can create a Perl script and execute it as (or through) a CGI file.
My (unsure) Idea for Implementation:

Implement the database back-end using MySQL Implement the keygen subroutine and database update subroutine using a custom Perl module(s)

Make the Perl module readable/executable by the web server, but hidden from everyone else

Use a CGI script as an interface between the client browser and the keygen Perl module

What I would really appreciate is someone with some expertise on this kind of arrangement to tell me:

If what I am thinking is possible (i.e. am I on the right track)

If there are any errors in my logic

If there is a better way to do this

What permissions I should use to make the script non-hackable

This would be much easier (because there would be a lot more options) if we were using a Virtual Private Server (VPS) as our webserver, but we are limited to our hosting package and the cPanel features it offers. I would appreciate any help/advice I can get.

答:
I think your approach is broadly sound.

I wouldn't go down the route of using an MVC framework, it's a bit of an overkill for this kind of thing. If you're using, for example, Perl's CGI module, then the output of the key as a simple text string or JSON string etc. is very simple, you just ask the CGI script to output a content header and the content as print strings, or the equivalent CGI output calls in your CGI scripts.

So, your CGI script does everything - it uses the DB connector (DBD::mysql through DBI), the function to calculate the next key is also defined in that single script, and a simple few lines to print the header to STDIO along with the key, and that's all you need.

If you think you might change the key generation code or use it elsewhere then modularise it, otherwise just define it inline.

If your web server is set to execute perl scripts in a give directory then nobody will be able to read the source anyway, it just gets executed by the server and the output (to STDOUT so anything 'print'ed is sent as the response to the client. The server will deal with setup and teardown of memory etc. Simple!


问:
How do I cope with a manager who’s always interfering in what I do, but doesn’t really understand it?
We've all had them, managers who have either come from sales or last looked at code 10 or more years ago but think they know how to write code.

What can I do to give the impression that I'm grateful for their intervention, but keep it as short as possible so I can get on with my work?

Or, should I be engaging more with the manager to educate them with modern coding techniques and practices? After all, a manager who understands these will be able to talk sensibly to clients and more senior management when discussing the project and its timescales.

答:
Sometimes one just has to sit down and listen, even when we don't want to.

One can only hurt the dignity of a person by not paying them attention.

Your manager is a person. Treat him like one. Look at him as if he were some guy in the street. No titles.

Doesn't that make him someone that may need a friend, someone who may feel lonely?

Have you thought about it from an emotional point of view?

Is he trying to convey an implicit message?

Talk to him. Just not about the problem. Ask him how is life going. He may feel appreciated and thus provide you with less work anxiety.

Have you considered or done this already?

If not, then why?


问:
Should one value simpler code over performance when returning multiple values?
I'm too often facing situations where I need to get several types of information from a method. I usually think long and hard to circumvent these situations but I'm thinking it's pointless work that I'm doing. My question: should I prefer to take a slight performance hit in these situations, like iterating over an array twice for example (resulting in slower but cleaner code) or try to return everything at once with an instance of a custom helper class?

Here's a case example for the sake of it

```<code>char[] arr = {'a', 'b', 'a', 'c', 'a'};
int count = 0;  // 'a' and 'b' count
String word= "";  // 'a's and 'b's glued together in their occurring order
for (int i = 0; i < arr.length; ++i) {
    for (int j = 0; j <= arr[0].length; ++j) {
        if (arr[i][j] == 'a' || arr[i][j] == 'b') {
            ++count;
            word += Character.toString(arr[i][j]);
        }
    }
}
// return both 'count' and 'word' inside a new object or iterate twice?
</code>```

答:
If the code change results in a...

measurable performance improvement that

satisfies a non-functional software requirement, and

you cannot satisfy the requirement using simpler code

...then make the code change.  Otherwise, you're almost always better off writing code that is easier to understand and more maintainable.


问:
IOC Between Presentation and Infrastructure Layer
Question:

I would like to set forth dependency mapping from a *.config file from a project that has no reference to the project that contains the concrete class.

Scenario:

I'll be using terms from C#, Microsoft Unity and Visual Studio: I've got a presentation layer with a web service project and a winform project, an infrastructure layer that communicates with repositories, and there is a core business logic layer that defines interfaces that the infrastructure must implement.

Projects:

Presentation:

DIApplication.WebServices - references the Core + DependencyResolution projects

DIApplication.Winform - references the Core + DependencyResolution projects

Infrastructure:

DIApplication.Data - Communicates with repositories, references the Core

DIApplication.DependencyResolution - Registers to the dependencies from Core to Data projects. These are the only two projects it references

Core:

DIApplication.Core - Defines interfaces, references nothing

Example:

For an example I'll say I have DIApplication.Core.IRepository interface and DIApplication.Data.RepositoryA class and DIApplication.Data.RepositoryB class.

It's fine to say that the DependencyResolution project will register the dependencies:

```<code>//If Application == WebService
container.RegisterType<IRepository , RepositoryA >();
//Else
container.RegisterType<IRepository , RepositoryB >();
</code>```

But what I would like to do is that the Webservices Web.config maps IRepository to RepositoryA, while the Winforms App.config maps IRepository to RepositoryB

Webservices:
    ```< register type="DIApplication.Core.IRepository, DIApplication.Core" mapTo=" DIApplication.Data.RepositoryA, DIApplication.Data" />```

Winforms:

    ```< register type="DIApplication.Core.IRepository, DIApplication.Core" mapTo=" DIApplication.Data.RepositoryB, DIApplication.Data" />```

The problem (I believe) is that neither DIapplication.Webservices or Winforms knows about DIapplication.Data, so it breaks on the final portion of this call in DIApplication.DependencyResolution:

```IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container);```

With the error: ```The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
```

Is there any way to get around this without having to include a reference to DIApplication.Data within both DIApplication.Webservices and Winforms?

Maybe I'm looking at this the wrong way. I know that it kind of breaks the notion of separation of concern, where the presentation layer shouldn't know nor care how data is being persisted to repositories, just that it is. But I also want to drive the dependencies based on what project is running.

答:
The context of your application decides everything.

To illustrate why this is true, let us first start with the purpose for inversion of control or IOC.  The purposes behind IOC are extensibility and horizontal scaling.

In extensibility, the application needs to decide what implementation to use under a particular set of circumstances.  For example, if the user chooses to pay via PayPal, it needs to choose the PayPalPaymentProvider implementation rather than the Authorize.NET implementation.

For horizontal scaling, the implementation is decoupled from the application code so that you can easily scale up by writing new implementations and setting those within the context of your application.  For example, if my application currently uses MySql, but I'm now to the point where MySql isn't performing well because my application has become too popular, using IOC I can simply write a new database implementation that is SQL specific and throw out the MySql code without having to change any application logic at all.

All of that being said, let's add the fact the presentation layer is nearly always tied to a specific environment that it needs to run under.  Unless you either write your own application host or OS or you abstract your entire UI into its own project that is then hosted by a context project, the project that contains your UI IS going to be the decision maker for everything implementation related.

Now, to answer your question.  You do not need to have a reference to the DIApplication.Data project in your DIApplication.Webservices or DIApplication.Winforms projects and you don't want to reference it directly because then it defeats the purpose of using the IOC.  However, you will need to copy the dll for DIApplication.Data into the context of your applications so that it can read the assembly.  Defining what implementation you want to use for the IOC in the web.config and app.config is good practice.

However, for the IOC to be able to read and instantiate the concrete implementation, it must be able to find it.  The idea here is that you could swap out that dll with a different concrete implementation, change the configuration file to point to the new concrete instance and everything would continue to work without needing to rebuild the application at all, much less having to change any code.

So, to summarize the answer, all you should really need to do at this point is use a post-build action to copy the concrete implementation into the bin folders for your Windows Forms and Web applications.


答:
Premature Optimization is the root of all evil.

As Donald Knuth said,

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Regardless of language, write your code to be as clear as you can.  If looping twice really results in clearer code, go ahead and write that.  A descent compiler may refactor away the second loop, or the overhead may be bottlenecked by other areas of your program.  Unless your software is very widely used, it's likely that the time your successor spends trying to decipher a quick but complicated block of code will be more expensive than the fractionally increased runtime.

If, after testing, you find that a given program is running unacceptably slow, a refactor to the more complex means may be appropriate.  But these situations are often difficult to identify in advance, because of this uncertainty more than anything else, you should err on the side of clarity over "performance" whenever such are in contention.

Title: Should one value simpler code over performance when returning multiple values?

Body:
I'm too often facing situations where I need to get several types of information from a method. I usually think long and hard to circumvent these situations but I'm thinking it's pointless work that I'm doing. My question: should I prefer to take a slight performance hit in these situations, like iterating over an array twice for example (resulting in slower but cleaner code) or try to return everything at once with an instance of a custom helper class?

Here's a case example for the sake of it

```<code>char[] arr = {'a', 'b', 'a', 'c', 'a'};
int count = 0;  // 'a' and 'b' count
String word= "";  // 'a's and 'b's glued together in their occurring order
for (int i = 0; i < arr.length; ++i) {
    for (int j = 0; j <= arr[0].length; ++j) {
        if (arr[i][j] == 'a' || arr[i][j] == 'b') {
            ++count;
            word += Character.toString(arr[i][j]);
        }
    }
}
// return both 'count' and 'word' inside a new object or iterate twice?
</code>```