问:
Is it a good idea to install Mercurial on your server and hg pull to deploy?
I've just started at a new job this past month and looks like they have NO source control for their code. They are relying on the backups their hosting provider takes for them.

After talking a bit I convinced my boss that we should definitely be using source control and after I gave a short seminar on it, the entire team is on board; they loved Mercurial.

So right now this is the way we work:

```<code>º----------BitBucket
º---------/
º--------/
</code>```

Myself and the three other developers hg pull from BitBucket, make our changes, then hg push to BitBucket.

Now for deployment, someone would need to FTP the latest files towards the production server.

I was thinking of installing Mercurial on our server, and using hg clone (subsequently hg pull) to keep the versions up to date on production.

```<code>º---push->-----BitBucket----<-pull-----º (production server)
º---push->----/
º---push->---/
</code>```

Is this a good idea? Any potential pitfalls I may not be seeing? Has anybody here done something similar? How do you deploy a large PHP framework application (We're using Moodle)?

答:
Another (in my opinion better) possibility: use a build server / continuous integration server.

Short short explanation: this is a server (can be in-house, doesn't need to be on the internet) that you set up to monitor your repositories, and whenever there are new changesets in the repos, the server builds your code (AFAIK this is not necessary in PHP), runs unit tests and deploys your code to the web server.

For more information, check these links:

Wikipedia article about CI

Stack Overflow question: What is the point of a “Build Server”?

There are a lot of different products for CI out there, but the only one I've used so far is TeamCity. Very easy to set up...in fact, it's the first one I tried, and I liked it so much that I sticked with it.

Alternative cheap solution:

If setting up a build server is too much effort or if you'd like more control about when exactly your site is deployed, just set up a script file (Batch/Powershell on Windows, or something similar on Linux/Mac) that pulls the newest version from your repository and FTPs it on the production server.

Basically, it's the same as a build server, only simpler.

No matter how exactly you solve it in the end...be sure to automate it somehow!

You want to be able to deploy with a single click/by typing a single command, so that EVERYBODY can do it without having to know anything special, and without making mistakes - even in case of a disaster or under stress.


问:
Why doesn't Python need a compiler?
Just wondering (now that I've started with C++ which needs a compiler) why Python doesn't need a compiler?

I just enter the code, save it as an exec, and run it. In C++ I have to make builds and all of that other fun stuff.

答:
what a diversion from the initial question... A point not mentioned is that the source of a python program is what you use and distribute,  from a user perspective it IS the program.  We tend to simplify things into categories that are not well defined.

Compiled programs are usually considered to be stand alone files of machine code. (admittedly often containing links to dynamic link libraries associated with specific operating systems). This said... there are variation of most programing language that could be described as compiled or interpreted.

Python does not need a compiler because it relies on an application (called an interpreter) that compiles and runs the code without storing the machine code being created in a form that you can easily access or distribute.

ContentLicense: CC BY-SA 3.0

Title: Why doesn't Python need a compiler?


问:
Application qos involving priority and bandwidth
Our manager wants us to do applicaiton qos which is quite different from the well-known system qos. We have many services of three types, they have priorites, the manager wants to suspend low priority services requests when there are not enough bandwidth for high priority services. But if the high priority services requests decrease, the bandwidth for low priority services should increase and low priority service requests are allowed again.

There should be an algorithm involving priority and bandwidth. I don't know how to design the algorithm, can anyone assist in getting this right?

All these services are within a same process. We are setting the maximum bandwidth for the three types of services via ports of services via TC (TC is the linux qos tool whose name means traffic control).

答: One solution would be to run the services through a message queuing solution (like RabbitMQ, MQSeries, etc.). That will provide priorities, can be load balanced, and offers guaranteed delivery.</p>


问:
Why do we study Java at university?
Java is often found in academia. What is the reason behind that? </p>

答:
There's a few reasons for that including:

Ubiquity in the job market--if universities want their students to get employed (and recommend more students to the the university) they need to teach relevant languages.

Simplifies the curriculum

Easier to grade and easier to implement your homework in it.

Garbage collected so no need to teach pointers and manual memory management

Do note that there are a number of schools who teach C# for many of the same reasons.  There are many more reasons, some of them more particular to the individual school.  In essence, Java has become the object oriented "BASIC" of yesteryear.

Title: Why do we study Java at university?

ContentLicense: CC BY-SA 2.5


问:
Pattern / methodology for representing large database records as objects
A bit of background information: We have an old database application written in Access that lets users monitor their workload, and the code is... 'procedural' might be too kind. The vast majority of code is hard-wired to form events, there's a lot of duplication, and little to no abstraction. If it needs to fetch data from the database, it'll just do it right there and then, even if that means roughly the same bit of code repeated 6 times for 6 similar buttons (and 6 practically identical database requests). It's not pretty.

I want to rebuild the application in VB.NET, but I'm hitting a bit of a design snag when it comes to writing classes to represent database records as objects - I don't have a huge amount of experience in OO programming (written a few small apps, read lots of books and material, regular SE lurker), so this is my first OO database application.

The problem is that a given 'job' for a user has a lot of fields on the database. About 30 or so - ID, Title, Requestor, Request Date, Target Date, Priority, Type, Approval... and so on. First pass: Whack everything into a dirty great Job class:

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestorName As String
    Private mRequestorEmail As String
    ...

    Public Property ID() As String
        Get
            Return mID
        End Get
        Set(value As String)
            Me.mID = value
        End Set
    End Property
    ...
End Class
</code>```

Yikes. I'm sure you can see my hesitance at having such an enormous class sitting front-and-center of the application. All those properties seem to be violating encapsulation too - the Private members might as well be Public, but conversely I need to be able to alter fields and later write back to the database.

Second pass: There's a few things in here that could be extracted and situated elsewhere: for example, all those Requestor___ members could sit in a Requestor class

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestor As Requestor
    ...
End Class

Public Class Requestor
    Private mName As String
    Private mEmail As String
    ...
End Class
</code>```

So now I have half a dozen of these. Smaller classes? Feels nice. But it feels like all I've really achieved is essentially database normalisation, which doesn't feel like it should live in the application. And the only real change to the structure is that it takes more steps to get to data items.

And I still have all those properties (which are forcing me to use hungarian notation on my private members, which I'm not a fan of, but VB.NET isn't case-sensitive so I can't use the same names), which still aren't sitting right with me.

Is there a standard pattern or methodology for moving large data items to and from a database? My current best idea is the above with commit() and read() methods in the Job class - alterations are made to the objects and then later commited to the database.

答:
The answer to your question is that you probably, most of the time, don't need to.

Actually, you're building up your model in such a way that it trivially maps the existing, relational database design. This is a bad approach per se, moreover if that relational design is flawed and/or denormalized. Persistence is support, not kernel.

Instead, focus on concrete problems your application is supposed to solve, and build a model explicitly designed to fulfill those requirements . This model will reflect your application's conceptual domain, much more than it does your data model.

My experience with large database records is that, most of the time, only a subset of columns is required to perform certain operations.


问:
Why are algorithms and data structures important?
It seems like a lot of university-level computer science programs and programmer job interviews focus heavily on algorithms and data structures. I'm curious as to why universities and employers put so much emphasis on the theoretical aspects of computer science rather than on specific languages and technologies, which in my opinion is far more useful and important.

Doesn't it make more sense to look for programmers with a specific skill-set when hiring for an open job position? For example employers should require knowledge of C++, Java, etc. instead of all that theoretical garbage. Programming is a vocational career, you're supposed to know how to use certain languages and frameworks and the syntax and logic behind them.

Like if you search Google for "learn to code" you will see a bunch of websites that teach you how. They don't teach you about algorithms or data structures, but instead about syntax and the features of each language. So why are A+DS so important?

答:
You can play a musical instrument, say a guitar, to a reasonable standard without studying technique, be self taught, find a few chords on the internet, play a few songs.

If you want to play fast though, or play jazz, or play sufficiently difficult things with relative ease technique becomes important. It becomes important to understand what you're doing, and how you can do it more efficiently and "easily".

where "ease" usually means conservation of motion and effort. The key to doing things fast is to do less more often. These are things that require direction, practice, and understanding.

Algorithms, data structures and problem solving are the techniques of programmers. You can learn to code by just studying syntax and mucking about. But to be a truly great programmer? you must understand the art, the technique. Beautiful code is simple, direct, much like playing an instrument with poise and grace.

Anyone can write code, and anyone can play E on a guitar. But to call yourself a programmer these are the things which you must master.


答:
Many of the applications we use, need to be fast and responsive. Take for example Photoshop, 3D creation app's, video games, Anti-Virus program's etc etc.
Such app's need to be fast, so the client's can be more productive. But writen with simple math wouldn't be very fast even in performing simple mathmeatical tasks by the code.
Mathematics offer great bunch of algorithms, one simple math task can be writen in different ways, some fast, some slower.

Take for example a prime generator, take the primitive calculations where you divide every number below it to see if it leaves any modulo.
Write this down and run the program.
Now write a Miller-Rabin prime test (algorithm) program, and see the difference in the speed.
It will take over an hour to provide two million prime numbers with the first function.
But with the Miller-Rabin algirthm, you can get these two million primes in less than 10 minutes.
Both functions are doing exactly the same thing (allmost), they test for primality of a number, but the second function is finishing the task 10 times faster, becouse of the good algirthm.

Writing graphical code also require mathematics, fast algebra algorithms, so the program can run smooth, and fast, responsive, and so on.

Some of the math algirthms are fast, and writen in your application will result in a better, faster app.
When I use 3D software, I want it to be faster like the light, and not to wait 3~ seconds every time i try to rotate that cube (polygon).

Title: Why are algorithms and data structures important?

Body:
It seems like a lot of university-level computer science programs and programmer job interviews focus heavily on algorithms and data structures. I'm curious as to why universities and employers put so much emphasis on the theoretical aspects of computer science rather than on specific languages and technologies, which in my opinion is far more useful and important.

Doesn't it make more sense to look for programmers with a specific skill-set when hiring for an open job position? For example employers should require knowledge of C++, Java, etc. instead of all that theoretical garbage. Programming is a vocational career, you're supposed to know how to use certain languages and frameworks and the syntax and logic behind them.

Like if you search Google for "learn to code" you will see a bunch of websites that teach you how. They don't teach you about algorithms or data structures, but instead about syntax and the features of each language. So why are A+DS so important?


问:
Loadbalancing and failover in code
I have HTTPS based webservices (not REST, rather old code). I am generating Java client stubs using Axis & using that to call the webservices. There are around 20 different APIs on the webservice.

I have 2 servers hosting the webservices (identical - 2 servers are being used for redundancy) and data is synced between the 2 servers - so that same API called either server produces the same result).

I do not have hardware or software load balancers or clusters.

So I am planning to implement the failover & loadbalancing in code (the failover is important, it's OK even if I don't do load balancing).

I was planning to do this in code
i.e if I get a connect exception, I will trap the exception and do the same Webservice call on the other server.

I was wondering if there are any known design patterns for this or any pitfalls I should be aware of.

答:
When I first read your description i wasn't sure where you planned to handle the exception, but after re-reading I am going to assume you are handling the failover in the client library. There are some JMS libraries that do something like this, so it isn't an unreasonable method. However, I would consider the following:

is each client going to have a preferred server, and only swap if that server goes down?

once a client picks a server that is working, will it ever switch?

if you pick a server that works, do you stick to it?

Basically, depending on how you answer these questions I could see all of the clients getting stuck on one server if the other has  small hiccup. In which case, you basically have fail-over but not load balancing.

If you swap servers randomly every request, then you have a performance problem if one server goes down.

The other big issue i can see is that if you hard code the server list into the client library then it is hard to change. It would be better to load the list from somewhere, or not at all, which is why load balancers are nice, in that they hide that list from the client completely. Assuming you want to keep the entire implementation in the client, i would make sure to make the list configurable from outside the library. As i mentioned, some JMS providers take a comma separated list of URLs for the server. You might try something like that, or take an array of URLs, or even a JSON configuration or similar.

So not totally an answer but some things to think about.

Title: Loadbalancing and failover in code


问:
Why to have an application with GUI on linux when command line is available?
If the question appears to be off topic then please migrate to some other suitable domain on stackexchange.

Q.why to have GUI along with CLI, when you already have command line interface?

I'm currently developing an application. As of now application has a command line interface.

The target machines for application will be 80% servers and 20% workstations. I'm considering to provide GUI too for the application.

GUI Use Case:
Product registration is main use case i.e. my product needs license key to run. And after that only some text info will be shown every time its launched. Only 2-3 buttons to perform extended functions.

CLI Use Case:
Product registration will expect some arguments as command line arguments. Later the 2-3 extended functions available in GUI can also be started from command line.

答:
Some of the reasons you might want a GUI are:

Some, or all, of the users are not comfortable with the command line interface

It may be easier to use a GUI, due to the complexity of the application. Think about Adobe Illustrator, the GUI is much simpler than writing postscript files or similar

There are visualizations, graphs and similar things that are better in a GUI than in ASCII

I suspect that the main thing that would motivate you, based on your description, is the first one. If you have some users that aren't comfortable with the command line interface, then you may want to provide a GUI.

One thing to consider, there are a few applications I have used that basically build their GUI as a front end for the command line version, so there is a lot of shared code.


问:
Architecture strategies for a complex competition scoring system
Competition description:

There are about 10 teams competing against each other over a 6-week period.

Each team's total score (out of a 1000 total available points) is based on the total of its scores in about 25,000 different scoring elements.

Most scoring elements are worth a small fraction of a point and there will about 10 X 25,000 = 250,000 total raw input data points.

The points for some scoring elements are awarded at frequent regular time intervals during the competition. The points for other scoring elements are awarded at either irregular time intervals or at just one moment in time.

There are about 20 different types of scoring elements.

Each of the 20 types of scoring elements has a different set of inputs, a different algorithm for calculating the earned score from the raw inputs, and a different number of total available points. The simplest algorithms require one input and one simple calculation. The most complex algorithms consist of hundreds or thousands of raw inputs and a more complicated calculation.

Some types of raw inputs are automatically generated. Other types of raw inputs are manually entered. All raw inputs are subject to possible manual retroactive adjustments by competition officials.

Primary requirements:

The scoring system UI for competitors and other competition followers will show current and historical total team scores, team standings, team scores by scoring element, raw input data (at several levels of aggregation, e.g. daily, weekly, etc.), and other metrics.

There will be charts, tables, and other widgets for displaying historical raw data inputs and scores.

There will be a quasi-real-time dashboard that will show current scores and raw data inputs.

Aggregate scores should be updated/refreshed whenever new raw data inputs arrive or existing raw data inputs are adjusted.

There will be a "scorekeeper UI" for manually entering new inputs, manually adjusting existing inputs, and manually adjusting calculated scores.

Decisions:

Should the scoring calculations be performed on the database layer (T-SQL/SQL Server, in my case) or on the application layer (C#/ASP.NET MVC, in my case)?

What are some recommended approaches for calculating updated total team scores whenever new raw inputs arrives? Calculating each of the teams' total scores from scratch every time a new input arrives will probably slow the system to a crawl. I've considered some kind of "diff" approach, but that approach may pose problems for ad-hoc queries and some aggegates. I'm trying draw some sports analogies, but it's tough because most games consist of no more than 20 or 30 scoring elements per game (I'm thinking of a high-scoring baseball game; football and soccer have fewer scoring events per game). Perhaps a financial balance sheet analogy makes more sense because financial "bottom line" calcs may be calculated from 250,000 or more transactions.

Should I be making heavy use of caching for this application?

Are there any obvious approaches or similar case studies that I may be overlooking?

答:
My thoughts, based on not knowing your actual algorithms:

Do the scoring in your application code, unless it is very simple

Keep running information that will help you generate scores quickly

For example, if you need an average, you can keep the sum and count and calculate the average as needed. (Note, for simple things like average, you could just use the Database)

Also, take a look at moving averages (http://en.wikipedia.org/wiki/Moving_average) they can allow you to store very little data about the past and still display historically useful information

I wouldn't worry too much about caching data, rather i would think about keeping the running information and being able to calculate the result quickly. However, if you have a lot of viewers for the same values, you might start caching.

If the total number of data points is 250k, you can do a fair bit of math on that in a very small amount of time.

I am not sure what you are planning to do for the web app architecture, but i would probably write the application you describe as a single page web app with as few server API points to get data as JSON. Then I would do the graphic/display all on the browser in JavaScript using something like D3, Raphael or another chart library.


答:
Learning about algorithms allows you to make smarter decisions about what code to write.

Imagine that you want to display a list of names in alphabetical order. How will you sort the list? The answer is an algorithm. Now, you could just use the sort associated with a data structure library you are using, and that might be fine. Now suppose you have 1 million names and you want to display the first 20 after sorting them. What if it was 100 million? Algorithms define how your program works, the more you know the more options you have.

Learning about data structures makes your code more efficient.

Back to that question about names. How do you store 10 names in memory? What about 100 Million? The answer may be different depending on what you want to do with the names. If you want to quickly check if a name is present you could use an array and look through it, or use a hashmap/dictionary and look up the name, or you could use a trie and store a minimal amount of information to find names very quickly. How you do hold the data determines how much data you can have and how fast you can access it.


问:
Should ** bind more tightly than !, ~?
Designing a programming language, I'm including the ** exponentiation operator. In Fortran and Python, the two languages I know of which have this operator, it binds more tightly than unary minus, which makes sense for practicality as well as tradition.

It should bind more loosely than the prefix increment operator ++ because the other way wouldn't make sense. Thus the usual single precedence level for the prefix unary operators gets split in two, which is fine as far as it goes.

I'm also including the logical and bitwise not operators ! and ~. Which side of the split should they fall on? Should they bind more loosely or tightly than **? I haven't been able to find either objective reason or relevant precedent for either choice. Is there any of either that I'm missing? Failing that, which would people find less surprising?

答: I don't have anything to back it up, but my feeling tells me that the logical and bitwise negation operators (! and ~) are most closely related to the unary minus (-) and should have the same precedence level.

Title: Should ** bind more tightly than !, ~?


问:
Hyperlinked, externalized source code documentation
Why do we still embed natural language descriptions of source code (i.e., the reason why a line of code was written) within the source code, rather than as a separate document?

Given the expansive real-estate afforded to modern development environments (high-resolution monitors, dual-monitors, etc.), an IDE could provide semi-lock-step panels wherein source code is visually separated from -- but intrinsically linked to -- its corresponding comments. For example, developers could write source code comments in a hyper-linked markup language (linking to additional software requirements), which would simultaneously prevent documentation from cluttering the source code.

What shortcomings would inhibit such a software development mechanism?

A mock-up to help clarify the question:

When the cursor is at a particular line in the source code (shown with a blue background, above), the documentation that corresponds to the line at the cursor is highlighted (i.e., distinguished from the other details). As noted in the question, the documentation would stay in lock-step with the source code as the cursor jumps through the source code. A hot-key could switch between "documentation mode" and "development mode".

Potential advantages include:

More source code and more documentation on the screen(s) at once

Ability to edit documentation independently of source code (regardless of language?)

Write documentation and source code in parallel without merge conflicts

Real-time hyperlinked documentation with superior text formatting

Quasi-real-time machine translation into different natural languages

Every line of code can be clearly linked to a task, business requirement, etc.

Documentation could automatically timestamp when each line of code was written (metrics)

Dynamic inclusion of architecture diagrams, images to explain relations, etc.

Single-source documentation (e.g., tag code snippets for user manual inclusion).

Note:

The documentation window can be collapsed

Workflow for viewing or comparing source files would not be affected

How the implementation happens is a detail; the documentation could be:

kept at the end of the source file;

split into two files by convention (filename.c, filename.c.doc); or

fully database-driven

By hyperlinked documentation, I mean linking to external sources (such as StackOverflow or Wikipedia) and internal documents (i.e., a wiki on a subdomain that could cross-reference business requirements documentation) and other source files (similar to JavaDocs).

Related thread: What's with the aversion to documentation in the industry?

答:
This problem bothers me all the time, and I just got an idea on the direction we should be going to try and solve it (thats how I found this question).

I think the linked documentation problem was thought wrong when we decided to include the user documentation in the source code. Like docco does.

First of all, lets differentiate code comments from user documentation .

Code comments normally are in its best when they are short, super short in fact, so I can actually read the code that does the stuff without having to see some poetry of why and how it works.

User comments are intended for people trying to use your library/API, and may include examples of use, explanation of why it was implemented like that, or instructions on how to extend the library. This kind of comments tend to be really verbose.

I do agree on the fact that documentation should be written in plain text so is not vendor fixed and its easy to add in a VCS. But I think that keeping the user documentation in the source file was a big mistake for at least two reasons:

Harder to read code

Not flexible enough documentation (suppose I need two documentation pages using the same example code or having one documentation page needing to interleave code from two different source files).

So why do we want to have it in the same file? Well, nobody wants to have their documentations out of sync from the code. But we do it anyways, and specially now a days with the big success of Markdown. Which I think is on the right path, but if falls short, waaay short.

When we interleave code comment with user comment, we have a 2 way binding. That allows us to easily see which comment corresponds to what part of the code. We can also see if some code is undocumented. What it doesn't offer, is a way to see if the comment is updated or not, and that happens a lot when your code is hard to read (because the documentation made it ugly).

What if instead of having a 2 way binding, we have a one way?. Documentation pointing to code. We could have markdown code with special commands like:

```<code>Some documentation right here that explains the following code:
   @include_file <path/to/some/file>:<line_start>-<line_end>
or
   @include_file <path/to/some/file>
     @starts_with "some regexp or literal text to search"
     @ends_with "another regexp"
or
   @include_file <path/to/some/file>
     @class MyClass
     @method foo
or any combination or way of linking you could imagine

We can even have semantic in the directives:
   @explain_code <path/and/same/of/above>
   @example_code <path/and/same/of/above>
   @performance_notice <path/and/same/of/above>

Which would do basically the same, but it adds the intention of why
do we want to add this code in the first place, which could be
used different by an IDE.
</code>```

This has the benefit of being markup with some additions, and with the proper tools, we could add more value to it.

Imagine this one way binding with tools like grunt (even with the watch task). You could detect when a source file change, see what documentation files depended on it and warn the user (or mark it out somewhere) if the code that was commented had change.

Body:
This problem bothers me all the time, and I just got an idea on the direction we should be going to try and solve it (thats how I found this question).

I think the linked documentation problem was thought wrong when we decided to include the user documentation in the source code. Like docco does.

First of all, lets differentiate code comments from user documentation .

Code comments normally are in its best when they are short, super short in fact, so I can actually read the code that does the stuff without having to see some poetry of why and how it works.

User comments are intended for people trying to use your library/API, and may include examples of use, explanation of why it was implemented like that, or instructions on how to extend the library. This kind of comments tend to be really verbose.

I do agree on the fact that documentation should be written in plain text so is not vendor fixed and its easy to add in a VCS. But I think that keeping the user documentation in the source file was a big mistake for at least two reasons:

Harder to read code

Not flexible enough documentation (suppose I need two documentation pages using the same example code or having one documentation page needing to interleave code from two different source files).

So why do we want to have it in the same file? Well, nobody wants to have their documentations out of sync from the code. But we do it anyways, and specially now a days with the big success of Markdown. Which I think is on the right path, but if falls short, waaay short.

When we interleave code comment with user comment, we have a 2 way binding. That allows us to easily see which comment corresponds to what part of the code. We can also see if some code is undocumented. What it doesn't offer, is a way to see if the comment is updated or not, and that happens a lot when your code is hard to read (because the documentation made it ugly).

What if instead of having a 2 way binding, we have a one way?. Documentation pointing to code. We could have markdown code with special commands like:

Some documentation right here that explains the following code:
   @include_file <path/to/some/file>:<line_start>-<line_end>
or
   @include_file <path/to/some/file>
     @starts_with "some regexp or literal text to search"
     @ends_with "another regexp"
or
   @include_file <path/to/some/file>
     @class MyClass
     @method foo
or any combination or way of linking you could imagine

We can even have semantic in the directives:
   @explain_code <path/and/same/of/above>
   @example_code <path/and/same/of/above>
   @performance_notice <path/and/same/of/above>

Which would do basically the same, but it adds the intention of why
do we want to add this code in the first place, which could be
used different by an IDE.

This has the benefit of being markup with some additions, and with the proper tools, we could add more value to it.

Imagine this one way binding with tools like grunt (even with the watch task). You could detect when a source file change, see what documentation files depended on it and warn the user (or mark it out somewhere) if the code that was commented had change.


答:
When designing a language, you can tweak precedence and other rules to create an elegant experience. Sometimes, not allowing certain constructs can improve readability, without sacrificing much expressiveness. You only loose similarity to other languages, thus making your language harder to learn.

You established -x**y == -(x**y). This makes sense, as this is the convention in maths.

You are considering ++x**y == (++x)**y. The alternative does not make sense, because x**y is not an lvalue. However, you may want to consider disallowing increment on an expression level. E.g. Go takes this route. This avoids the problem that x = ++x is undefined behaviour in many languages. Also, x++**y is downright ugly ;-)

If you have a static type system and a boolean type, then specifying precedence between ** and ! does not make sense: One is a numeric operator, the other is logical.

If you have no boolean type, or no static type system, then ! should have lower precedence, so !x**y is !(x**y). Exponentiation should bind very tightly, only increment and method calls should have higher precedence. Also, the interpretation (!x)**y is wonky: Few would expect that, and you should generally follow the principle of least surprise. This would also give ! a higher precedence than unary minus…

I personally am a fan of alphabetic logical operators like not, and, or with very low precedence. This can improve readability.

I am not a fan of bitwise operators like <<, ~, & because bit twiddling is only useful in very few domains and these characters would be valuable for other operators. << could be some stream operator, ~ could be string concatenation. Look into Haskell or Perl6 for cute ideas.

If you want to include bitwise operators, then they should relate in precedence to their logical equivalents: ! and ~ might have same precedence. ^ (xor) and | should have roughly same precedence, and bind slightly more tightly than the logical operators || and &&. & should have higher precedence than |, just like && usually has higher precedence than ||.

To avoid suprises, stay near C, as it is one of the most influential languages. You can find a precedence table on Wikipedia. Compare with Perl, Python. Also remember that some languages in the ML family survive without such elaborate precedence tables.

Title: Should ** bind more tightly than !, ~?

Body:
Designing a programming language, I'm including the ** exponentiation operator. In Fortran and Python, the two languages I know of which have this operator, it binds more tightly than unary minus, which makes sense for practicality as well as tradition.

It should bind more loosely than the prefix increment operator ++ because the other way wouldn't make sense. Thus the usual single precedence level for the prefix unary operators gets split in two, which is fine as far as it goes.

I'm also including the logical and bitwise not operators ! and ~. Which side of the split should they fall on? Should they bind more loosely or tightly than **? I haven't been able to find either objective reason or relevant precedent for either choice. Is there any of either that I'm missing? Failing that, which would people find less surprising?


答:
I am also assuming that you are talking about effectively calling the API from the client and not about the 2 servers you have.
You cannot do a load balancing at the client side, because you would never know the load on each of the server, if you even look at connection time out or turn around time, you are not aware it is because of the load or because of network failures. Best is to alternatively call each servers, if at all you would like to do so.

For failover, the above suggestion holds well, where in you can inject the urls from outside.
Whenever there is a connection failure, you may not need to re-try every time. instead you can also have a ping service, which pings the server every configured time and updates a common location about the status of the server and thus would help you to create and connect to the server which is available. Else you would end up making a wrong connection every time from your actual working code.

Title: Loadbalancing and failover in code

Body:
I have HTTPS based webservices (not REST, rather old code). I am generating Java client stubs using Axis & using that to call the webservices. There are around 20 different APIs on the webservice.

I have 2 servers hosting the webservices (identical - 2 servers are being used for redundancy) and data is synced between the 2 servers - so that same API called either server produces the same result).

I do not have hardware or software load balancers or clusters.

So I am planning to implement the failover & loadbalancing in code (the failover is important, it's OK even if I don't do load balancing).

I was planning to do this in code
i.e if I get a connect exception, I will trap the exception and do the same Webservice call on the other server.

I was wondering if there are any known design patterns for this or any pitfalls I should be aware of.


问:
Drawing a biggest possible circle inside a polygon - JSXGRAPH
I manage to create a circle inside triangle with this code, but circle inside other polygons are not maximum size:

```<code>var p1 = board.create("point", [0.0, 2.0]);
var p2 = board.create("point", [2.0, 1.0]);

//var pol = board.create("regularpolygon", [p1, p2, 3]);
var pol = board.create("regularpolygon", [p1, p2, 4]);
//var pol = board.create("regularpolygon", [p1, p2, 5]);

board.create("incircle", pol.vertices);
</code>```

What is the easiest way to draw a maximum circle inside square and pentagon?

How about smallest circle around the polygon?

答:
This is why geometry class in high school had you spending all that time drawing stuff.

Assuming a regular polygon (all sides same length, all "corners" same angle), it is immediately obvious that the centers of the largest inscribed circle and the smallest circumscribed circle are identical, and are given by the vector arithmetic mean of the polygon vertices.

The largest inscribed circle touches the polygon at the midpoint of each edge.  The radius is thus given by the distance from the center to the midpoint of any one edge of the polygon.

The smallest circumscribed circle touches the polygon at every vertex.  The radius is the distance from the center to any one vertex of the polygon.

ContentLicense: CC BY-SA 4.0


问:
Plugin naming based on GPL v2
I'm programming a plugin for a software under GPL v2. I'm using an unique name for my plugin, but I'm considering to rename it. I would like to take another plugin's name which has been abandoned and isn't currently being developed.

Am I allowed to take up that name without asking for permission from the author beforehand?

答:
This is not so much a copyright/licensing issue as a trademark issue.
The name of a program/library/plugin is not substantive enough to claim copyright on, but it can be protected under the trademark laws.

As long as the author of the abandoned plugin has not registered a trademark on the plugin's name, you can publish a plugin yourself that uses the same name.

Whether you should do that is an entirely different question and is of a more ethical nature. I would not do it unless your plugin can be seen as a replacement/improvement of the original one, or the original one is not only abandoned but also disused and there is no better name for your plugin.

Title: Plugin naming based on GPL v2


答:
The name of the project is not covered by the GPL, the license applies only to the project's code.

Now, without knowing the actual project, it's impossible to tell if you are allowed to use its name or not. For all we know, the name may be trademarked. Nevertheless, if you are set on using the name, the proper thing to do would be to at least try and contact the project's authors before you rename your project. It's just common courtesy.

All that said, my advice would be use a distinct name, especially if the abandoned project is popular(ish). Using the same name will only serve to confuse both projects' users.

Title: Plugin naming based on GPL v2

Body:
I'm programming a plugin for a software under GPL v2. I'm using an unique name for my plugin, but I'm considering to rename it. I would like to take another plugin's name which has been abandoned and isn't currently being developed.

Am I allowed to take up that name without asking for permission from the author beforehand?


问:
Why doesn't Visual Studio auto increment your version number?
This question asked how to auto update version number in VS 2010 :
https://stackoverflow.com/questions/4025704/publishing-in-net-produces-application-files-myapp-someversionnumber-how-to-ge

The answer was,
You have to update both Assembly Version AND File version manually

Shouldn't the version number increment each time I publish?  Why should I do it manually?  Is this is a conscious decision by MS to do it this way? What's the thinking behind having people manually update their own version number?

答: Visual Studio does update your version number automatically.  If you code AssemblyVersion("a.b.*"), every build will get a different number a.b.c.d, and every build number will be greater than all older builds.  It just isn't a monotonically-increasing system like most of us expect.  Instead, the trailing two components, c.d will be computed based on the current date and time.


答:
```<code>// two points for the side of the polygon
var p1 = board.create("point", [0.0, 0.0], point_props);
var p2 = board.create("point", [4.0, 0.0], point_props);

// square polygon has 4 regular sides
var pl = board.create("regularpolygon", [p1, p2, 4]);

// center point of the polygon
var cp = board.create("circumcenter", pl.vertices);

// for incircle get middle point of the side
var mp = board.create("midpoint", [p1, p2]);
board.create("circle", [cp, mp]);

// for outcircle use either p1 or p2
board.create("circle", [cp, p1]);
</code>```

Title: Drawing a biggest possible circle inside a polygon - JSXGRAPH

Body:
I manage to create a circle inside triangle with this code, but circle inside other polygons are not maximum size:

```<code>var p1 = board.create("point", [0.0, 2.0]);
var p2 = board.create("point", [2.0, 1.0]);

//var pol = board.create("regularpolygon", [p1, p2, 3]);
var pol = board.create("regularpolygon", [p1, p2, 4]);
//var pol = board.create("regularpolygon", [p1, p2, 5]);

board.create("incircle", pol.vertices);
</code>```

What is the easiest way to draw a maximum circle inside square and pentagon?

How about smallest circle around the polygon?


问:
Is it ok to learn from C# 2002 materials?
I've found some videos that explain C# but it back to C#.NET when it is first appeared, if I learn from these videos will I learn something that has been removed from the language? will I miss alot? </p>

答: You will miss a good amount of the new features.  I think you'd be better off focusing on newer training materials.  This way you won't have to unlearn all of the stuff from the earlier versions as you learn stuff from the more modern versions.  The .NET of 2002 is very different from the .NET of today.</p>


答:
I've written something very similar to score live sporting events for several different sports, where is what worked for me.

I found the application layer was the best place to perform scoring calculations for two reasons, 1: We were able to express the logic in c# than SQL. 2: We were using NHibernate so it just seemed more natural not to do it in the database and work with our domain model. Where we needed to expose logic to external applications we used a WCF service layer.

The model the actual scoring process of each match we used the idea of a match, consisting of two teams playing against each other, as a timeline with each scoring element and any other match related milestone e.g. half time, foul, being an item on the timeline.

each scoring element, which in the implementation consisted of a command object, would then update the match state, e.g. the score, phase of play, but would also contain the logic/data needed to roll back the state change if necessary. sometimes this consisted of having to save the entire match state every time something new was entered on the time line.

each time line entry or collection of entries was tracked with a Guid that represented a transaction in our system. The match class then had logic that would allow it to roll back the last transaction to any previous point in the match.

Each important entity that we need reports on in our system e.g. player, team, league, season, would have its own report class which would be updated by a trigger which fired every time a time line entry was made, what was updated would depend on the timeline entry but the result was we had these cached report objects that always had the latest information pushed to them.

We found no good solution for dealing with ad-hoc queries

Cache state/timeline entries of any on going matches, also cache your report data and push updates to it rather than update it by polling for changes periodically.

If you have your scoring logic on a server and your scoring client software has to connect to it remotely from a sports venue then message queueing is your friend, you will lose connection at some point and reliable message queuing will ensure that each message, in my case each time line entry, will get through and be in order.

Title: Architecture strategies for a complex competition scoring system

Body:
Competition description:

There are about 10 teams competing against each other over a 6-week period.

Each team's total score (out of a 1000 total available points) is based on the total of its scores in about 25,000 different scoring elements.

Most scoring elements are worth a small fraction of a point and there will about 10 X 25,000 = 250,000 total raw input data points.

The points for some scoring elements are awarded at frequent regular time intervals during the competition. The points for other scoring elements are awarded at either irregular time intervals or at just one moment in time.

There are about 20 different types of scoring elements.

Each of the 20 types of scoring elements has a different set of inputs, a different algorithm for calculating the earned score from the raw inputs, and a different number of total available points. The simplest algorithms require one input and one simple calculation. The most complex algorithms consist of hundreds or thousands of raw inputs and a more complicated calculation.

Some types of raw inputs are automatically generated. Other types of raw inputs are manually entered. All raw inputs are subject to possible manual retroactive adjustments by competition officials.

Primary requirements:

The scoring system UI for competitors and other competition followers will show current and historical total team scores, team standings, team scores by scoring element, raw input data (at several levels of aggregation, e.g. daily, weekly, etc.), and other metrics.

There will be charts, tables, and other widgets for displaying historical raw data inputs and scores.

There will be a quasi-real-time dashboard that will show current scores and raw data inputs.

Aggregate scores should be updated/refreshed whenever new raw data inputs arrive or existing raw data inputs are adjusted.

There will be a "scorekeeper UI" for manually entering new inputs, manually adjusting existing inputs, and manually adjusting calculated scores.

Decisions:

Should the scoring calculations be performed on the database layer (T-SQL/SQL Server, in my case) or on the application layer (C#/ASP.NET MVC, in my case)?

What are some recommended approaches for calculating updated total team scores whenever new raw inputs arrives? Calculating each of the teams' total scores from scratch every time a new input arrives will probably slow the system to a crawl. I've considered some kind of "diff" approach, but that approach may pose problems for ad-hoc queries and some aggegates. I'm trying draw some sports analogies, but it's tough because most games consist of no more than 20 or 30 scoring elements per game (I'm thinking of a high-scoring baseball game; football and soccer have fewer scoring events per game). Perhaps a financial balance sheet analogy makes more sense because financial "bottom line" calcs may be calculated from 250,000 or more transactions.

Should I be making heavy use of caching for this application?

Are there any obvious approaches or similar case studies that I may be overlooking?


答:
Whatever you find, it should start at C#/.NET 2.0.

Much of .NET 1.0 was refined in 2.0 with generics, and the 2.0 framework is still widely used today; the 3.0 and 3.5 frameworks are enhancements to 2.0, not rewrites.

If you're looking for a beginner book, Head First C# is pretty good.

Title: Is it ok to learn from C# 2002 materials?

Body: I've found some videos that explain C# but it back to C#.NET when it is first appeared, if I learn from these videos will I learn something that has been removed from the language? will I miss alot? </p>


答:
Information organization. UI applications has a richer toolkit to present the data - e.g. checkbox is much faster to parse at a glance then to distinguish "true" from "false", charts give instant insight into dataset, different fonts help to drive user attention, etc.

Performance. Console application IO is inherently slow. The console application you see is actually two applications (UI application called terminal emulator and actual application running in the background) that communicate over 3 pipes (e.g. character-by-character copy). Terminal emulator knows nothing about actual application and can't make any assumptions - it only parses the streams and reacts on control codes. UI applications are fused into one - instead of inefficient "emit string with control codes > switch context to different application > parse the string > update presentation" they only need to update the presentation (which they do just the same way terminal emulator does - but instead they may be optimized, e.g. cache some regions beforehand to avoid re-rendering).

User-friendliness. Non-IT people are much more used to UI.

Title: Why to have an application with GUI on linux when command line is available?

Body:
If the question appears to be off topic then please migrate to some other suitable domain on stackexchange.

Q.why to have GUI along with CLI, when you already have command line interface?

I'm currently developing an application. As of now application has a command line interface.

The target machines for application will be 80% servers and 20% workstations. I'm considering to provide GUI too for the application.

GUI Use Case:
Product registration is main use case i.e. my product needs license key to run. And after that only some text info will be shown every time its launched. Only 2-3 buttons to perform extended functions.

CLI Use Case:
Product registration will expect some arguments as command line arguments. Later the 2-3 extended functions available in GUI can also be started from command line.


答:
I would highly suggest leaving the calculations to the database layer. The database is much better suited to handling the calculations and manipulating large datasets, as well as storing them in a way that is most efficient to retrieve. Not to mention, if you do this at the application layer you will need a way to handle contention and failures, should two users initiate the calculations at once or should a failure occur.

I would recommend storing the raw data in tables and create a view layer to aggregate the data. I am more familiar with Oracle materialized views, but SQL Server offers a similar construct called Indexed Views. These views act like tables, and are perfect for aggregate functions like the calculations you're talking about. And, these Indexed Views can be updated automatically when data is changed on the underlying tables.


问:
Casual projects on Github omit error checking, logging, etc., for the sake of clarity?
I just started using GitHub to socialize some projects for simple chat and peer-to-peer apps. With respect to coding, is it customary to omit exception handling, error checking, logging, etc., to promote easy-to-understand and 'clean'-looking code, if those additions are not completely necessary to actually run the code?

For instance, here's two extreme examples:

   if( msg != null){
      NodeEvent event = NodeEvent.valueOf(msg.getAction());
      switch (event) {
        case NODE_CONNECTING:
          if( nodeName.isInvalid())
             Utils.log("Invalid node name, ignoring...");
          else{
             String existingNodeAddress = _nodeNameAddressMap.get(nodeName);
             if( existingNodeAddress != null)
                Utils.log("Node address for '" + nodeName + "' updated");
             else
                Utils.log("New node '" + nodeName + "' connected");

             _nodeNameAddressMap.put(nodeName, nodeAddress);
          }
    }
```

<p>Here's the same snippet minus the fluff, although this version can easily crash if fed bad data, but otherwise it will compile and run fine:</p>

<pre class="lang-java prettyprint-override"><code>   NodeEvent event = NodeEvent.valueOf(msg.getAction());
   switch (event) {
     case NODE_CONNECTING:
        _nodeNameAddressMap.put(nodeName, nodeAddress);
</code>```

The clean version is easier to read, obviously, but is brittle. The verbose version is safer, it just looks cluttered.

I'm just curious to know if it's more effective for a social projects to go for the cleaner look at the expense of fragility, allowing those who fork the project to fill in the blanks. A quick survey of github projects and it's clear most go for the clean look.

答:
If this is code intended to run in live environments (actually used in real programs), include all the necessary error checking and logging.  If its meant for teaching purposes only, you can safely leave it out for clarity sake.  But make sure you mark it as such.  You may even want to include such teach code only inside documentation, so there's no confusion.

Also keep in mind, if you are using this code as a showcase for potential employers, if they run it and it has tons of unhandled exceptions, how is that going to make you look?


问:
Is Free Pascal just an open source, multi-platform clone of Turbo Pascal & Delphi?
Does Free Pascal introduce any significant language features over Turbo Pascal & then Delphi, or does it just introduce the Turbo Pascal & Delphi flavors of Pascal to more platforms?</p>

答:
Overloading was standard at least from Turbo Pascal 4.  Free Pascal has evolved in a more mature way than the bloated later Borland/Embarcadero versions although it certainly took on the enhanced features that Turbo Pascal had (The free Pascal "Delphi style" IDE and visual Library is called Lazarus).  Delphi 4 was, if I remember correctly, the last commercial version that came with a proprietary, blisteringly fast help system that was based on a database of pascal/Delphi examples illustrating every aspect of the Delphi 4 language.  Even today this would be an ideal development environment to use for teaching and can be used to create very fast light compiled apps.
Free Pascal has many modern features and has evolved to support many new technologies.</p>


问:
Should I store test files in source control?
I have a number of (large) test files that need to be maintained. This means access to their history is a requirement.

Benefits

Any new developers get the entire test suite with just a git pull.

The history of the files is backed up.

The files themselves are backed up.

Drawbacks

Huge increase in size of repository.

Huge increase in download size of new developers copying the repository.

What are the best practices for maintaining test files?

Do I store these files in source control? Are there any alternatives?

答:
Store them in source control. The benefits you listed are all very good ones. When you say that doing this will result in a "huge" size, just how huge are you talking? 100's of gigabytes? Terabytes?

If storage is really that much of a problem, could you zip the files, store the zip file in source control and then have a script that unzips them when the test cases are run? You'd lose detailed history of each file that way (unless you can find a tool that will unzip and show history in memory), but new developers would still have easy access to test files.

Depending on the nature of your test data, you could have a script to generate test files. This might work if you are testing very large images that can be generated procedurally (SQL inserts to populate a database can also be easily generated by a program or script), but this technique does not apply to all kinds of test data...


答:
I'd store them in source control. Is there ever a case where you want the test suite without the code? Doesn't make sense. Is there ever a case where you want to edit the code without updating the test suite? There shouldn't be.

Drawback 1 shouldn't be a problem given the storage prices these days, and modern SCM systems should make the network activity not a concern outside of initial setup either.

Your drawback 2 doesn't seem like it should be much. How frequently do you have new developers coming on board this project that initial clone time becomes an issue?

Title: Should I store test files in source control?

Body:
I have a number of (large) test files that need to be maintained. This means access to their history is a requirement.

Benefits

Any new developers get the entire test suite with just a git pull.

The history of the files is backed up.

The files themselves are backed up.

Drawbacks

Huge increase in size of repository.

Huge increase in download size of new developers copying the repository.

What are the best practices for maintaining test files?

Do I store these files in source control? Are there any alternatives?


问:
Is it poor practice to name a property/member the same as the declaring type in C#?
For instance, a class like:

```<code>class Dog { } //never mind that there's nothing in it...
</code>```

and then a property like:

```<code>Dog Dog { get; set; }
</code>```

I've been told that if I can't come up with a more imaginative name for it, then I must use:

```<code>Dog DogObject { get; set; }
</code>```

Any thoughts on how to name these better?

答:
It could be a bad practice, were it not for the fact that it's already pretty obvious what you're talking about in your code, based on context.

```<code>Dog = new Dog();
</code>```

Which is the type constructor?  Which is the object?  Not confused?  OK, how about

```<code>Dog = Dog.Create();
</code>```

Which is the object?  Which is the static factory method on the type?  Still not confused?  I didn't think so.

The only time I've seen this be a potential problem is when the namespace tree gets fairly elaborate, and the compiler can't figure out the ambiguity, in which case you wind up with something like

```<code>Dog = new Some.Namespace.Dog();
</code>```

In any case, this should only happen with Automatic Properties (and perhaps enums), since local variable names are always camelCased, avoiding the ambiguity entirely.

```<code>dog = new Dog();
</code>```

Body:
It could be a bad practice, were it not for the fact that it's already pretty obvious what you're talking about in your code, based on context.

Dog = new Dog();

Which is the type constructor?  Which is the object?  Not confused?  OK, how about

Dog = Dog.Create();

Which is the object?  Which is the static factory method on the type?  Still not confused?  I didn't think so.

The only time I've seen this be a potential problem is when the namespace tree gets fairly elaborate, and the compiler can't figure out the ambiguity, in which case you wind up with something like

Dog = new Some.Namespace.Dog();

In any case, this should only happen with Automatic Properties (and perhaps enums), since local variable names are always camelCased, avoiding the ambiguity entirely.

dog = new Dog();


问:
When should you trim input?
I am intern learning tons about the industry outside of academia.

One thing I thought about today was trimming input.

On one side of the coin I don't want the user/implementer to constantly receive unexpected results because their input had too many spaces, thus I need to constantly trim user input after every function call.

But at the same time If I am creating a API library  for internal use here at the office trailing/leading whitespace may be crucial to the results.

Then there are instances were I am not sure if whitespace will be important or not.

The big issue for me is that I find myself CONSTANTLY calling .trim() everywhere in my code.

Does anyone have any tips/ rules of thumb or just thoughts on how to handle certain situations?

答: One useful principle here is YAGNI: "You Ain't Gonna Need It."  What it means is that, when you have an idea for a feature that you're not sure you'll actually need, don't implement it until you are sure you need it.  Then, when the need for it becomes apparent, the places in your codebase where it is actually necessary should also be apparent.

Title: When should you trim input?


问:
Domain Logic in Service Layer exposed as WCF service
I am designing an enterprise solution which consists of modularized products within a product range using Entity Framework code first to define the domain model and provide the data access.

e.g. Solutions:

```<code>ProductRange.Authentication
ProductRange.Gateway
ProductRange.OrderSystem
ProductRange.MarketingSystem
</code>```

Each of these products (solutions) will have similar layers, currently:

Projects in each solution:

```<code>ProductRange.OrderSystem.Model (contains code first POCOs)
ProductRange.OrderSystem.DataContext (contains the dbContext)
ProductRange.OrderSystem.DataAccess (contains the Generic Repository)
ProductRange.OrderSystem.Service.DomainLogic (contains business logic)
ProductRange.OrderSystem.Service.ApplicationLogic (contains application logic)
ProductRange.OrderSystem.Presentation.AdminWebsite
ProductRange.OrderSystem.Presentation.CustomerWebsite
</code>```

Some of the products will need to access the domain logic of another product, especially they will all need to access the ProductRange.Authentication but also ProductRange.MarketingSystem will need to query ProductRange.OrderSystem

I am thinking to expose the domain logic between products in the range via a WCF service. But I will also need to reference the product locally (e.g. creating project references).

How should I go about implementing this? Should I create a WCF service e.g. ProductRange.OrderSystem.WCF which calls the domain logic and exposes it or should my domain logic itsself be a WCF service? If the latter, would I always have to reference my domain logic via the WCF, even from the local ApplicationLogic?

I guess I am looking for some guidance about what layers to have and how best to provide inter connectivity between the solutions.

答:
Here is my two cents worth, I tried to find support for my "WCF is just an interface" on google but have had no luck. I will try again this evening if I get the chance.

The way I was taught and have always approached this is that WCF is just another interface (using the term interface in the way that "GUI" uses it not as the .Net keyword), specifically a way to access code over a network (or internet etc.) I always have a separate class library(s) that the WCF service delegates to for all functionality not related to WCF.

That class library is designed to be usable from any .Net code on the same machine.

The WCF service will do the work to make the library consumable by a variety of languages over the wire. It may translate .Net types to more generic types, lists to arrays for example, or it may add compression for performance reasons.

So if you are consuming the library from .Net code on the same machine I would go directly against the class library. You may want to install this in the GAC for version control.

Of course if the service is stateful then you may want to code against it for simplicity's sake.

Edit.
I thought of another reason you might want to bypass WCF locally. For performance reasons a WCF Client should never be "chatty" it is better to make fewer calls that pull in more data, running against a DLL this limitation is not important. So your class library could expose methods that you would not want to expose over WCF.


问:
Refactoring jQuery spaghetti code to use DDD
Most of my client side code ends up as a long script in one file the mostly looks like this:

```<code><script>
function someFunction1(){/*...*/}
function someFunction2(){/*...*/}
...
var globalVariable1;
var globalVariable2;
...
$(function(){

$('selector1').click(function(){
    //get relevant data from various DOM elements

    //some business logic rules and validation

    //open dialog box

    //more business logic rules and more validation

    //post an ajax request

    //update the DOM
});

//many other events

//many jQuery dialogs
});
</script>
</code>```

It's a maintenance nightmare. Although I use a well designed server-side structure using DDD (application services, domain sevices, value objects,...etc.) I have had little luck structuring my client code to a better separation of concerns.

I'm not building a client-side application. I just use jQuery intensively for the client side.

How should I approach the code structure to apply DDD client-side wide?

答:
You can roll your own MVC if your site is fairly basic. Take a look at PureMVC and try to emulate that model. Get a pub/sub system such as radio then build this:
A facade that registers all mediators, controllers and models. Given you know what the last two are, the mediator is basically the view/view component - but it abstracts it so you don't have to worry about the underlying html.
Mediators receive and send messages. Oftentimes they can receive msgs from the model raw, so long as the data chunk isn't too huge. Other times you will need a controller to manage things.
Controllers are stateless and spring into action on a given message. They manage the exchange between the model and the view.
If you do everything right, the controllers are the most disposable as far as reuse. The other two are as dumb as possible.</p>


问:
Why is the yield keyword used in conjunction with return and break, and not by itself?
In C# you can construct methods with the return type of IEnumerable<T> and use yield return and yield break to control the flow. Here is a simple example that uses both controls:

```<code>public IEnumerable<int> GetEvens(int start, int end) {
    if(end < start)
        yield break;

    if(start & 2 != 0)
        start++;

    for(int i = start; i <= end; i+=2) {
        yield return i;
    }
}
</code>```

My question is, why was it originally designed to use two keywords with yield and not use it like the following with the single yield "yielding the return value":

```<code>public IEnumerable<int> GetEvens(int start, int end) {
    if(end < start)
        return; // stop completely and return nothing

    if(start & 2 != 0)
        start++;

    for(int i = start; i <= end; i+=2) {
        yield i; // yield the current value.
    }
}
</code>```

To me, this is simpler to read and understand.

答:
The slightly awkward yield return syntax was created so that existing code that used the word "yield" as an identifier (variable name) would not break.  (It makes perfect sense, for example, to have a variable named yield if you're working with financial code.)  Since "yield return" would have been a syntax error back then, the new syntax would not break any existing code.

As for yield break, no idea.  That really doesn't seem to have any good reason behind it that I can find.


答:
What you have to ask is, what model is my code going to execute in? If it is going to execute wholly within a single machine, there's no point in a WCF service. If it is going to execute in a networked model, placing logic in a WCF service for the clients to call makes sense IF the client(s) will not have access to a resource (e.g. database)

Practically speaking, your domain logic classes should be exposed as interfaces to the consuming clients, so that if you decide to change your implementation from single machine to WCF or REST your consumer classes won't know the difference. -PatFromCanada alluded to this

Your 'layers' should be triaged along the same principle, only create separate projects for separate files to be deployed. Separate 'layers' by namespaces

Title: Domain Logic in Service Layer exposed as WCF service

Body:
I am designing an enterprise solution which consists of modularized products within a product range using Entity Framework code first to define the domain model and provide the data access.

e.g. Solutions:

```<code>ProductRange.Authentication
ProductRange.Gateway
ProductRange.OrderSystem
ProductRange.MarketingSystem
</code>```

Each of these products (solutions) will have similar layers, currently:

Projects in each solution:

```<code>ProductRange.OrderSystem.Model (contains code first POCOs)
ProductRange.OrderSystem.DataContext (contains the dbContext)
ProductRange.OrderSystem.DataAccess (contains the Generic Repository)
ProductRange.OrderSystem.Service.DomainLogic (contains business logic)
ProductRange.OrderSystem.Service.ApplicationLogic (contains application logic)
ProductRange.OrderSystem.Presentation.AdminWebsite
ProductRange.OrderSystem.Presentation.CustomerWebsite
</code>```

Some of the products will need to access the domain logic of another product, especially they will all need to access the ProductRange.Authentication but also ProductRange.MarketingSystem will need to query ProductRange.OrderSystem

I am thinking to expose the domain logic between products in the range via a WCF service. But I will also need to reference the product locally (e.g. creating project references).

How should I go about implementing this? Should I create a WCF service e.g. ProductRange.OrderSystem.WCF which calls the domain logic and exposes it or should my domain logic itsself be a WCF service? If the latter, would I always have to reference my domain logic via the WCF, even from the local ApplicationLogic?

I guess I am looking for some guidance about what layers to have and how best to provide inter connectivity between the solutions.


答:
You will miss a ton of features. As jkohlhepp said, the .Net of today is much different than that of when it was first released. You can check out Windows Development For Beginners and Web Development For Beginners on Microsoft's site. This is targeted towards beginners (obviously) but there are links to othe resources as well.

Take advantage of Microsoft's MSDN as I think it has great documentation and has helped me along greatly! That is one of the things I love about the .Net languages and that I have found lacking in other langauges (Python has a decent documentation, but it is nowhere the caliber of the MSDN).


答:
It depends what the input is going to be used for. If you are trimming white-space from data that's been entered as a search term then I can understand why you are doing it. It's a good habit to learn not to trust data coming into a system, I'm thinking primarily of SQL Injection but there are other aspects as well.

You might not need to always trim input but you definitely should always check input.

Title: When should you trim input?

Body:
I am intern learning tons about the industry outside of academia.

One thing I thought about today was trimming input.

On one side of the coin I don't want the user/implementer to constantly receive unexpected results because their input had too many spaces, thus I need to constantly trim user input after every function call.

But at the same time If I am creating a API library  for internal use here at the office trailing/leading whitespace may be crucial to the results.

Then there are instances were I am not sure if whitespace will be important or not.

The big issue for me is that I find myself CONSTANTLY calling .trim() everywhere in my code.

Does anyone have any tips/ rules of thumb or just thoughts on how to handle certain situations?


问:
How to solve binary labeling with graph cut?
Many literature references suggest that the binary labeling problem can be converted into a graph cut problem and solved with the max flow/min cut algorithm. I'm trying to understand the formulation given in Xiaowei Zhou's presentation of the reduction.

The binary labeling problem consists of partitioning n items (here segments of the overlapped regions of two images) into two disjoint sets in a way which minimises an energy function. We can denote the partition as a vector (x_1, ..., x_n) whose elements are 0 or 1; we also have per-item fitness functions D_i; and we define a per-item-pair transition function V_{i,j} which penalises discontinuities. Then the energy function is given by

```<code>E(x_1, ..., x_n) = SUM_p D_p(x_p) + SUM_{p,q} V_{p,q}(x_p, x_q)
</code>```

In my particular case I have 32 segments, so there are 2^32 possible vectors to evaluate. I could evaluate E for each combination, performing 2^32 evaluations, and so get the minimum energy and the combination which achieves it. This is what my intuition suggests. But this is impractical, because the complexity is exponential.

Therefore I want to use the graph cut approach, but I don't understand how to formulate the graph. The 32 segments are the nodes of the graph, but what would be the weight of the edges? And what would be the capacity?

答:
I'm going to attempt this from first principles based on my understanding from the papers I've read. Warning: I've left in a false start.

Initialisation step 1

To your 32 segments nodes we add a source node S and a sink node T. Then we aim to construct things such that a cut which partitions the nodes into disjoint sets, one containing S and the other containing T, has a capacity equal to the energy of the corresponding partition.

So we start by adding edges from S to each segment p with capacity D_p(1) (these edges are cut if the segments are in T's half) and from each segment p to T with capacity D_p(0) (these edges are cut if the segments are in S's half).

Initialisation step 2

We then run a loop through the non-trivial V_{p,q} updating the subgraph generated by  S, p, q, and T. We add an edge p->q and an edge q->p, and we also update the capacities of S->p, S->q, p->T, q->T. Our aim is to make these updates in such a way that any cut has an overall capacity increase of V_{p,q}(x_p, x_q) for the corresponding values of x_p, x_q. Let's draw up a table of the edges cut by each of the four cases:

```<code>x_p  x_q  Edges cut
 0    0   p->T, q->T
 0    1   p->T, S->q, p->q, (q->p)
 1    0   S->p, q->T, (p->q), q->p
 1    1   S->p, S->q
</code>```

(The edges in brackets are back-edges and hence don't affect the capacity of the cut).

The values of the deltas

So if the capacity changes of our update are c_{vertex,vertex} we derive the simultaneous equations

```<code>       c_pT        + c_qT               = V_{p,q}(0,0)
       c_pT + c_Sq        + c_pq        = V_{p,q}(0,1)
c_Sp               + c_qT        + c_qp = V_{p,q}(1,0)
c_Sp        + c_Sq                      = V_{p,q}(1,1)
</code>```

That's underdetermined. The easy approach looks to be to set c_pq = c_qp = 0 and effectively ditch the edges between neighbours. However, that is of course singular. The next easy approach is to set c_Sp = c_pT = 0. Then we get:

```<code>c_Sq = V_{p,q}(1,1)
c_qT = V_{p,q}(0,0)
c_pq = V_{p,q}(0,1) - V_{p,q}(1,1)
c_qp = V_{p,q}(1,0) - V_{p,q}(0,0)
</code>```

Optimisation

Are we done?

The aim was to get the cut equal to the energy. We want to minimise the energy, which means finding a min cut, and we're definitely ok provided that all of the capacity changes above are non-negative. For any reasonable transition penalisation function we can expect a transition to be penalised more than a non-transition, so that's fine.

However, there is a small optimisation which the standard approach takes. If we ensure that every cut adds the same constant value K to the energy, then it doesn't change which input gives the minimum solution. So we can add K to our simultaneous equations and get

```<code>       c_pT        + c_qT               = K + V_{p,q}(0,0)
       c_pT + c_Sq        + c_pq        = K + V_{p,q}(0,1)
c_Sp               + c_qT        + c_qp = K + V_{p,q}(1,0)
c_Sp        + c_Sq                      = K + V_{p,q}(1,1)
</code>```

Now, the standard approach to a determined system is to set c_Sq = c_qp = c_pT = 0, reducing to

```<code>       c_qT        - K' = V_{p,q}(0,0)
            + c_pq - K' = V_{p,q}(0,1)
c_Sp + c_qT        - K' = V_{p,q}(1,0)
c_Sp               - K' = V_{p,q}(1,1)
</code>```

with solution

```<code>K'   = V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)
c_Sp = V_{p,q}(1,0) - V_{p,q}(0,0)
c_qT = V_{p,q}(1,0) - V_{p,q}(1,1)
c_pq = V_{p,q}(0,1) + V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)
</code>```

This only requires one additional edge between p and q, which will give a small optimisation in the setup and in the graph flow computation. Of course, it induces slightly different inequality constraints on the values which V_{p,q} can take.

Putting it all together

For each p, we add edges

```<code>S->p with weight D_p(1) + SUM_q (V_{p,q}(1,0) - V_{p,q}(0,0))
p->T with weight D_p(0) + SUM_q (V_{q,p}(1,0) - V_{q,p}(1,1))
</code>```

For each p,q we add edge

```<code>p->q with weight V_{p,q}(0,1) + V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)
</code>```

Body:
I'm going to attempt this from first principles based on my understanding from the papers I've read. Warning: I've left in a false start.

Initialisation step 1

To your 32 segments nodes we add a source node S and a sink node T. Then we aim to construct things such that a cut which partitions the nodes into disjoint sets, one containing S and the other containing T, has a capacity equal to the energy of the corresponding partition.

So we start by adding edges from S to each segment p with capacity D_p(1) (these edges are cut if the segments are in T's half) and from each segment p to T with capacity D_p(0) (these edges are cut if the segments are in S's half).

Initialisation step 2

We then run a loop through the non-trivial V_{p,q} updating the subgraph generated by  S, p, q, and T. We add an edge p->q and an edge q->p, and we also update the capacities of S->p, S->q, p->T, q->T. Our aim is to make these updates in such a way that any cut has an overall capacity increase of V_{p,q}(x_p, x_q) for the corresponding values of x_p, x_q. Let's draw up a table of the edges cut by each of the four cases:

x_p  x_q  Edges cut
 0    0   p->T, q->T
 0    1   p->T, S->q, p->q, (q->p)
 1    0   S->p, q->T, (p->q), q->p
 1    1   S->p, S->q

(The edges in brackets are back-edges and hence don't affect the capacity of the cut).

The values of the deltas

So if the capacity changes of our update are c_{vertex,vertex} we derive the simultaneous equations

       c_pT        + c_qT               = V_{p,q}(0,0)
       c_pT + c_Sq        + c_pq        = V_{p,q}(0,1)
c_Sp               + c_qT        + c_qp = V_{p,q}(1,0)
c_Sp        + c_Sq                      = V_{p,q}(1,1)

That's underdetermined. The easy approach looks to be to set c_pq = c_qp = 0 and effectively ditch the edges between neighbours. However, that is of course singular. The next easy approach is to set c_Sp = c_pT = 0. Then we get:

c_Sq = V_{p,q}(1,1)
c_qT = V_{p,q}(0,0)
c_pq = V_{p,q}(0,1) - V_{p,q}(1,1)
c_qp = V_{p,q}(1,0) - V_{p,q}(0,0)

Optimisation

Are we done?

The aim was to get the cut equal to the energy. We want to minimise the energy, which means finding a min cut, and we're definitely ok provided that all of the capacity changes above are non-negative. For any reasonable transition penalisation function we can expect a transition to be penalised more than a non-transition, so that's fine.

However, there is a small optimisation which the standard approach takes. If we ensure that every cut adds the same constant value K to the energy, then it doesn't change which input gives the minimum solution. So we can add K to our simultaneous equations and get

       c_pT        + c_qT               = K + V_{p,q}(0,0)
       c_pT + c_Sq        + c_pq        = K + V_{p,q}(0,1)
c_Sp               + c_qT        + c_qp = K + V_{p,q}(1,0)
c_Sp        + c_Sq                      = K + V_{p,q}(1,1)

Now, the standard approach to a determined system is to set c_Sq = c_qp = c_pT = 0, reducing to

       c_qT        - K' = V_{p,q}(0,0)
            + c_pq - K' = V_{p,q}(0,1)
c_Sp + c_qT        - K' = V_{p,q}(1,0)
c_Sp               - K' = V_{p,q}(1,1)

with solution

K'   = V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)
c_Sp = V_{p,q}(1,0) - V_{p,q}(0,0)
c_qT = V_{p,q}(1,0) - V_{p,q}(1,1)
c_pq = V_{p,q}(0,1) + V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)

This only requires one additional edge between p and q, which will give a small optimisation in the setup and in the graph flow computation. Of course, it induces slightly different inequality constraints on the values which V_{p,q} can take.

Putting it all together

For each p, we add edges

S->p with weight D_p(1) + SUM_q (V_{p,q}(1,0) - V_{p,q}(0,0))
p->T with weight D_p(0) + SUM_q (V_{q,p}(1,0) - V_{q,p}(1,1))

For each p,q we add edge

p->q with weight V_{p,q}(0,1) + V_{p,q}(1,0) - V_{p,q}(0,0) - V_{p,q}(1,1)


问:
Why don't RDBMSes return joined tables in a nested format?
For example, say I want to fetch a User and all of his phone numbers and email addresses. The phone numbers and emails are stored in separate tables, One user to many phones/emails. I can do this quite easily:

```<code>SELECT * FROM users user
    LEFT JOIN emails email ON email.user_id=user.id
    LEFT JOIN phones phone ON phone.user_id=user.id
</code>```

The problem* with this is that it's returning the user's name, DOB, favorite color, and all the other information stored in the user table over-and-over again for each record (users×emails×phones records), presumably eating up bandwidth and slowing down the results.

Wouldn't it be nicer if it returned a  single row for each user, and within that record there was a list of emails and a list of phones? It would make the data much easier to work with too.

I know you can get results like this using LINQ or perhaps other frameworks, but it seems to be a weakness in the underlying design of relational databases.

We could get around this by using NoSQL, but shouldn't there be some middle ground?

Am I missing something? Why doesn't this exist?

* Yes, it's designed this way. I get it. I'm wondering why there isn't an alternative that is easier to work with. SQL could keep doing what it's doing but then they could add a keyword or two to do a little bit of post-processing that returns the data in a nested format instead of a cartesian product.

I know this can be done in a scripting language of your choice, but it requires that the SQL server either sends redundant data (example below) or that you to issue multiple queries like SELECT email FROM emails WHERE user_id IN (/* result of first query */).

Instead of having MySQL return something akin to this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "johnsmith45@gmail.com",
    },
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "email": "john@smithsunite.com",
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "email": "originaljane@deerclan.com",
    }
]
</code>```

And then having to group on some unique identifier (which means I need to fetch that too!) client-side to reformat the result set how you want it, just return this:

```<code>[
    {
        "name": "John Smith",
        "dob": "1945-05-13",
        "fav_color": "red",
        "emails": ["johnsmith45@gmail.com", "john@smithsunite.com"]
    },
    {
        "name": "Jane Doe",
        "dob": "1953-02-19",
        "fav_color": "green",
        "emails": ["originaljane@deerclan.com"],
    }
]
</code>```

Alternatively, I can issue 3 queries: 1 for the users, 1 for the emails, and 1 for the phone numbers, but then the email and phone number result sets need to contain the user_id so that I can match them back up with the users I previously fetched. Again, redundant data and needless post-processing.

答:
Deep down, in the guts of a relational database, its all rows and columns.  That is the structure that a relational database is optimized to work with.  Cursors work on individual rows at a time.  Some operations create temporary tables (again, it needs to be rows and columns).

By working with only rows and returning only rows, the system is able to better deal with memory and network traffic.

As mentioned, this allows for certain optimizations to be done (indexes, joins, unions, etc...)

If one was to want a nested tree structure, this requires that one pulls all the data at once.  Gone are the optimizations for the cursors on the database side.  Likewise, the traffic over the network becomes one big burst that can take much longer than the slow trickle of row by row (this is something that is occasionally lost in today's web world).

Every language has arrays within it.  These are easy things to work with and interface with.  By using a very primitive structure, the driver between the database and program - no matter what language - can work in a common way.  Once one starts adding trees, the structures in the language become more complex and more difficult to traverse.

It isn't that hard for a programing language to convert the rows returned into some other structure.  Make it into a tree or a hash set or leave it as a list of rows that you can iterate over.

There is also history at work here.  Transferring structured data was something ugly in the days of old.  Look at the EDI format to get an idea of what you might be asking for.  Trees also imply recursion - which some languages didn't support (the two most important languages of the old days didn't support recursion - recursion didn't enter Fortran until F90 and of the era COBOL didn't either).

And while the languages of today have support for recursion and more advanced data types, there isn't really a good reason to change things.  They work, and they work well.  The ones that are changing things are the nosql databases.  You can store trees in documents in a document based one.  LDAP (its actually oldish) is also a tree based system (though its probably not what you're after).   Who knows, maybe the next thing in nosql databases will be one that returns back the query as a json object.

However, the 'old' relational databases... they're working with rows because thats what they're good at and everything can talk to them without trouble or translation.

In protocol design, perfection has been reached not when there is nothing left to add, but when there is nothing left to take away.

From RFC 1925 - The Twelve Networking Truths


答:
I'm not building a client-side application. I just use jQuery intensively for the client side.

If your goal is gradual refactoring rather than a rewrite, I'd check out RequireJS, which (unlike all the other answers) is not an MVC framework.

Instead, it's just a way to break your code down into modules and to handle the dependencies between them. The mechanism for this is called "Asynchronous Module Definition", or AMD, which somewhat resembles the way classes in PHP or Java are typically organized.

Here's a ridiculously simple example:

myapp/quoteList.js

```<code>// Define a module with no dependencies that is an array
define([],function(){
    return(["Hello","World"]);
});
</code>```

myapp/generateQuote.js

```<code>// Define a module with one dependency on another module and is a function
define(["./quoteList"],function(quoteList){
    var f = function(){
        var num = Math.floor(Math.random() * quotes.length);
        return quotes[num];
    };
    return f;
});
</code>```

myapp/MyUtils.js

```<code>// Define a module which is an object. (Effectively a singleton)
define(["./generateQuote"],function(quotes){
    var o = {
        "getQuote" : generateQuote,
        "doPopup" : function(msg){alert(msg);}
    };
    return o;
});
</code>```

page.html

```<code><script>
// Load a module for use by plain old procedural code
require(["myapp/MyUtils"],function(MyUtils){
    MyUtils.doPopup(MyUtils.getQuote());
});
</script>
</code>```

In this way you can start to chunk your existing code into whatever organization makes the most sense to you.

Title: Refactoring jQuery spaghetti code to use DDD

Body:
Most of my client side code ends up as a long script in one file the mostly looks like this:

```<code><script>
function someFunction1(){/*...*/}
function someFunction2(){/*...*/}
...
var globalVariable1;
var globalVariable2;
...
$(function(){

$('selector1').click(function(){
    //get relevant data from various DOM elements

    //some business logic rules and validation

    //open dialog box

    //more business logic rules and more validation

    //post an ajax request

    //update the DOM
});

//many other events

//many jQuery dialogs
});
</script>
</code>```

It's a maintenance nightmare. Although I use a well designed server-side structure using DDD (application services, domain sevices, value objects,...etc.) I have had little luck structuring my client code to a better separation of concerns.

I'm not building a client-side application. I just use jQuery intensively for the client side.

How should I approach the code structure to apply DDD client-side wide?

Body:
I'm not building a client-side application. I just use jQuery intensively for the client side.

If your goal is gradual refactoring rather than a rewrite, I'd check out RequireJS, which (unlike all the other answers) is not an MVC framework.

Instead, it's just a way to break your code down into modules and to handle the dependencies between them. The mechanism for this is called "Asynchronous Module Definition", or AMD, which somewhat resembles the way classes in PHP or Java are typically organized.

Here's a ridiculously simple example:

myapp/quoteList.js

// Define a module with no dependencies that is an array
define([],function(){
    return(["Hello","World"]);
});

myapp/generateQuote.js

// Define a module with one dependency on another module and is a function
define(["./quoteList"],function(quoteList){
    var f = function(){
        var num = Math.floor(Math.random() * quotes.length);
        return quotes[num];
    };
    return f;
});

myapp/MyUtils.js

// Define a module which is an object. (Effectively a singleton)
define(["./generateQuote"],function(quotes){
    var o = {
        "getQuote" : generateQuote,
        "doPopup" : function(msg){alert(msg);}
    };
    return o;
});

page.html

<script>
// Load a module for use by plain old procedural code
require(["myapp/MyUtils"],function(MyUtils){
    MyUtils.doPopup(MyUtils.getQuote());
});
</script>

In this way you can start to chunk your existing code into whatever organization makes the most sense to you.


答:
Never trim whitespace arbitrarily in an API.

The only reason to ever trim whitespace arbitrarily is as a UI feature. People frequently leave spaces at the end of entered fields but can't see that they've done so. It's pretty confusing to return a message, so -- except in the rare case where a user might enter "A " to mean something other than "A" -- you can usually ditch any useless spaces.

But computers don't add spaces by mistake, they add spaces because a programmer told them to, and if they break your API implementation you should throw an error back to the developer. If they don't then you should just use them.

There is, of course, a possibility that this data is coming from a human via an application, but that's the application-developer's issue, not yours. Again, if they're going to cause you a problem, reject them; if not, accept them. Don't trim them and assume your consumer knows that will happen.

Title: When should you trim input?


答: I would store them in a different repo . The drawbacks you mentioned are inevitable if you have a bulky test suite. </p>


问:
What is the proper aproach of Subversion when using DLL
Background:

Our team develops a solution and it includes a number of projects. Most of the projects are built as DLLs and those DLLs are used by the rest of the projects.

Currently we uses Subversion for our code management and I ask others to remove DLLs from Subversion because we do not need to keep the history of the DLLs. So I ask my team to update their source every morning from Subversion and build each project to get DLL with yesterday submitted changes.

Issue:

This procedure was very good in the beginning f the project. but now each project of the solution getting bigger and bigger.Also gets more time to compile. now each developer waste around 20 mins each morning for build solution in their local computer.

Now I'm thinking again to ask each developer to submit their built DLLs to Subversion at end of the day and the next morning the rest of the users can download these DLLs directly from Subversion.

But I feel something is wrong with this procedure. Because Subversion waste space keeping the history records of each DLLs. Now I'm searching for a better solution.

Do you guys have any idea over your experience?

答:
Something is wrong indeed.

There are two approaches to organize development of something split in modules:

Separate and asynchronous: you version every DLL separately and treat the rest of modules similarly to third-party components. In this case every DLL should make some kind of release to provide its functionality to users (other developers). This will include putting that "released" version of DLL either to source control repository or to artefact repository.

Combined and synchronous: all DLLs are developed together and released (when needed) together, in this case you should think about speeding up build process. This can be done similarly to optimizing a program - find the biggest slow-down factor and eliminate it.

Selection between these two approaches is usually based on degree of coupling between them. If most of changes touch several DLLs, or changes in different DLLs are usually dependent on each other, likely approach #2 is more appropriate. If every DLL has stable interface, clear and specific purpose and some kind of compatibility between versions, approach #1 may be applicable.


问:
Should you hard code your data across all unit tests?
Most unit testing tutorials/examples out there usually involve defining the data to be tested for each individual test. I guess this is part of the "everything should be tested in isolation" theory.

However I've found that when dealing with multitier applications with a lot of DI, the code required for setting up each test gets very long winded. Instead I've built a number of testbase classes which I can now inherit which has a lot of test scaffolding pre-built.

As part of this, I'm also building fake datasets which represent the database of a running application, albeit with usually only one or two rows in each "table".

Is it an accepted practice to predefine, if not all, then the majority of the test data across all the unit tests?

Update

From the comments below it does feel like I'm doing more integration than unit testing.

My current project is ASP.NET MVC, using Unit of Work over Entity Framework Code First, and Moq for testing. I've mocked the UoW, and the repositories, but I'm using the real business logic classes, and testing the controller actions. The tests will often check that the UoW has been committed, e.g:

```<code>[TestClass]
public class SetupControllerTests : SetupControllerTestBase {
  [TestMethod]
  public void UserInvite_ExistingUser_DoesntInsertNewUser() {
    // Arrange
    var model = new Mandy.App.Models.Setup.UserInvite() {
      Email = userData.First().Email
    };

    // Act
    setupController.UserInvite(model);

    // Assert
    mockUserSet.Verify(m => m.Add(It.IsAny<UserProfile>()), Times.Never);
    mockUnitOfWork.Verify(m => m.Commit(), Times.Once);
  }
}
</code>```

SetupControllerTestBase is building the mock UoW, and instantiating the userLogic.

A lot of the tests require having an existing user or product in the database, so I've pre-populated what the mock UoW returns, in this example userData, which is just an IList<User> with a single user record.

答:
I think it is pretty common to hard code most of the data for your tests.

Consider a simple situation where a particular data set causes a bug to occur. You might specifically create a unit test for that data to exercise the fix and ensure that the bug doesn't come back. Over time your tests will have a set of data that covers a number of test cases.

Predefined test data also allows you to build a set of data that covers a wide and known range of situations.

That said, I think there is also value in having some random data in your tests.