问:
If you favor "T *var", do you ever write "T*"?

Possible Duplicate:

  int* i; or int *i; or int * i;

Thinking about where we place our asterisks; how do those that prefer to keep the "pointerness" away from the type and with the identifier (int *i) write code when the identifier is missing?

```<code>void f(int*); // 1
void f(int *); // 2
</code>```

The former seems much more common, no matter what your preference when with the identifier.  Is this a special case?  What makes it an exception?

However, the first still isn't universal, because I have seen the latter style.  Besides consistency along the lines of "there's always a space with the identifier, so we have one without", are there any other reasons to prefer it?

What about casts or array and function types?  How would you re-write these:

```<code>(void*)var /*or*/ (void *)var

int[3] /*or*/ int [3]
// more relevant in C++ than C: Example<int[3]>

void(int) /*or*/ void (int)
// more relevant in C++ than C: std::function<void(int)>
</code>```

The latter two would rarely, if ever, be used in C, but are seen with C++ templates.

答:
The goal should be to make the code readable and clear. The style int* a; may seem fine, but when it becomes int* a, b; it implies something different than what it really is. Contrast with int *a, b; and int *a, *b; where each reads exactly like the way it works.

The difference between void f(int*); and void f(int *); for readability is negligible, and I can't find myself caring much which one is used.

When you remember the top level goal (readability) it's easier to separate pure nitpicks from potential comprehension/maintenance problems.

OwnerDisplayName: Roger Pate


问:
Specific empty children classes
Is having empty children classes, just to specify, a bad practice?

Lets suppose I've a generic Product class. There are electrical, electronic and mechanical products. I need to represent all them and must be able to differ each one in some operations.
I've two options:

add a member named "type" in Product class to specify whether it's a electrical, electronic or mechanical product.

create children classes of Product, one for each kind of product: ElectricalProduct, ElectronicProduct and MechanicalProduct. As these classes don't differ from each other in methods or members - already defined in parent class - they would be all empty.

I consider second option a better approach, but is it the right way? I've never seen such thing on any application or library.

What do you thing? Any suggestion?

Edit:

Here is an example of doing it using second option: https://gist.github.com/tsouzar/c2ffebbcdad30920bf06

I can't see a better way of doing it, but I don't know if it is a good practice to have that empty classes.

答: My opinion is that adding a type member is a better solution. It's simpler to define, allows you to treat the type as a first-class value, lets you code Product as a plain old data structure (which it is), works without RTTI, and you can use a switch instead of multiple if/else to efficiently branch based on the type. Using inheritance your code can break if someone introduces a new subclass, since you're only expecting a finite number of types of products.

ContentLicense: CC BY-SA 3.0

Title: Specific empty children classes


问:
Reuse a small method from Apache Ant: How to do that correctly
I adapted some code from the Apache Ant project in my work. The part I used is really small: ~70 lines, ~2000 characters. Adding dependency to ant to use that a single method seemed like an overkill.

The project I work on is internal to the company, so I initially included a javadoc like

```<code>    @see original source
</code>```

for my colleagues to know the code wasn't mine.

Then I encountered this summary at tldrlegal which states that this is not enough, and to do this properly I have to do much more:

Include Copyright

Include License: Including the full text of license in modified software.

State Changes: Stating significant changes made to software.

Include Notice: If the library has a "NOTICE" file with attribution notes, you must include that NOTICE when you distribute. You may append to this NOTICE file.

From this I deduce that I actually have to include NOTICE file from ant (it's like 10 lines), somehow redistribute Apache 2 license text with the project, and include a monster comment like this before the function body or before the beginning of my class:

```<code>   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
</code>```

Is there a more compact but still correct way to do it, or is there no other way? Introducing lots of changes because I only use a minuscule part of the project (namely, a single ~70-line method) will negatively impact code-review quality and maintainability of the final code.

P.S. I don't seek professional law advice, just some common-sense-based guidelines for this situation, preferrably with examples from other open-source projects.

答:
I ultimately chose to add Ant (org.apache.ant:ant) as dependency and pack it into uberjar with maven-shade-plugin. This way original code is re-used (which was my goal), and license-maven-plugin can download all project dependencies' licenses automatically. There is a small drawback of increased uberjar size, but it is negligible (~2 Mb for ant 1.9.4).

Some comments on my original approach:

As per point 4 of the Apache 2.0 license, a copy of the license must be included. NOTICE file must be added as well, because ant already has it. So there is no "more compact but correct way" that I searched for.

Copying the original Commandline class verbatim, or adding Commandline class with appropriate license comment and only the methods I used offers better readability than adding license comment above the copied method's body.

Body:
I adapted some code from the Apache Ant project in my work. The part I used is really small: ~70 lines, ~2000 characters. Adding dependency to ant to use that a single method seemed like an overkill.

The project I work on is internal to the company, so I initially included a javadoc like

```<code>    @see <a href="...">original source</a>
</code>```

for my colleagues to know the code wasn't mine.

Then I encountered this summary at tldrlegal which states that this is not enough, and to do this properly I have to do much more:

Include Copyright

Include License: Including the full text of license in modified software.

State Changes: Stating significant changes made to software.

Include Notice: If the library has a "NOTICE" file with attribution notes, you must include that NOTICE when you distribute. You may append to this NOTICE file.

From this I deduce that I actually have to include NOTICE file from ant (it's like 10 lines), somehow redistribute Apache 2 license text with the project, and include a monster comment like this before the function body or before the beginning of my class:

```<code>   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
</code>```

Is there a more compact but still correct way to do it, or is there no other way? Introducing lots of changes because I only use a minuscule part of the project (namely, a single ~70-line method) will negatively impact code-review quality and maintainability of the final code.

P.S. I don't seek professional law advice, just some common-sense-based guidelines for this situation, preferrably with examples from other open-source projects.


问:
Is there an effective way to test XSL transforms/BizTalk maps?
Creating repeatable tests for BizTalk maps is frustrating. I can't find a way to handle testing them like I'd do unit testing, because I can't find ways to break them into logical chunks. They tend to be one big monolithic unit, and any change has the potential to ripple through the map and break a lot of unit tests. Even if I could break it up, creating XML test inputs is painful and error prone.

Is there any effective way of testing these? I'd settle for recommendations for testing XSL transforms in general, but I specifically mention BizTalk maps primarily for the reason that when using the mapper, there really isn't any way to break your XSLT into templates (which I'd imagine you could use to break up your logic into testable chunks, but I've honestly never gotten that far with XSLT).

答: For testing XSLT I rely on two command-line tools: the hopefully familiar xmllint for validity and xmlstarlet for data validation.  The latter allows you to create shell scripts to pull out data elements for testing within that script.  You can use arbitrary XPath and so test things like the number of elements in an output document.  Thus you can create a test directory next to your XSLT which has a sample input document along with a script to produce the output and test it.


问:
What is the difference between user requirements and system requirements?
From what I've read I believe user requirements are just the system requirements given in lay mans terms, is this correct? I'm specifically referring to the book "Software Engineering" by Ian Sommerville which I am obligated to follow. Given the example below from said book, why is there not a user requirement to match the second system requirement. For example "the user requires the report to be generated after 17.30 on the last working day of the month." To me that is still in natural language so it is readable by the user. How much detail should be included in a user requirement vs system requirement and where do you draw the line?

User Requirement Definition:

```<code>1. The MHC-PMS shall generate monthly management reports showing
   the cost of drugs prescribed by each clinic during that month.
</code>```

System Requirements Specification:

```<code>1.1. On the last working day of each month, a summary of the drugs
     prescribed, their cost, and the prescribing clinics shall be generated.
1.2. The system shall automatically generate the report for printing after
     17.30 on the last working day of the month.
</code>```

答:
In the sense of Ian Sommerville's software engineering book:

User requirements talk about the problem domain, the world of the user.
They describe what effects need to be achieved.
These effects are the combined responsibility of the software,
the hardware, and the users (together: the socio-technical system).

System requirements talk about the solution domain, the world
of the software logic.
They describe what the software must do (as opposed to the effects
in the user's world that this may or may not achieve).
They are the responsibility of the technical system alone (without the socio part).

For instance for a bookkeeping software,

the user requirement is to compute the correct revenue.

But the system requirement is only to compute the correct sum
of the partial revenues entered by the user.

If the user enters incorrect partial revenues the software is
not required to magically correct them: The output will
be the correct sum of the inputs, but not the correct overall revenue.

The difference is not overly interesting for most simple information systems.
It can be very important for life-critical software; see for instance the
various accidents involving the issue when or when not the thrust reversal
can be activated on a commercial airplane: The user requirement
"reverse thrust can only be activated if the airplane is on a runway"
has turned out to be surprisingly tricky to turn into system requirements
that reliably lead to the desired effect.

ContentLicense: CC BY-SA 4.0


问:
How do I efficiently send notifications for different events to different users based on their preferences?
I'm creating a notification system for particular events.

A user can set the criteria that match particular events (ie. New item, changed item, closed item etc) Items have different characteristics (ie. Minor, Major, Critical). So a user may set up a search for All New Critical Items.

What is the most efficient way to identify the ones that match the users' saved searches and send notifications to them every time an event happens?

One way would be to run ALL the saved searches for all users, every time an event happens and see which items are in those search results and send notifications.

The problem with this method I see is that it is inefficient (saved searches could become quite a few) and the complexity of this algorithm is directly proportional to the number of searches.

Does anyone know how websites, such as property websites do it? They send out emails for new properties that match users' searches.

I'm thinking of a way to map new events to users, given their search somehow without running all the searches.

答:
We're currently building a web service to solve problems like this (with very complex rules, including negative rules - things not happening). Unfortunately it's in private beta right now and we're capped on users. However, hopefully I can share the details on how to build a much simpler version (minus negation).

As you outlined as your data grows it will become very slow to run through all the saved searches in a traditional relational database. If I've read your question correctly your events should contain all the data about whether a notification should be fired or not. I would create a namespace like naming convention for events like 'new-item:minor', 'new-item:critical', 'closed-item:major'. Use these namedspaced events as the keys in a key value store like redis with the value being what should happen if that event arrives.

When an item is saved, updated, destroyed etc. use an aggregator like statsd to push the namespaced event key to a log.

Then you'll have a data collector like fluentd watching that log file and running a background worker whenever an event key is pushed in. The worker looks up the redis key and either finds nothing and does nothing or sends out the appropriate event.

That's about it, if you change fluentd's config file to check every second (I think the default is a minute) you can have near real-time event notifications.


问:
Help Improve DB model/strategy, for use in refactoring SQL-ridden legacy code
Question:

Which design pattern do I use to help me refactor legacy SQL code into separate classes?

Goal

Bring in concepts of data separation and database separation and also latest modern techniques I may not yet be aware of (if any), to bring quality to spaghetti-coded test-less legacy PHP code base.

Details:

I am looking for a good model to help me refactor out DB code in a large legacy php project.  I thought at first to use TableModule, but seeing how my SQL is complex, I think DomainModel may be better.  But still I do not know how to implement it as description is too abstract.  Maybe Service Layer is what I need...  but to be honest, I am kind of lost.

Sample SQL that I deal with (one of many):

```<code>        SELECT
            db1.item.quantity,
            db1.sheet.serial,
            db2.work.id AS work,
            db3.part.id AS partid,
            db3.part.number,
            db3.part.description,
            db3.part.current_inv
        FROM db1.item
            LEFT JOIN db1.partial ON db1.partial.id = db1.item.db1_partial_id
            LEFT JOIN db1.sheet ON db1.sheet.id = db1.partial.db1_sheet_id
            LEFT JOIN db2.work ON db2.work.id = db1.sheet.db2_work_id
            LEFT JOIN db3.part ON db3.part.id = db1.item.db3_part_id
        WHERE
            db1.sheet.status != 'VOID' AND
            db1.item.id = "$itemid" AND
            db1.item.record = 0
</code>```

It ties up 3 databases and multiple tables.  Considering that I want to decouple SQL from my app, and decouple app from data handling, and having complex SQL queries like above, what do you suggest I do?

My current sample plan is

find next available stray SQL inside legacy code

determine what it is trying to do - i.e. save/update what data on what object or model.

create or add to the class that best encompasses SQL.  For example, above SQL checks if inventory has been used up for an item.  So I can place it into some class called CheckInventoryData, and be happy with that.. until maybe I learn something that makes me want to change the name of the class, for example.  i.e. HandleItem, and put that class in some directory structure for database handling, i.e. /db_handling_code

have a function in that class saying isInventoryUsedUpForItem($item), or the like

repeat....

While I think this will work, I do not feel too confident about my plan.  I am hoping to find solidification of it in a more modern/industry accepted practice.  And finding that plan is my question -- is there a better plan available.  -- is there a model I should aspire towards?

答:
I'll attempt if not answer your question, at least give some hints. As a side note, I've contributed to refactoring of several medium-sized projects (although not as big as yours), especially the ones which had data access directly mixed with business code, so the answer is partially based on my personal experience.

Identify the problem

The first thing I note in your question and comments is that it doesn't seem clear whether you have an actual problem you want to solve:

Right now, I am looking to more so add modern concepts to my code. Things like looser coupling, data injection, database injection, and whatever else modern techniques relating to data codification are.

Adding modern concepts shouldn't be your goal. Neither do lose coupling or data injection. The first thing to do is to identify the actual problem, i.e. something which blocks you right now and should be solved (eventually through lose coupling, data injection, or anything else).

That the actual problems might be:

Problem 1■ the difficulty to unit test the code. Whenever you want to test a simple function, you can't do it in isolation, because it relies heavily on the database.

Problem 2■ the difficulty to find the relevant SQL query, because instead of following a clear architecture, queries are buried deep in business logic.

Thus, I'll address those two problems below. Remember that it is imperative, before you search for the solution, to identify the problem. Otherwise, you may find yourself doing a lot of unneeded work or making things worse.

Study the environment
(Identify the scope of the problem)

Don't overly focus on the location of SQL queries, but watch the overall architecture of the application. It might be that the problem is particularly visible when it comes to SQL queries, but applies to the overall code base.

Three years ago, I had to maintain a small application. It had SQL queries mixed with business logic, but the previous developer did a great work defining the architecture of the application. I don't know why he refused to use n-tier, but the fact is that every time I had to find an SQL query, it was a matter of seconds, because the code was clear, classes were separated enough and naming conventions were excellent. While Cart class was dealing at the same time with data access, business logic and presentation, it was easy to guess that the SQL query which changes the quantity of a product in a cart would be in a function similar to $cart->changeQuantity($customer, $product, $delta).

If you have a good grasp on the scope of the problem, you may target better the parts of the code base which should be changed. In your case, if you're concerned particularly about the location of the SQL queries (Problem 2■), but have found that the scope is larger (i.e. the lack of architecture concerns the whole code base), you would be better refactoring everything, not just the database-related code.

Don't overly rely on a tool

When searching for a solution, you'll find promising tools, as well as people recommending a specific tool, pattern or technique which will magically solve your problems.

Just use ORM! It will make data access much simpler!

Just use <some pattern here>, and your code will become easy to maintain!

While those tools, patterns or techniques are helpful, they won't magically solve anything. At best, they will push the code base in a good direction with little impact. In worst case, they will require weeks or months of hard work and will have practically no positive impact.

Take an ORM. Yes, this will make your code simpler. In many cases, at least. But this doesn't make the code easier to test (Problem 1■) and may make it even harder to find the location where a specific SQL query is generated (Problem 2■), since you won't be able to grep the query itself any longer. It some cases, it might even have a negative impact of having two completely different ways of accessing data: through an ORM, for simple cases, and directly, for more difficult ones.

Solve the problem pragmatically

Once you identified the problem and its scope, the goal is now to solve the problem pragmatically, without overly relying on a single tool, pattern or technique (while using tools, patterns and techniques when needed).

The way I approached the problem in the past is the following in order to solve the two problems identified above.

Find next available stray SQL inside legacy code.

Determine what it is trying to do, i.e. save/update what data on what object or model.

Those two steps are exactly the same as the ones in your question.

Create either functional or integration and system tests corresponding to this part of the code. Functional, integration and system tests usually run on a test database, specifically filled with test data.

This will serve as regression tests when you start making changes. Since those tests are at a high level (for example they may do an HTTP request to a web app instead of dealing with the underlying classes and interfaces), they should not be affected by the later changes in the code itself.

Check the coherence of the architecture/design of the class where the concerned SQL query was found. For example, if I find a query which changes a name of the product from Cart class, that's not right. Refactoring, in this case, is mandatory. (Problem 2■)

Ensure the query is doing what it is supposed to do. Untested legacy code contains lots of surprises, and it is not unusual to find functions with misleading names, selection queries with side effects which always return an empty result, or update queries which don't change anything. (Problem 2■)

This step also involves dealing with legacy horror such as dynamically generated queries (should be replaced by parametrized queries).

Ensure the query is as simple as it can be. Make it simpler, if possible.

Ensure you use all capabilities of your database engine you need to make things as simple as possible. For example, as I previously commented on your question, the query from your question might be replaced by a view.

Study the queries refactored in the past in order to identify potential code duplication. This may be as obvious as finding the exact same query somewhere else, or may be more difficult if only a part of a query is duplicated (for example same query but with an additional where criteria). (Problem 2■)

If duplication found, deduplicate.

Find a name for the query. (Problem 2■)

(Create a type which represents what the query returns or what it needs. The type should basically have one property per column in select. Since you're using a dynamic language, you may not need to do this step.)

Extract the query into a function and locate a class which should contain this function.

If the class doesn't exist:

Find an explicit name. You may use a naming convention such as ...Repository (ProductsRepository, CustomersRepository).

Create the class.

Create the corresponding interface. (Problem 1■)

Create the default mock which implements the interface. This mock returns zero rows in data retrieval functions and does nothing in data altering functions.

Create one or several mocks and/or stubs relevant in the context of the business code which uses the SQL query. Create the corresponding unit tests. They should be red at this stage, since your business code doesn't use the stubs/mocks yet. (Problem 1■)

Change the business code to use the newly created function instead of a direct query. Unit tests should be green now.

I wouldn't care about design patterns here (well, that would be a repository pattern, but again, I don't care). Once you get your 2 200 SQL queries out of your business code, you can start playing with ORMs, design patterns, etc. The main benefit is that you'll have your business logic completely separated from data access, and also covered by unit tests. With data access layer (DAL) and business layer (BL) communicating through interfaces, you have more room for experimentation.

A practical example is that I can now create a different implementation of DAL which uses an ORM while my team continues working with the previous implementation. Then, moving from one to another should consist of a tiny change of configuration (if dependency injection is used).

More importantly, experimentation becomes easier at this step. You can start implementing an ORM, find it to be a mistake, and abandon this particular implementation without having to revert code base to previous revision.


问:
Why is it you never get as much done as you'd planned?
I always start the day thinking "I'll easily get this done by the end of the day" and set what looks like a realistic target.

So why do I never hit it? The task always ends up taking 3x longer due to unforeseen bugs, last minute changes etc.

Is it just me?  I don't seem to be getting any better predicting what can be done in a day.

答:
That's a good question and one that I'm constantly pondering. I tend to think that

it's very easy to misjudge the amount of work feature X will take.

I never plan for bugs or trips to the kettle.

either you get a lot done with little code or nothing done will lots and there seems to be no in between.

sometimes you lose your 'zone', sometimes things need thinking through.

ContentLicense: CC BY-SA 2.5


问:
How to license open source code you have heavily modified under the BSD license
I've created a heavily modified and more reusable version of this Qt Quick Scene Graph example. Every source file includes a BSD license. The following lines basically say I have to include the entire copyright notice and list of conditions with the modification distribution:

```<code>** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
</code>```

Is it enough to simply reference the license in every derived source file of mine, or do I really need to include the whole notice in every source file? My modifications are radically different and hardly resemble the original example, yet they were iteratively derived from the original code. I understand this is a trivial example and Digia probably couldn't care less, but I want to do this the right way.

答:
As stated in the license you quoted, you must keep the entire copyright notice, license and disclaimer intact.

It is not sufficient to replace it with a reference.

What you are allowed to do (and really should do) is add your own copyright to the existing copyright notice.


问:
What roadblocks face the development process in using plain-text markup languages as opposed to, e.g., Microsoft Word?
I'm currently an intern at a government contractor and am getting the (obnoxiously unavoidable) feeling that Word is the de-facto standard in the software development process.

Its binary format makes it very difficult to collaborate on documents in the way I am used to collaborating on a code base.  The use of plain text markup (with such languages as LaTeX, Markdown, ReStructured Text, etc.) allows for a diff-friendly document that works well with the normal workflow of a developer.  As for comments where the language doesn't support them (eg Markdown), there are many existing solutions that allow collaborative comments on code bases (eg GitHub, Bitbucket) that could easily be applied to other plain-text files containing markup.

I understand the need to cooperate with technologically illiterate management necessitates some sort of graphical interface to everything, but such interfaces exist for most of these formats.  For example, LaTeX has a 'fork' of sorts called LyX that puts a graphical front-end to a plain-text, LaTeX-like syntax.  This file, even though primarily graphical in its editing, is still diff-friendly.  (It even also has Word-style comments.) Many of these solutions could yet be used instead of Word, and the vast majority are free or open-source.

However, we use Word even for our own internal documentation that nobody else sees.  We work with text for a significant chunk of our career---why is documentation so special?  Aside from the trivial "We didn't know any better and now we're stuck here", there must be reasons supporting such a decision.  What challenges face the software development process in using plain-text documentation in lieu of other, more colloquial (and debatably less powerful) means of writing documents?

Since the reasons will differ, perhaps answering for these two closely related scenarios separately should be in order.

Using plain-text documentation from the start

Migrating to plain-text documentation over time

答:
You really have 2 questions:

First: Why do non development groups not use LaTeX or other Markdown in the software development process?

The problem with migrating to LaTeX is the perceived learning curve particularly when you are dealing with non technical users. Users already know other formats and don't want to have to learn another method of doing the same thing they been doing. They know little if anything about how to diff 2 documents and so there is little value in changing to a text based format for them. Explaining to a person that you have a solution for a problem they didn't know they had is a pretty tough sell.

You also can't underestimate the value of forward momentum. In order to migrate to a new format you really have to convince other people in your chain it is a worth while to investment in learning something new. Even if you don't expect them to edit anything It takes time and a lot of effort to migrate to a new format when an existing format works (even if poorly).

The second question: Why does my team continue to use word documents when there are better options and they are more than capable of learning them?

This is something that you should talk with the people on your team about. There may be valid reasons that they choose to maintain word documents or it may just be because that is the way it has always been done.

There are costs associated with any change and it can be expensive and time consuming to move hundreds or thousands of documents to a new format. If you are going to try to change your environment expect to have to make a case for why you should change


问:
Merging very big branch with master
I have rather big git branch with code that was created on may of this year and never before was merged with master. Compare shows huuuge difference between branch and master: about 50 new files and about 150 modified files. I'm really worried about forthcoming merge.

What can you recommend? Any advises about how better to merge etc.? Have you ever met similar situation? Any, absolutely any notices and advises are highly appreciated.

PS: Repository is under git. The most important parts of project are covered with unit tests. I'm using IDE by JetBrains (if it is important).

答: Rebase and resolve any conflicts. Then run your tests (you do have tests, right?) on the branch. If everything passes, you're good to merge.</p>

Title: Merging very big branch with master


问:
Front-end or Back-end Implementation of API?
Lets say I want to implement an API from an external website, for example like Dribbble or Last.fm.

I'm fairly new to this new generation of front-end MVC's (angular, etc), and most example's I've seen implement API's in the front-end with use of ajax calls.

So my question is this, is there a benefit of doing this, instead of lets say calling the API requried in the back-end(php)? What are some obvious drawbacks/benefits from each approach?

答:
Interactivity.

Putting functionality in the browser has the same advantages that putting functionality in any other user interface does, as opposed to just showing static forms: you get to interact with the user in real-time, instead of waiting for the user to fill out the form, submit it to the server, and wait for a full-page response.

Some examples of this:

Validating fields as the user types them.

Providing real-time display and updates of dashboard data, widgets or graphs.

Providing real-time control of and access to server functionality.

Allowing for other modes of interaction, such as machine to machine.

And so on.

Imagine a first-person shooter game that didn't have these facilities, that relied on a postback of the entire page for anything to happen.  Wouldn't be very interesting or nimble, would it?


问:
How to unit test a function that is refactored to strategy pattern?
If I have a function in my code that goes like:

```<code>class Employee{

    public string calculateTax(string name, int salary)
    {
        switch (name)
        {
            case "Chris":
                doSomething($salary);
            case "David":
                doSomethingDifferent($salary);
            case "Scott":
               doOtherThing($salary);
       }
}
</code>```

Normally I would refactor this to use Ploymorphism using a factory class and strategy pattern:

```<code>public string calculateTax(string name)
{
    InameHandler nameHandler = NameHandlerFactory::getHandler(name);
    nameHandler->calculateTax($salary);
}
</code>```

Now if I were using TDD then I would have some tests that work on the original calculateTax() before refactoring.

ex:

```<code>calculateTax_givenChrisSalaryBelowThreshold_Expect111(){}
calculateTax_givenChrisSalaryAboveThreshold_Expect111(){}

calculateTax_givenDavidSalaryBelowThreshold_Expect222(){}
calculateTax_givenDavidSalaryAboveThreshold_Expect222(){}

calculateTax_givenScottSalaryBelowThreshold_Expect333(){}
calculateTax_givenScottSalaryAboveThreshold_Expect333(){}
</code>```

After refactoring I'll have a Factory class NameHandlerFactory and at least 3 implementation of InameHandler.

How should I proceed to refactor my tests? Should I delete the unit test for claculateTax() from EmployeeTests and create a Test class for each implementation of InameHandler?

Should I test the Factory class too?

答:
My opinion is that you should do nothing, meaning you should not add any new tests.

I stress that this is an opinion, and it actually depends on the way you perceive the expectations from the object. Do you think the user of the class would like to supply a strategy for tax calculation? If he doesn't care, then the tests should reflect that, and the behaviour reflected from the unit tests should be that they should not care that the class has started to use a strategy object to calculate tax.

I actually ran into this problem several times when using TDD. I think the main reason is that a strategy object is not a natural dependency, as opposed to say an architectural boundary dependency like an external resource (a file, a DB, a remote service, etc.). Since it is not a natural dependency, I usually don't base the behaviour of my class on this strategy. My instinct is that I should only change my tests if the expectations from my class have changed.

There's a great post from Uncle Bob, that talks exactly about this problem when using TDD.

I think that the tendency to test each separate class is what's killing TDD. The whole beauty of TDD is that you use tests to spur up design schemes and not vice versa.


答: Because I spend too much time on Stack Overflow.</p>

Title: Why is it you never get as much done as you'd planned?

Body:
I always start the day thinking "I'll easily get this done by the end of the day" and set what looks like a realistic target.

So why do I never hit it? The task always ends up taking 3x longer due to unforeseen bugs, last minute changes etc.

Is it just me?  I don't seem to be getting any better predicting what can be done in a day.


问:
Term for 24-bits
Is there a term for a 24-bit (3-byte) integer?

I know uncommon bit counts (such as a "nibble" or "nybble" for 4 bits) have names, and having 24-bits in both video and audio technology, for instance, is very common.

答:
Some languages have types named according to the value format and bit width. C++ has int32_t, .NET has Int32, and Go has int32.

All programmers should immediately recognize the meaning of a derived term like int24, so I think it would be acceptable to use anywhere that an alternative term has not been provided.

There are even implementations on SO for C++ and C#.

Title: Term for 24-bits


答:
Do a zip-merge.

This is a sequence of merges, that simulate what may have happened if you had merged earlier. The resulting dag will look like a zip.

This is based on the assumption that the sum of the complexity of each small merge is lower than the complexity of a large merge. This will be so if there are a lot of conflicts. If I remember correctly complexity ≈ conflicts² and a² + b² + c² < (a+b+c)²

Title: Merging very big branch with master

Body:
I have rather big git branch with code that was created on may of this year and never before was merged with master. Compare shows huuuge difference between branch and master: about 50 new files and about 150 modified files. I'm really worried about forthcoming merge.

What can you recommend? Any advises about how better to merge etc.? Have you ever met similar situation? Any, absolutely any notices and advises are highly appreciated.

PS: Repository is under git. The most important parts of project are covered with unit tests. I'm using IDE by JetBrains (if it is important).


问:
Code First vs. Database First
When I design and create the software I work on, I typically design and create the back-end SQL tables first and then move on to the actual programming. The project I'm currently working on has me down right puzzled though. This is probably due to a lack of good, solid requirements, but there's unfortunately little I can do about that this time. It's a "just go make it happen" kind of situation.. but I digress.

I'm thinking of flipping my workflow on it's head and creating the UI and data model classes first in hopes that working that out will make it clear to me what my database schema will eventually look like. Is this a good idea? I'm nervous that I'll end up with a UI and still no idea of how to structure the db.

If anyone is curious, I'm using SQL Server as a backend and MS Access as a front end application. (Access isn't my choice either... so please don't hate on it too bad.)

答:
A root cause analysis suggests this problem is not one of method, but is the lack of a specification.  Without one it doesn't really matter what you write first - you are going to throw it away anyway.

Do yourself a favour and do some basic systems analysis - identify some users at various levels, make up a quick & dirty questionnaire then turn off your machine, grab some coffee and cookies/donuts (or whatever greases the wheels) then take a walk to their desks, ask them what they do and what they need to know/record to do their job even if it seems obvious - still ask.  Don't worry about how important they are, if they're too busy then make an arrangement to come back another time or leave it with them.

Once you have that you should be able to start building whatever you think will give you the best results and wait for the rest of the specification to come in.

Title: Code First vs. Database First


答:
Since this seems so fluid/unspecified, I'd do the frontend GUI first - that sounds like what you need to get responses, support, time, and feedback from the stakeholders, right?  They don't care about your brilliant normalized tables and foreign keys constraints and cascading deletes.  But a cool GUI with lots of shiny colors - well, that's top notch!

For the initial backend "database", use something extremely simple, maybe just keys/values stored to a file.  I'm unfamiliar with MS Access, so don't know what the "lightweightiest" backend would be.  (a spreadsheed table?)  Whatever is quick and dirty, plan on throwing it away.

If you can, use a funny look and feel in the GUI to make it clear that it is a prototype.  If all else fails, use index cards.

Now, maybe your stakeholders are DB experts - that has been the case with me sometimes! - in which case, do some DB designs.

Title: Code First vs. Database First

Body:
When I design and create the software I work on, I typically design and create the back-end SQL tables first and then move on to the actual programming. The project I'm currently working on has me down right puzzled though. This is probably due to a lack of good, solid requirements, but there's unfortunately little I can do about that this time. It's a "just go make it happen" kind of situation.. but I digress.

I'm thinking of flipping my workflow on it's head and creating the UI and data model classes first in hopes that working that out will make it clear to me what my database schema will eventually look like. Is this a good idea? I'm nervous that I'll end up with a UI and still no idea of how to structure the db.

If anyone is curious, I'm using SQL Server as a backend and MS Access as a front end application. (Access isn't my choice either... so please don't hate on it too bad.)


答:
What came first, the process, or the data used by that process? I know this is kind of a "chicken or the egg" question, but in the case of software, I believe it is the process.

For instance, you can build up your data model incrementally by implementing a single use-case at a time with just in-memory persistence (or anything as easy to implement). When you feel you've implemented enough use-cases to outline the basic entities, you may replace the in-memory persistence by a real database, and then continue to refine the schema as you go forward, one use-case at a time.

This takes the focus out of the database and moves it to the core of the problem: the business rules. If you start by implementing the business rules, you'll eventually find (by a process very similar to Natural Selection, by the way) which data is truly needed by the business. If you start by modeling the database, without the feedback of whether that data is truly needed (or in that format, or in that level of normalization, etc...), you'll either end up doing a lot of late adjustments in the schema (which may require heavy migration procedures, if the business is already running with it), or you'll have to implement "work-arounds" in the business rules to make up for the out-of-tune data model.

TL;DR: The database depends on the the business - it is defined by them. You won't need the data unless you have a process that operates with it (a report is also a process). Implement the process first, and you'll find which data it needs. Model the data first, and you may just be able to count how many assumptions were wrong when you first modeled it.

A little out of the topic but very important: the workflow I describe is often used along with very important practices such as "The simplest thing that could possibly work", test-driven development, and a focus on decoupling your architecture from the details that get in your way (hint: database). About the last one, this talk sums up the idea pretty well.

Title: Code First vs. Database First


问:
Infix vs Prefix Notation - Which do you prefer?
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

答:
I vastly prefer to have prefix when I'm reading code.

But infix when thinking about code.


问:
Is there a downside to using AggressiveInlining on simple properties?
I bet I could answer that myself if I knew more about tools to analyze how C#/JIT behaves but since I don't, please bear with me asking.

I have simple code like this :

```<code>    private SqlMetaData[] meta;

    private SqlMetaData[] Meta
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            return this.meta;
        }
    }
</code>```

As you can see I put AggressiveInlining because I feel like it should be inlined.

I think. There's no guarantee the JIT would inline it otherwise. Am I wrong?

Could doing this kind of thing hurt the performance/stability/anything?

答:
EDIT: I realize my answer didn't exactly answer the question, while there is no real downside, from my timing results there is no real upside either. The difference between a inline property getter is 0.002 seconds over 500 million iterations. My test case may also not be 100% accurate since its using a struct because there are some caveats to the jitter and inlining with structs.

As always, the only way to really know is to write a test and figure it out. Here are my results with the following configuration:

Windows 7 Home
8GB ram
64bit os
i5-2300 2.8ghz
```

<p>Empty project with the following settings:  </p>

<pre class="lang-none prettyprint-override"><code>.NET 4.5
Release mode
Start without debugger attached - CRUCIAL
Unchecked "Prefer 32-bit" under project build settings
</code>```

Results

struct get property                               : 0.3097832 seconds
struct inline get property                        : 0.3079076 seconds
struct method call with params                    : 1.0925033 seconds
struct inline method call with params             : 1.0930666 seconds
struct method call without params                 : 1.5211852 seconds
struct intline method call without params         : 1.2235001 seconds
```

<p>Tested with this code:</p>

<pre class="lang-c# prettyprint-override"><code>class Program
{
    const int SAMPLES = 5;
    const int ITERATIONS = 100000;
    const int DATASIZE = 1000;

    static Random random = new Random();
    static Stopwatch timer = new Stopwatch();
    static Dictionary<string, TimeSpan> timings = new Dictionary<string, TimeSpan>();

    class SimpleTimer : IDisposable
    {
        private string name;
        public SimpleTimer(string name)
        {
            this.name = name;
            timer.Restart();
        }

        public void Dispose()
        {
            timer.Stop();
            TimeSpan ts = TimeSpan.Zero;
            if (timings.ContainsKey(name))
                ts = timings[name];

            ts += timer.Elapsed;
            timings[name] = ts;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 4)]
    struct TestStruct
    {
        private int x;
        public int X { get { return x; } set { x = value; } }
    }

    [StructLayout(LayoutKind.Sequential, Size = 4)]
    struct TestStruct2
    {
        private int x;

        public int X
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return x; }
            set { x = value; }
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct3
    {
        private int x;
        private int y;

        public void Update(int _x, int _y)
        {
            x += _x;
            y += _y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct4
    {
        private int x;
        private int y;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update(int _x, int _y)
        {
            x += _x;
            y += _y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct5
    {
        private int x;
        private int y;

        public void Update()
        {
            x *= x;
            y *= y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct6
    {
        private int x;
        private int y;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update()
        {
            x *= x;
            y *= y;
        }
    }

    static void RunTests()
    {
        for (var i = 0; i < SAMPLES; ++i)
        {
            Console.Write("Sample {0} ... ", i);
            RunTest1();
            RunTest2();
            RunTest3();
            RunTest4();
            RunTest5();
            RunTest6();
            Console.WriteLine(" complate");
        }
    }

    static int RunTest1()
    {
        var data = new TestStruct[DATASIZE];
        var temp = 0;
        unchecked
        {
            //init the data, just so jitter can't make assumptions
            for (var j = 0; j < DATASIZE; ++j)
                data[j].X = random.Next();

            using (new SimpleTimer("struct get property"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        temp += data[j].X;
                    }
                }
            }
        }
        //again need variables to cross scopes to make sure the jitter doesn't do crazy optimizations
        return temp;
    }

    static int RunTest2()
    {
        var data = new TestStruct2[DATASIZE];
        var temp = 0;
        unchecked
        {
            //init the data, just so jitter can't make assumptions
            for (var j = 0; j < DATASIZE; ++j)
                data[j].X = random.Next();

            using (new SimpleTimer("struct inline get property"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        temp += data[j].X;
                    }
                }
            }
        }
        //again need variables to cross scopes to make sure the jitter doesn't do crazy optimizations
        return temp;
    }

    static void RunTest3()
    {
        var data = new TestStruct3[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct method call with params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update(j, i);
                    }
                }
            }
        }
    }

    static void RunTest4()
    {
        var data = new TestStruct4[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct inline method call with params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update(j, i);
                    }
                }
            }
        }
    }

    static void RunTest5()
    {
        var data = new TestStruct5[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct method call without params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update();
                    }
                }
            }
        }
    }

    static void RunTest6()
    {
        var data = new TestStruct6[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct intline method call without params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update();
                    }
                }
            }
        }
    }

    static void Main(string[] args)
    {
        RunTests();
        DumpResults();
        Console.Read();
    }

    static void DumpResults()
    {
        foreach (var kvp in timings)
        {
            Console.WriteLine("{0,-50}: {1} seconds", kvp.Key, kvp.Value.TotalSeconds);
        }
    }
}
</code>```

Body:
EDIT: I realize my answer didn't exactly answer the question, while there is no real downside, from my timing results there is no real upside either. The difference between a inline property getter is 0.002 seconds over 500 million iterations. My test case may also not be 100% accurate since its using a struct because there are some caveats to the jitter and inlining with structs.

As always, the only way to really know is to write a test and figure it out. Here are my results with the following configuration:

Windows 7 Home
8GB ram
64bit os
i5-2300 2.8ghz

Empty project with the following settings:

.NET 4.5
Release mode
Start without debugger attached - CRUCIAL
Unchecked "Prefer 32-bit" under project build settings

Results

struct get property                               : 0.3097832 seconds
struct inline get property                        : 0.3079076 seconds
struct method call with params                    : 1.0925033 seconds
struct inline method call with params             : 1.0930666 seconds
struct method call without params                 : 1.5211852 seconds
struct intline method call without params         : 1.2235001 seconds

Tested with this code:

class Program
{
    const int SAMPLES = 5;
    const int ITERATIONS = 100000;
    const int DATASIZE = 1000;

    static Random random = new Random();
    static Stopwatch timer = new Stopwatch();
    static Dictionary<string, TimeSpan> timings = new Dictionary<string, TimeSpan>();

    class SimpleTimer : IDisposable
    {
        private string name;
        public SimpleTimer(string name)
        {
            this.name = name;
            timer.Restart();
        }

        public void Dispose()
        {
            timer.Stop();
            TimeSpan ts = TimeSpan.Zero;
            if (timings.ContainsKey(name))
                ts = timings[name];

            ts += timer.Elapsed;
            timings[name] = ts;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 4)]
    struct TestStruct
    {
        private int x;
        public int X { get { return x; } set { x = value; } }
    }

    [StructLayout(LayoutKind.Sequential, Size = 4)]
    struct TestStruct2
    {
        private int x;

        public int X
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return x; }
            set { x = value; }
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct3
    {
        private int x;
        private int y;

        public void Update(int _x, int _y)
        {
            x += _x;
            y += _y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct4
    {
        private int x;
        private int y;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update(int _x, int _y)
        {
            x += _x;
            y += _y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct5
    {
        private int x;
        private int y;

        public void Update()
        {
            x *= x;
            y *= y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Size = 8)]
    struct TestStruct6
    {
        private int x;
        private int y;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update()
        {
            x *= x;
            y *= y;
        }
    }

    static void RunTests()
    {
        for (var i = 0; i < SAMPLES; ++i)
        {
            Console.Write("Sample {0} ... ", i);
            RunTest1();
            RunTest2();
            RunTest3();
            RunTest4();
            RunTest5();
            RunTest6();
            Console.WriteLine(" complate");
        }
    }

    static int RunTest1()
    {
        var data = new TestStruct[DATASIZE];
        var temp = 0;
        unchecked
        {
            //init the data, just so jitter can't make assumptions
            for (var j = 0; j < DATASIZE; ++j)
                data[j].X = random.Next();

            using (new SimpleTimer("struct get property"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        temp += data[j].X;
                    }
                }
            }
        }
        //again need variables to cross scopes to make sure the jitter doesn't do crazy optimizations
        return temp;
    }

    static int RunTest2()
    {
        var data = new TestStruct2[DATASIZE];
        var temp = 0;
        unchecked
        {
            //init the data, just so jitter can't make assumptions
            for (var j = 0; j < DATASIZE; ++j)
                data[j].X = random.Next();

            using (new SimpleTimer("struct inline get property"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        temp += data[j].X;
                    }
                }
            }
        }
        //again need variables to cross scopes to make sure the jitter doesn't do crazy optimizations
        return temp;
    }

    static void RunTest3()
    {
        var data = new TestStruct3[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct method call with params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update(j, i);
                    }
                }
            }
        }
    }

    static void RunTest4()
    {
        var data = new TestStruct4[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct inline method call with params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update(j, i);
                    }
                }
            }
        }
    }

    static void RunTest5()
    {
        var data = new TestStruct5[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct method call without params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update();
                    }
                }
            }
        }
    }

    static void RunTest6()
    {
        var data = new TestStruct6[DATASIZE];
        unchecked
        {
            using (new SimpleTimer("struct intline method call without params"))
            {
                for (var j = 0; j < DATASIZE; ++j)
                {
                    for (var i = 0; i < ITERATIONS; ++i)
                    {
                        //use some math to make sure its not optimized out (aka don't use an incrementor)
                        data[j].Update();
                    }
                }
            }
        }
    }

    static void Main(string[] args)
    {
        RunTests();
        DumpResults();
        Console.Read();
    }

    static void DumpResults()
    {
        foreach (var kvp in timings)
        {
            Console.WriteLine("{0,-50}: {1} seconds", kvp.Key, kvp.Value.TotalSeconds);
        }
    }
}


问:
ASP.NET MVC should I reference the DAL from the UI?
I am developing an ASP.NET MVC  application, and I have three projects:

UI (with the system.web.mvc reference, BL and DAL references)

BL (business facade  and business objects)

DAL (contains my entities/poco classes and connects to the DB using an external  assembly)

I am building my viewmodels in the UI layer, using the data contained in my DAL entities, so my UI has reference to BLL and DAL, but I'm not sure if a DAL reference should exist in the UI project.

I was thinking about creating a class in the BL layer That uses the data contained in the DAL entities, and then creating my viewmodels using the new class, but it seems very repeatitive and redundant.

What do you guys think? What I want to do is to build my viewmodels using data contained in data base

答: I generally don't expose my poco objects to the UI layer. Create a wrapper/domain objects layer that will transform the data of Dal layer. This way you can control the data going to the UI layer.</p>

OwnerDisplayName: Enrique Olvera

OwnerDisplayName: Azhar Khorasany


答:
I don't generally expose the DAL directly to the UI.

Normally, I create model classes as close as the final UI representation as possible. And wrappers that translate / transform one or more entities from the DB into those.

This, as you said, might seem a little bit redundant, but it is useful when the viewmodel gets complex enough so that you have different representations for querying multiples objects vs updating / inserting / deleting those.

It is actually inspired on the CQRS design pattern, where different representations are used for queries (the new wrapped classes you were talking) and updates back from the viewmodel to the entities using commands.

Here is a very good link from Martin Fowler's blog explaining CQRS.

I actually use Web API 2 for the commands as the web applications are really client-side intensive (KnockoutJS etc).

Title: ASP.NET MVC should I reference the DAL from the UI?

Body:
I am developing an ASP.NET MVC  application, and I have three projects:

UI (with the system.web.mvc reference, BL and DAL references)

BL (business facade  and business objects)

DAL (contains my entities/poco classes and connects to the DB using an external  assembly)

I am building my viewmodels in the UI layer, using the data contained in my DAL entities, so my UI has reference to BLL and DAL, but I'm not sure if a DAL reference should exist in the UI project.

I was thinking about creating a class in the BL layer That uses the data contained in the DAL entities, and then creating my viewmodels using the new class, but it seems very repeatitive and redundant.

What do you guys think? What I want to do is to build my viewmodels using data contained in data base

OwnerDisplayName: Jordi


答:
My experience is as follows:

In most projects I've worked on, we designed the database first.

Often times data already exists in spreadsheets, legacy databases, paper, etc. That data will give you hints about the tables you need to hold it.

Often times a process is already being used, yet manually or using several, disparate tools that are not automated, don't inter-operate and/or don't conform to standards.

Once you have a semi-mature database model you can begin designing prototype forms, windows etc., that read and write to that database.

As you continue, some changes will be necessary to accommodate for things not contemplated at first.

Also remember:

It's no longer a one-app<->one-database world. Maybe your app will have to read or write data from more than one database or your solution will comprise more than one app using the same database.

Conclusion: I recommend you to design the database first.

Title: Code First vs. Database First


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
Without any discernable cause, I was brought into a private meeting, and told not to check if my computer was being monitored - including, never ever checking my task manager for any reason. I asked if they were monitoring my computer, and was told (roughly) "this is just a preventative thing -- you know, our lawyer told us to tell the employees about this -- but you know, we can't really say -- but I'm not monitoring it now."

(nudge, I think they were monitoring my computer, just not while they were telling me not to look for any monitoring programs. In fact, a few weeks later, I came in early and literally watched the mouse moving around my screen as if by remote -- so I looked through the window of the CEO and saw him remotely clicking around on my computer from his laptop.)

OwnerDisplayName: GlennIsaac


问:
Is a good practice to call a Controller function from another Controller?
I'm having a case where I'm handling the logic of a search in one controller and I'm generating some data based on searches and returning as statistics.

Is a good practice calling a controller function from another controller? Or two controllers should never 'talk'?

答:
This is rather strange, although the answer depends on the language/framework you use, since different languages/frameworks have different approaches of MVC.

In general, you won't use one controller from another one since:

Controllers usually return a result of a type intended to be used by the MVC framework. This result contains a lot of information you, as a caller, don't need (such as the name of the view), and doesn't always make it easy to get to the information you may be interested in (in your case the model, if I guess right).

Controllers are not easy to initialize from business code, since they often need some amount of information about the HTTP request and the context. All this information is expected to be passed by the MVC framework.

More importantly, if you need a bunch of search results in two controllers—one which shows the results to the end user, another one which generates statistics, simply put the search logic in your business layer (where it belongs to in the first place, by the way), and keep your controllers as small as possible.

The role of a controller, in MVC, is to orchestrate the process:

Get the relevant input from the request,

Delegate to validators the task of validating/sanitizing the input,

Call the relevant methods of business layer,

Give to MVC framework the resulting model and the view.

The role of a controller is not to deal with business logic.

Once code moved to business layer, you can then provide a search interface which can be reusable in a clear, straightforward way, unlike one controller being used from another.


问:
PHP vs ROR for AJAX and responsive design
I'm in the planning phase of making a website for calculating various mathematical problems, as a school/sparetime project with a couple of friends. We're gonna start off with implementing a "right angled triangle calculator", and then gradually implement more mathematical stuff.

So, basically, we want some boxes that you can fill with the variables you know, and as you type in your numbers, a program will decide which equations it can use for the specified variables of the triangle, then it will calculate the answers for all the unknown variables and fill out the empty boxes with the calculated answers.

All this, we wanna do in real time.

We know, that we are gonna want to use AJAX and jQuery, but we can't decide wether to use PHP or ROR..?

We want basically everything to be executed in real time, so that we only have to reload the webpage when the user navigates to another "part" of the site.

So my question to you guys is, What would be the smartest to use? PHP or ROR?

I have read a lot about the matter, and alot of comparisons of the two, when it comes to responsive design, but there's alot of mixed feelings, as far as i can tell.

I would love your guys' opinion.

Pros and cons of the two?

答:
Generally, you use Web frameworks (or languages, in PHP's case) to serve and store persistent data.

What do I mean by that?

Well, Twitter is the go-to example. When you make a Tweet, that gets stored in a database somewhere. Then, when you look at the tweet again, it's loaded from the Database and sent to you.

In your case, there is no need for persistent data. Your users are going to perform mathematics and leave the website. They will not look at the calculations other users performed.

As such, your best bet is a static application made in pure JavaScript.


问:
New DDD, context-oriented, functional... approach in building business layer
We are building some business modules that must be intuitive for developers to use, so the code itself explains and forces developers to use it in certain way. This applies both for enhancing the existing features (by our developers) or reusing it (by 3rd party developers). All modules are part of big infrastructure, so they share same entities (like User), but operate on their own entities. It's Java 7 (meh).

Here are some principles that popup.

don't encapsulate business in one method, so we can have more flexibility on reusing it in different way (think functional here)

hide models completely from developers, because no matter how we tried, models always represents different representations depending on use case; plus there is some tech info in models we do not want to share with the devs. This is a step forward from making them immutable.

don't generalize; try to force the usage for the users.

It's hard to explain this, so let me try to give you an overview how this business layer should be used:

first specify the context you are working with. The context is a composite of models, that simulates the aggregate.

on the context you can specify the model action (don't have a better name at the moment): this is a DSL to change the model. user can change only what this dsl allows.

on the context then you can perform one or more commands (chainable). This time, this is DSL over the business.

finally you may invoke the renderer which purpose is to render the context into the any view class needed for the UI.

Here is how this looks like (don't be hard on class names, they are not best yet):

```<code>    PollsService polls = new PollsService();

    PollsView pollsView = polls.newPoll(new ModelAction<PollsQuestionModelBuilder>() {
        @Override
        public void execute(PollsQuestionModelBuilder question) {
            question.title(title);
            question.choices(choices);
            if (!expiration) {
                question.doesNotExpire();
            }
        }
    }).update(new Command<UpdateService>() {
        @Override
        public void execute(UpdateService updater) {
            updater.savePollQuestion();
            updater.savePollChoices();
        }
    }).render(new ModelView<PollsView, PollsQuerier, PollsQuestionAndChoiceView>() {
        @Override
        public PollsView render(PollsQuerier pollsQuerier, PollsQuestionAndChoiceView data) {
            return new PollsView(data.getPollsQuestion(), data.getPollsChoices());
        }
    });
</code>```

At one point this can be written as:

```<code>    PollsView pollsView = polls
        .newPoll(fromRequest(request))
        .update(pollsUpdate())
        .render(defaultView());
</code>```

Here is another example on update:

```<code>    PollsService polls = new PollsService();

    polls.on(questionTicket, new ModelAction<PollsQuestionModelUpdater>() {
        @Override
        public void execute(PollsQuestionModelUpdater pollsQuestionModelUpdater) {
            pollsQuestionModelUpdater.changeTitle("Why do you do this?");
        }
    }).update(new Command<UpdateService>() {
        @Override
        public void execute(UpdateService pollsQuestionUpdater) {
            pollsQuestionUpdater.savePollQuestion();
        }
    });
</code>```

So it all about above steps, in functional way (as much java7 allows it). As developer, you need to be aware of your context and all the changes you do, they must reflect the context. If you need more - create new context i.e. new aggregate. So as developer you have to think about:

what you are working with

which operation to perform on top of it

and how data should look like.

Of course, step 2 and 3 are not mandatory, i.e. you can have view without operation and vice-versa.

Did anyone used similar approach? and why?

答:
... intuitive for developers to use, so the code itself explains and forces developers to use it in certain way...

It's a myth that OO bits can be intuitive unless they are trivial.
like the most fundamental framework elements. LOB objects are the
opposite of that. They need good documentation and examples
demonstrating all the functionality you'd hope to use. If you have
unit tests, you can use some of those for examples. Think of how
much googling it takes just to consume some frameworks and these are
generally less complex than business rules.

It might not be the best idea to force devs to use it in a certain
way. Especially if you're hoping it's intuitive. Even top devs will
'intuit' all kinds of random ways to use objects if all they have to
go on is the list of types and members.

So, If you're not giving the devs your cell#, plan on spending a lot of time generating documentation!


问:
Can I minify Javascript that requires copyright notice?
I guess this is actually a legal question, but it relates to software. I'm about to include a JS plugin in a project. The comments include:

Redistributions of source code must
  retain the above copyright notice,
  this list of conditions and the
  following disclaimer.  * Redistributions in binary form must
  reproduce the above copyright notice,
  this list of conditions and the
  following disclaimer in the
  documentation and/or other materials
  provided with the distribution.

Is using this in my web site "redistribution?"

If I minify this to conserve bandwidth, I assume it will strip all comments. If the answer to #1 is yes, doesn't that imply I'm legally not allowed to minify it?

(That would stink, since I was planning to auto-minify all JS as part of the deploy process.)

答:
From my reading of the licenses, I believe that in order to be totally safe you need to include the complete license text with any distribution of the software or its derivative works (including minified JS). From the major open-source licenses:

GPLv3:

You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you ... give all recipients a copy of this License along with the Program. ...

You may convey a work based on the Program ... in the form of source code under the terms of [the above section].

MIT license:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

BSD licenses:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

It looks like this approach is not being taken by most people, however. Even the official minified Bootstrap from Twitter only contains a small copyright notice, so you'd be in violation of the MIT license if you served it to your users.


问:
What can C++ do that Python cannot?
I was reading this post: http://www.quora.com/What-are-the-advantages-of-Python-over-C++

And I am wondering the converse of this question: what can C++ do that Python cannot?

For example, in the realm of performance graphics and GUIs: I understand that C++ would be a better language for high-end game development that requires fancy graphics and great performance, but as far as making GUIs I don't understand the tangible difference between using C++ and QT, or choosing PyQt.

If someone could please make a point-by-point quick rundown like this (e.g., GUIs, high performance graphics, building command line tools, concurrency, etc), it would be very helpful for me to decide whether to choose C++ or Python for my next programming project.

答:
It is notably an implementation issue, not a language one (however the typing is different in the languages).

Pedantically, both Python & C++ are Turing-complete languages with a lot of bindings to external libraries, so every program you could write in Python could be rewritten in C++ and vice versa.

On Linux, /usr/bin/python (a.k.a. cpython) is a bytecode interpreter
but /usr/bin/g++ is a native compiler

So very often a C++ program would be faster than the equivalent python program.

notice that there are experimental python compilers (e.g. pypy) and experimental C++ interpreters.

So C++ is good for programs which need to be fast, but may accept more development time, and Python is good for programs which need to be written quickly.

You probably won't write a Unix shell or an OS kernel (or even an optimizing C++ compiler) in Python (but in C++ or C), and you probably won't write a sysadmin script or utility in C++ (but in Python).

Also, a C++ program can usually be distributed as a self-contained executable (either statically linked, or using many C++ shared libraries).

At last, C++ is statically typed, and Python is dynamically typed. This means that you would need to do whole program type analysis to compile Python to efficient code. However, some Javascript JIT implementations (e.g. v8) seems to show that dynamically typed languages might be efficiently compiled with a lot of efforts (on implementation development). But nobody paid for such an effort on a mythical Python whole-program compiler implementation.

BTW, some Common Lisp implementations (e.g. SBCL) brings you a dynamic typing and an expressivity close to Python with a performance close to C++.

Title: What can C++ do that Python cannot?


答:
Programs which require real-time number crunching (such as digital audio workstations or video players) have what I call a "computational threshold."  What that means is that the choice of programming language can matter when there is not enough hardware horsepower to satisfy the necessary computational load, if the language itself is consuming a substantial part of the CPU's clock cycles.  In other words, if your language is not efficient enough, the application may not work at all.

Consequently, the choice of language depends on whether such a threshold exists.  Naturally, you will have a better chance at writing a functional video player if you do it in a language that is highly efficient, like C++.  The tradeoff is that you will generally write more code (and it will take longer to write), but that is generally true of applications like video players anyway.

For business applications with form-based GUI's, python is often chosen over C++ because, generally speaking, python allows you to code at a higher level of abstraction and with fewer intellectual hurdles than C++ does.  Faster prototyping is thus made possible.

Of course, these are broad generalizations, and your mileage may vary due to factors like the speed of the processor, the number of available cores, the size of the installed RAM, whether you're cross-compiling the python to C, etc, making any definitive decision of which language to use for which application impossible to predict.  As will all performance-related things, measure, don't guess.

Title: What can C++ do that Python cannot?

Body:
I was reading this post: http://www.quora.com/What-are-the-advantages-of-Python-over-C++

And I am wondering the converse of this question: what can C++ do that Python cannot?

For example, in the realm of performance graphics and GUIs: I understand that C++ would be a better language for high-end game development that requires fancy graphics and great performance, but as far as making GUIs I don't understand the tangible difference between using C++ and QT, or choosing PyQt.

If someone could please make a point-by-point quick rundown like this (e.g., GUIs, high performance graphics, building command line tools, concurrency, etc), it would be very helpful for me to decide whether to choose C++ or Python for my next programming project.


问:
Unit test approaches other than test-first and test-last? And what about variants of them?
I'm wondering if there are other approaches, old or new, to writing unit tests, and how viable they are, other than the traditional and tdd unit testing approaches.

I know there is behavior-driven development, which also uses test-first, but the tests themselves can be used as specification. What others?

答:
I think there's not much more, you might be "close" to the complete picture (at least the picture that I'm aware of), so I'll give you a list of buzz-words.

no testing: Don't use!

test-last: old crap from the past, like doctors not washing their hands or accountants attempting to skip double-entry book keeping. Better than no testing, but still don't use.

test-first: The thing to do, but do it right, see TDD.

TDD: Formalized approach to test-first, based on the 3 Laws of Test-Driven Development, driving us through a Red-Green-Refactor cycle.

ATDD: Application of test-first on acceptance tests. The 3 Laws are changed from "write" to "pick", as we usually don't want to wait with writing further acceptance tests for the current acceptance tests to pass.

Transformation Priority Premise: Sequence of transformations that we should keep in mind in order to know with which tests to start and which tests to write (TDD) or pick/add (ATDD) next.

3 A's: Arrange, Act, Assert - the three major steps of a test case.

4 A's: Extension of 3 A's: Arrange, Act, Assert, Annihilate. Let's not forget cleaning up.

BDD: Mapping of the 3 A's to good names givenArrangement, whenAction, thenAssertion, ideally in a file format that's readable by non-technical humans, like Gherkin.

Single-Assert-Rule: Only one logical assertion per test-case. Manifestation of the SRP in testing.

Mocking: The substitution of components/classes/objects with by test-doubles. Used to cover the required interface towards the substituted thing on which the component/class/object under test depends. Also used to speedup tests (i.e. a fake in-memory db will be faster than a real SQL db). Also helps with design, especially decoupling, to decrease immobility and improve re-usability. Ontology: mock extends spy extends stub extends dummy extends abstract test double; fake extends abstract test double. But only use mocking when it helps you, for example, speeds up tests by replacing external dependencies. Don't mock because you can, only mock when you actually need to.

Integration testing: Testing the combined interaction between components/classes/objects. Currently the field where the industry is lacking most, as it seems nobody knows yet how to get this part right. If you want to get famous, fix this topic.

And finally, what are tests? Tests are the actual requirements specification. What ppl used to call requirements specification actually is not a requirements specification, it's a requirements model (simplified and incomplete). When we're releasing software, we're not looking at the code on one screen and the requirements document on the other screen, going through it like a checklist - instead we're running tests. Therefore, the tests are the true requirements specification.

As with all guidelines and laws, use judgement when to not follow them. You don't want to tell your customers that their credit cards were stolen because you first had to write a test for that SQL injection bug that one of your clients found. But you also don't want to tell your clients that their credit cards were stolen because after fixing that SQL injection bug you didn't write tests to verify the fix and look for more bugs like that.


问:
How much business logic should be allowed to exist in the controller layer?
Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?

答:
As little as possible. Preferably none.

The controller should be concerned with accepting the request, asking the correct domain service to process the request, and handing off the response to the correct view.

In that process, all of the "business logic" should exist in the domain services.

If you have functionality that takes domain objects and creates viewmodels out of them, then that can reasonably coexist with the controller. But that should be code that exists only for the sake of the corresponding views. If there is a business-level rule about data sanitization, that should exist in your domain/service level (with the approriate unit tests).


问:
Repository Pattern: Doctrine2 vs Microsoft Entity Framework?
I have been using Symfony2 with Doctrine2 for some years. I have recently started using Microsoft's Entity Framework with MVC5. From my Symfony2 experience I understand that a repository's job is only to retrieve and return objects, no additional operations like Saving. Now every examples I have seen for EF has a method Save/Update as part of the repository.

For symfony I have been creating manager classes as follows:

```<code>interface IManager
{
    function getClassName() ;
    IRepository getRepository() ;
    function Save(object);
    function Update();
}
</code>```

So I pass around the manager, if I need to retrieve objects I call the repository directly. If I need to save I call the manager's save method.

Is a repository supposed to support save/update? What do you think of my IManager class, should I also use it for EF?

答:
I think what confuses you about EF is the database context. It allows you to query objects like a Repository and save changes in persistence like a Unit of Work.

You have a lot of work done with EF database context. All you have to do is segregate the responsibilities by creating specific repositories and a unit of work that share the database context and pesists all changes in presistence with a single save call.

Check this link about create Repositories and UoW in EF. It is clear and easy to understand.


答:
Python is a dynamically-typed language. This has two important consequences:

The compiler is unable to reject certain kinds of logical error at compile time which would be caught by a C++ compiler

Because the types of some (even most) variables cannot be determined at compile time, operations on those variables must be implemented by dynamically dispatching a method call (a fairly slow operation) whereas C++ compilers are often able to generate inline code (which has no overhead). C++ is therefore an inherently faster
language.

The former of these is actually surprisingly useful. See for example the Boost Units library, which allows scientific and engineering code to be written in a way that allows the compiler to statically check that the calculations have logically consistent unit usage at compile time, with no runtime overhead. This would be impossible in Python.

Python also has very poor support for multithreading. Its language design requires certain operations (for instance modifications to lists) to complete atomically, which has lead to the most common implementation using a global lock to prevent two threads executing Python code at the same time (although if one thread calls native code the other will be allowed to procede), because the overhead of locking and unlocking individual objects made single threaded performance terrible.

C++, on the other hand, leaves the job of ensuring code is thread-safe up to the developer, which allows for efficient multithreading.

C++ also gives developers much more control over memory management, allowing for example generic containers that allocate user-specified object types inside their structures (leading to lower overhead and better locality of reference than is possible with Python), allocating objects in specified memory regions (e.g. so that multiple objects can be deleted in a single operation, or to allocate them in a memory-mapped file) or using developer-supplied custom allocators.

C++ is also loosely typed, which means you can use an area of memory for one type of data, and then change to treating it as containing another type. While operations of this type are dangerous (and the language specification states that programs that do this have "undefined behavior"), if you know what you're doing you can use this to implement dynamic loading of code modules, runtime native code generation, direct manipulation of file structures without individually extracting fields as you would have to in Python, and a wide variety of other uses. This is why operating systems can be implemented in C++ and not in Python.

Title: What can C++ do that Python cannot?


问:
NLP - Queries using semantic wildcards in full text searching, maybe with Lucene?
Let's say I have a big corpus (for example in english or an arbitrary language), and I want to perform some semantic search on it. For example I have the query:

"Be careful: [art] armada of [sg] is coming to [do sg]!"

And the corpus contains the following sentence:

"Be careful: an armada of alien ships is coming to destroy our planet!"

It can be seen that my query string could contain "semantic placeholders", such as:

[art] - some placeholder for articles (for example a / an in English)
[sg], [do sg] - some placeholders for NPs and VPs (subjects and predicates)
I would like to develop a library which would be capable to handle these queries efficiently. I suspect that some kind of POS-tagging would be necessary for parsing the text, but because I don't want to fully reimplement an already existing full-text search engine to make it work, I'm considering that how could I integrate this behaviour into a search engine like Lucene?

I know there are SpanQueries which could behave similarly in some cases, but as I can see, Lucene doesn't do any semantic stuff with stored texts.

It is possible to implement a behavior like this? Or do I have to write an own search engine?

答: I would consider using a standard keyword search with the nouns and verbs from your query as a way of generating a shortlist of possible results and then using an NLP parser (e.g. Stanford Core NLP) to preform a more detailed analysis on each contender in order to filter them to only exact matches. Assuming a reasonable corpus size and that the queries use words that don't generate a large number of matches, this should be adequate.</p>


答:
Controllers should be very light on domain logic.

Controllers should delegate tasks such as retrieving a record from the data store by way of an abstracted service/repository layer and passing data back into the data store by the same (or related) service. As for the mechanics and finer-workings between those operations, usually they belong somewhere other than the controller.

I often find myself adding small data sanitation methods to my controllers which save data back to the store and although this is an effective solution, it doesn't fit well with the intended role of the controller. Ideally, anything that will be modifying, validating, or parsing your model should occur very near to- if not within- the model itself. For example, if you need to 'clean' a model object before you store it, consider having a SanitizeInputs() method on the model or as part of the service which handles storing the model.

Title: How much business logic should be allowed to exist in the controller layer?

Body:
Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?


问:
Whether Methods could be defined in Constructors in Java?
I am learning to program in Java and have run into a situation I don't understand.

I have this code

```<code>import java.io.*;
class temp
{
  temp()
  {
    Finish f=new Finish();
    f.end();
  }

  public static void main(String args[])
  {
    System.out.println("STARTING JAVA PROGRAM");
  }
}

class Finish
{
  public void end()
  {
    System.out.println("ENDING JAVA PROGRAM");
  }
}
</code>```

I expected the code to print

```<code>STARTING JAVA PROGRAM
ENDING JAVA PROGRAM
</code>```

but I am only getting

```<code>STARTING JAVA PROGRAM
</code>```

Is it possible to call a method from a constructor?

答:
You need to create an object of temp in the main to acheive what you want.

To get the result that you want add the below in your main:

```<code>   public static void main(String args[])
      {
        System.out.println("STARTING JAVA PROGRAM");
        temp t = new temp(); //New temp object
      }
</code>```

Body:
You need to create an object of temp in the main to acheive what you want.

To get the result that you want add the below in your main:

   public static void main(String args[])
      {
        System.out.println("STARTING JAVA PROGRAM");
        temp t = new temp(); //New temp object
      }


答:
I was going to say Database First since I have a lot of experience with large projects and you really need a solid data model if you have many developers working in parallel.

But then I though about it a little more and I realized that what we were really doing on the more successful large projects was "requirements first".

A good well specified set of business requirements, leads on to a good set of functional requirements. If you have a good set of functional requirements then the data model and module specs just fall in to place without much effort.

Title: Code First vs. Database First


问:
Testing vs Don't Repeat Yourself (DRY)
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?

答: If you think your test code is too similar to your implementation code, this may be an indication that you are over-using a mocking framework. Mock-based testing at too low a level can end up with the test setup looking a lot like the method being tested. Try to write higher level tests that are less likely to break if you change your implementation (I know this can be hard, but if you can manage it you will have a more useful test suite as a result ).</p>

Title: Testing vs Don't Repeat Yourself (DRY)