问:
Is it OK to have multiple asserts in a single unit test?
In the comment to this great post, Roy Osherove mentioned the OAPT project that is designed to run each assert in a single test.

The following is written on the project's home page:

Proper unit tests should fail for
  exactly one reason, that’s why you
  should be using one assert per unit
  test.

And, also, Roy wrote in comments:

My guideline is usually that you test
  one logical CONCEPT per test. you can
  have multiple asserts on the same
  object. they will usually be the same concept being tested.

I think that, there are some cases where multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really needed.

答:
If you have multiple asserts in a single test function, I expect them to be directly relevant to the test you are conducting. For example,

@Test
test_Is_Date_segments_correct {

   // It is okay if you have multiple asserts checking dd, mm, yyyy, hh, mm, ss, etc.
   // But you would not have any assert statement checking if it is string or number,
   // that is a different test and may be with multiple or single assert statement.
}
```

Having a lot of tests (even when you feel that it is probably an overkill) is not a bad thing. You can argue that having the vital and most essential tests is more important. SO, when you are asserting, make sure your assert statements are correctly placed rather than worrying about multiple asserts too much. If you need more than one, use more than one.

ContentLicense: CC BY-SA 4.0

Body:
If you have multiple asserts in a single test function, I expect them to be directly relevant to the test you are conducting. For example,

@Test
test_Is_Date_segments_correct {

   // It is okay if you have multiple asserts checking dd, mm, yyyy, hh, mm, ss, etc.
   // But you would not have any assert statement checking if it is string or number,
   // that is a different test and may be with multiple or single assert statement.
}

Having a lot of tests (even when you feel that it is probably an overkill) is not a bad thing. You can argue that having the vital and most essential tests is more important. SO, when you are asserting, make sure your assert statements are correctly placed rather than worrying about multiple asserts too much. If you need more than one, use more than one.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Spoken and Written language.

They are currently one of the most efficient algorithm to transfer knowledge from one thing to another. Without language, civil society could not exist, and information could not be conveyed.

ContentLicense: CC BY-SA 2.5


问:
Finding duplicate files?
I am going to be developing a program that detects duplicate files and I was wondering what the best/fastest method would be to do this? I am more interested in what the best hash algorithm would be to do this? For example, I was thinking of having it get the hash of each files contents and then group the hashes that are the same. Also, should there be a limit set for what the maximum file size can be or is there a hash that is suitable for large files?</p>

答:
The fastest way is just to compare hash code of files having same size.

This is the idea of of this answer on SO (see the second command line and its explanations).

There is no security issue while detecting duplicated files, therefore I would recommend a fast hashing code. For instance the project ccache uses MD4:

ccache uses MD4, a very fast cryptographic hash algorithm, for the hashing.
  (MD4 is nowadays too weak to be useful in cryptographic contexts,
  but it should be safe enough to be used to identify recompilations.)

If two files have same size and same hash code, they are probably equal. But there will still be a little chance these two files are different (except if file size is less than hash code size).

As you imply in your question, false positive can happen more frequently as the file size is larger.

There are two options to fix the large files issue:

Use a second hash code for large file (e.g. MD4 and MD5).

Use a dynamic-length hash code

The limit to consider a file as enough large to require a second check depends on how critical is your application.

Finally, the safest way to proceed is:

Detect files having same size

If same size => compare their (already computed) hash codes

If same size and same hash code => compare the full content

ContentLicense: CC BY-SA 3.0

Title: Finding duplicate files?


问:
Is it a good practice to wrap all primitives and Strings?
According to Jeff Bay's Essay on Object Callisthenics,

One of the practices is set to be "Wrap all primitives and Strings"

Can anyone elaborate on this ?

In languages where we already have wrappers for primitives like C# and Java.
and In languages where Collections can have generics where you are sure of what type goes into the collection, do we need to wrap string's inside their own classes ?

Does it have any other advantage ?

答:
Imagine a situation where you have a primative type:

```<code>int distanceInKm;
</code>```

This is in many, many places throughout your code.

One day Mr Client comes to you and says, "We'd like everything displayed in miles now, please."

You now have to change everywhere where distanceInKm is used.

Now imagine an alternative situation where you have you own type:

```<code>class Distance
{
    private int _distanceInKm;

    public string DescriptionOfDistance()
    {
        return ...;
    }
}
</code>```

Now you only need to change one place to make everything display in miles.

As @DanielFisherlennybacon has mentioned in the comments, you need to be pragmatic about when to apply any 'rules' of programming.  In this specific case, it is worth noting that Object Calisthenics is an exercise to stretch your programming muscles. Marathon runners do sprints in training to improve their basic speed; it doesn't mean they have to sprint for the entire race.

Body:
Imagine a situation where you have a primative type:

int distanceInKm;

This is in many, many places throughout your code.

One day Mr Client comes to you and says, "We'd like everything displayed in miles now, please."

You now have to change everywhere where distanceInKm is used.

Now imagine an alternative situation where you have you own type:

class Distance
{
    private int _distanceInKm;

    public string DescriptionOfDistance()
    {
        return ...;
    }
}

Now you only need to change one place to make everything display in miles.

As @DanielFisherlennybacon has mentioned in the comments, you need to be pragmatic about when to apply any 'rules' of programming.  In this specific case, it is worth noting that Object Calisthenics is an exercise to stretch your programming muscles. Marathon runners do sprints in training to improve their basic speed; it doesn't mean they have to sprint for the entire race.


问:
Why do certain sites don't allow Back / Forward / Refresh?
This has been a cause of frustration for me on many sites like IRCTC, Online Banking sites which wont allow Back, forward or refresh. If you do you would be logged out and you have to login again. What I don't understand is what concern had there been in their mind to have such terrible "feature".</p>

答:
Modern web applications (notably those written in MVC or similar) have no need for such navigation methods as the process flow is driven by the on-screen assets.

Much of the interface of modern browsers is however still very much geared towards Web 1.0 style web sites where the content is static and there isn't so much need for maintaining state.

Even knowing all the above is true, I agree that it is something of a pain to have such features taken away when they're now so natural to us.

I'd take a punt that future frameworks will have some way of hooking on-screen assets into browser back/forward/refresh buttons in a similar way to winforms apps where buttons could be assigned to the Enter and Escape keys.

An alternative could be for browsers to (somehow) detect the underlying framework and hide buttons not supported by the web application interface.


答:
In fact, the article repeatedly states that it is not best practice to blindly wrap all primitives:

The Challenge
  Do a simple project using far stricter coding standards than you’ve ever used in your life.  Below, you’ll find 12 “rules of thumb” that will help push your code into good object-oriented shape.

By suspending disbelief, and rigidly applying these rules on a small, 1000 line project, you’ll start to see a significantly different approach to designing software.  Once you’ve written 1000 lines of code, the exercise is done, and you can relax and go back to using these 12 rules as guidelines.

This is a hard exercise, especially because many of these rules are not universally applicable.   The fact is, sometimes classes are a little more than 50 lines. But there’s great value in thinking about what would have to happen to move those responsibilities into real, first-class-objects of their own.  It’s developing this type of thinking that’s the real value of the exercise.  So stretch the limits of what you imagine is possible, and see whether you start thinking about your code in a new way.

Why would you post a question asking to explain an article you haven't read?

Here is what it says:

Rule 3: Wrap all primitives and Strings
  In the Java language, int is a primitive, not a real object, so it obeys different rules than objects.  It is used with a syntax that isn’t object-oriented. More importantly, an int on its own is just a scalar, so it has no meaning.   When a method takes an int as a parameter, the method name needs to do all of the work of expressing the intent.  If the same method takes an Hour as a parameter, it’s much easier to see what’s going on.  Small objects like this can make programs more maintainable, since it isn’t possible to pass a Year to a method that takes an Hour parameter. With a primitive variable the compiler can’t help you write semantically correct programs. With an object, even a small one, you are giving both the compiler and the programmer additional info about what the value is and why it is being used.

Small objects like Hour or Money also give us an obvious place to put behavior that would otherwise have been littered around other classes. This becomes especially true when you apply the Rule X, and only the small object can access the value.

Title: Is it a good practice to wrap all primitives and Strings?

Body:
According to Jeff Bay's Essay on Object Callisthenics,

One of the practices is set to be "Wrap all primitives and Strings"

Can anyone elaborate on this ?

In languages where we already have wrappers for primitives like C# and Java.
and In languages where Collections can have generics where you are sure of what type goes into the collection, do we need to wrap string's inside their own classes ?

Does it have any other advantage ?


问:
How do you deal with over-the-head APIs/technology
I guess most people have been in this situation.

The initial project planning begins. The requirements are outlined. After architectural review and sorting through APIs/Frameworks the fitting technology is picked. The development starts.

And then it starts. As soon as you need to do some supposedly simple supporting things, framework/API start to backfire, and instead of doing any work you end up fighting against the technology. The research time skyrockets, forums are silent, nothing seems to be done, and even when you get something to work, you're not really sure it's done right.

How do you manage in these situations? Do you go for hacks, do you research further, what do you say to management?

答:
Prototype, Prototype, Prototype!!

If your team is not familiar with a particular framework then prototype something in it to evaluate where the pain points are.

Matt Raible (Java Web framework comparator guy) suggests working with a framework for one week if possible.

Prototyping includes investigating the community support behind a framework and other factors


问:
Decorator not calling the decorated instance - alternative design needed
Assume I have a simple interface for translating text (sample code in C#):

```<code>public interface ITranslationService
{
    string GetTranslation(string key, CultureInfo targetLanguage);
    // some other methods...
}
</code>```

A first simple implementation of this interface already exists and simply goes to the database for every method call. Assuming a UI that is being translated at start up this results in one database call per control.

To improve this, I want to add the following behavior:

As soon as a request for one language comes in, fetch all translations from this language and cache them. All translation requests are served from the cache.

I thought about implementing this new behavior as a decorator, because all other methods of that interface implemented by the decorater would simple delegate to the decorated instance.

However, the implementation of GetTranslation wouldn't use GetTranslation of the decorated instance at all to get all translations of a certain language. It would fire its own query against the database.

This breaks the decorator pattern, because every functionality provided by the decorated instance is simply skipped. This becomes a real problem if there are other decorators involved.

My understanding is that a Decorator should be additive. In this case however, the decorator is replacing the behavior of the decorated instance.

I can't really think of a nice solution for this - how would you solve it? Everything is allowed, even a complete re-design of ITranslationService itself.

答:
The feasibility of a lot of the possible options depends on how closed the current implementation of the ITranslationService interface is.

If the current implementation is completely closed (final class, no modifications will be accepted), then your only real options are

Create a separate, independent implementation of the interface

use your current 'decorator' approach. This can be extended to call the GetTranslation method of the decorated object if the translation could not be found in the cache.

If the current implementation allows sub-classes, you could provide your cached version as a derived class

If the current implementation is still open for modification, you could change the GetTranslation implementation to use the Strategy pattern, where one strategy always goes to the database and the other uses caching.


问:
How to serialize and deserialize lambda expression in F#?
I serialized lambda expressions in C# before. Now I wanna use F# instead of C# for serialization and deserialization.

I heard F# is better in this area. Is it true?
How can I do that with F#?

I’d appreciate even if you just suggested a correlated link.

答:
I heard F# is act better in this area. Is it true?

Yes, the F# Expr type is marked as [Serializable], so you can use for example binary serialization with it. On the other hand the C# (and VB) Expression is not [Serializable], so to serialize it, you would either need to write quite a lot of code yourself, or use a library for that.


问:
What is the difference between Enterprise Java vs Core Java?
I have some experience in programming in Java but wondering if someone could explain what is the difference between Enterprise Java vs Core Java?

Someone asked me a question on whether I use core-Java or Enterprise Java. Now I have to ask is there such thing as core-java?

答:
What you are calling Core Java is actually known as Java Standard Edition (SE) and the Enterprise Java is Java Enterprise Edition (EE).

Java SE is the base Java API that makes up 99.9% of the Java functionality that you know and love, that is, unless you're an enterprise developer creating java apps for large scale applications (think server farms).

Java EE is the API built on top of the SE API to provide the tools necessary to do large scale projects more easily.

Long story short, you probably want to be using the SE edition.


答:
Keep the ITranslationService, but instead of implementing calls directly against to the cache or the database, send to an object IRepository that uses a list of preferred IProviders which provide access to the underlying persistence mechanisms.

The first, or generally "preferred provider", is a CacheProvider. The second, is your primary LocalDatabaseTranslationProvider.  Conceivable, there could be a third or more providers.  The last provider in the list is least preferred, but a reliable fallback provider.  For example one might take the form of a 3rd party translation service.  It would be implemented as an object proxy service like RemotePartnerTranslationProvider.

Each provider will implement a common interface that allows the strategy to differ, so no matter which provider is chosen and no matter how each provides for reads and writes, the repository acts on each and receives from each in the same way.  The repository is responsible for providing coordination and conflict resolution amongst the providers when necessary.

Among other concerns, you might look at an observable interface for each provider too, for when you need to propagate/push state/signal amongst all/most providers from the repository, for instance to properly close or dispose of them when cleaning up/shutting down.

Title: Decorator not calling the decorated instance - alternative design needed

Body:
Assume I have a simple interface for translating text (sample code in C#):

```<code>public interface ITranslationService
{
    string GetTranslation(string key, CultureInfo targetLanguage);
    // some other methods...
}
</code>```

A first simple implementation of this interface already exists and simply goes to the database for every method call. Assuming a UI that is being translated at start up this results in one database call per control.

To improve this, I want to add the following behavior:

As soon as a request for one language comes in, fetch all translations from this language and cache them. All translation requests are served from the cache.

I thought about implementing this new behavior as a decorator, because all other methods of that interface implemented by the decorater would simple delegate to the decorated instance.

However, the implementation of GetTranslation wouldn't use GetTranslation of the decorated instance at all to get all translations of a certain language. It would fire its own query against the database.

This breaks the decorator pattern, because every functionality provided by the decorated instance is simply skipped. This becomes a real problem if there are other decorators involved.

My understanding is that a Decorator should be additive. In this case however, the decorator is replacing the behavior of the decorated instance.

I can't really think of a nice solution for this - how would you solve it? Everything is allowed, even a complete re-design of ITranslationService itself.


问:
General questions regarding open-source licensing
I'm looking to release an open-source iOS software project but I'm very new to the licensing side of the things. While I'm aware that the majority of answers here will not lawyers, I'd appreciate it if anyone could steer me in the right direction.

With the exception of the following requirements I'm happy for developers to largely do whatever they want with the projects source code. I'm not interested in any copyleft licensing schemes, and while I'd like to encourage attribution in derivative works it is not required.

As such, my requirements are as follows:

Original source can be distributed and re-distributed (verbatim) both
commercially and non-commercially as long as the original copyright
information, website link and license is maintained.

I wish to retain rights to any of the multi-media distributed as part
of the project (sound effects, graphics, logo marks, etc). Such
assets will be included to allow other developers to easily execute
the project, but cannot be re-distributed in any manner.

I wish to retain rights to the applications name and branding.

Futher to selecting an applicable license, I have the following questions:

The project makes use of a number of third-party libraries (all licensed under variants of the MIT license). I've included individual licenses within the source (and application) and believe I've met all requirements expressed in these licenses, but is there anything else that needs to be done before distributing them as part of my open-source project?

Also included in my project is a single proprietary, close-sourced library that's used to power a small part of the application. I'm obviously unable to include this in the source release, but what's the best way of handling this? Should I simply weak-link the project and exclude it entirely from the Git project?

答:
To get the easy stuff out of the way, the best way to protect your application's name and logos is by registering those as trademarks. This is irrespective of the licence you use for the source code.

You can release your artwork and multi-media files under a different license than your source code, but there is a possibility that for that separation to be effective, you need to distribute them in different packages. This is something you definitely need to discuss with a lawyer.

Then the hard question: what license to use for your source code.
 The fact that you depend on a closed-source library makes it impossible to use the GPL license, because that license explicitly requires that the GPL applies to every piece that makes up your application.

The MIT or BSD licenses might be applicable to your software, but you should expect a lot of flack. People expect that when the download the source of an open-source project, then they are able to build the project by themselves. But for your application, that would not be the case due to the dependency on the closed-source library. Additionally, the MIT and BSD licenses allow re-licensing of derived software, which seems to be contrary to your first bullet.


答:
Core Java is not an official name in Java platform (it is the name of a book); also Enterprise Java is not an official name.

However these two terms tend to refer to two distinct parts of Java:

Core Java usually refers to Java SE which consists of the Java Language, the JVM and JDK (which itself contains the compiler some tools and a pretty large library). Core Java is used for general purpose programming and almost anything written in Java is based on the Core Java.

Enterprise Java refers to Java applications written for enterprises; the leading technology here is Java EE which consists of a set of APIs (EJB, JMS, JPA, JTA, JSF etc.) and the application servers (Glassfish, Tomcat, JBoss/WildFly etc.) which implement these APIs (or a part of them). But Enterprise Java is not strictly restricted to Java EE; someone using Spring Framework for example is still an Enterprise Java programmer.

Title: What is the difference between Enterprise Java vs Core Java?

Body:
I have some experience in programming in Java but wondering if someone could explain what is the difference between Enterprise Java vs Core Java?

Someone asked me a question on whether I use core-Java or Enterprise Java. Now I have to ask is there such thing as core-java?


问:
What is the best PHP ORM library?
I want to build a PHP web application, but always faces the problem that I need to connect to database and deal with related objects. So I tried codeigniter and it uses a special way to connect to database named Active Record and I've known that its an ORM technique and there are lot of ORM libraries out there.

What is the best, the easiest and the fastest of them?

答:
Doctrine and Propel are two popular ORMs.  Personally I only have experience with Doctrine and have no complaints.

You should also read through the answers to this question on StackOverflow.

Title: What is the best PHP ORM library?


问:
Using Sql Server Change Data Capture with a frequently changing schema
We are looking into enabling Sql Server Change Data Capture for a new subsystem we are building.

It's not really because we need it, but we are being pushed for having a complete history traceability, and CDC would nicely solve this requirement with minimum effort on our parts.

We are following an agile development process, which in this case means that we frequently make changes to the database schema, e.g. adding new columns, moving data to other columns, etc.

We did a small test where we created a table, enabled CDC for that table, and then added a new column to the table. Changes to the new column is not registered in the CDC table.

Is there a mechanism to update the CDC table to the new schema, and are there any best practices to how you deal with captured data when migrating the database schema?

答: Simple-Talk has a great article about change data capture and a very through guide on CDC as well as the MSDN documentation explains the various methods depending on the requirements. But they both can help you with your specific requirements. </p>


问:
Why does DataContractJsonSerializer not include generic like JavaScriptSerializer?
So the JavaScriptSerializer was deprecated in favor of the DataContractJsonSerializer.

```<code>var client = new WebClient();
var json = await client.DownloadStringTaskAsync(url); // http://example.com/api/people/1

// Deprecated, but clean looking and generally fits in nicely with
// other code in my app domain that makes use of generics
var serializer = new JavaScriptSerializer();
Person p = serializer.Deserialize<Person>(json);

// Now have to make use of ugly typeof to get the Type when I
// already know the Type at compile type. Why no Generic type T?
var serializer = new DataContractJsonSerializer(typeof(Person));
Person p = serializer.ReadObject(json) as Person;
</code>```

The JavaScriptSerializer is nice and allows you to deserialize using a type of T generic in the function name. Understandably, it's been deprecated for good reason, with the DataContractJsonSerializer, you can decorate your Type to be deserialized with various things so it isn't so brittle like the JavaScriptSerializer, for example

```<code>[DataMember(name = "personName")]
public string Name { get; set; }
</code>```

Is there a particular reason why they decided to only allow users to pass in the Type?

```<code>Type type = typeof(Person);

var serializer = new DataContractJsonSerializer(type);
Person p = serializer.ReadObject(json) as Person;
</code>```

Why not this?

```<code>var serializer = new DataContractJsonSerializer();
Person p = serializer.ReadObject<Person>(json);
</code>```

They can still use reflection with the DataContract decorated attributes based on the T that I've specified on the .ReadObject<T>(json)

答:
JavaScriptSerializer does not seem to be deprecated, based on current MSDN documentation. It was un-obsoleted with .NET 3 SP1 (see the comment from Microsoft). Examples of it's usage also appears in current Microsoft Learning publications.

I'm not sure then if the DataContractJsonSerializer approach is necessarily superior than the other. But of course, some benchmarks might be interesting :)


问:
Dev Server vs Local Development
On the past 2 projects I've worked, teams prefer a local development environment over a development server.

The one project lead stated that local was better since it didn't require an internet connection. But, this seems assumed when developing.

Which is usually better?

答:
Your development environment really depends on how your IT Department/Company is organised and run. In general though the closed your development environment matches that of your production environment the better.

If for instance you are developing stand alone desktop applications that require no internet access then of course a local development environment is acceptable.

On the other hand if you are developing a desktop application that requires communication with a remote server/database etc and you do not have network connection to simulate this in work you may find additional bugs in production due to network latency, security issues.

If you are developing an Internet/Cloud application then while you may need the internet to develop the application you will need access to test and verify.

Btw you don't need an Internet connection to have a development server just a local network connection.

Title: Dev Server vs Local Development


问:
Is it correct to fix bugs without adding new features when releasing software for system testing?
This question is to experienced testers or test leads.
This is a scenario from a software project:

Say the dev team have completed the first iteration of 10 features and released it to system testing. The test team has created test cases for these 10 features and estimated 5 days for testing. The dev team of course cannot sit idle for 5 days and they start creating 10 new features for next iteration. During this time the test team found defects and raised some bugs. The bugs are prioritised and some of them have to be fixed before next iteration. The catch is that they would not accept the new release with any new features or changes to existing features until all those bugs fixed. The test team says that's how can we guarantee a stable release for testing if we also introduce new features along with the bug fix. They also cannot do regression tests of all their test cases each iteration. Apparently this is proper testing process according to ISQTB.

This means the dev team has to create a branch of code solely for bug fixing and another branch where they continue development. There is more merging overhead specially with refactoring and architectural changes.

Can you agree if this is a common testing principle. Is the test team's concern valid. Have you encountered this in practice in your project.

答:
If the testers are attempting to get a defined release to a customer, that is not expecting the new features then their request is reasonable, justified and you should bend over backwards to deliver it.

If this is just to assist in their "processes" during normal development phases, and ensuring that the bug list is not running out of control then without making an issue of it, ask the head of testing if this restraint can be relaxed a little until we get closer to the release point.

Consider changing your source control system to a distributed product.  This will make it much easier to deliver such a release.


答:
The benefits of running local is that you can work without influencing/hindering others. The benefits of a central dev server is that you can test how your changes influence and interact with the changes others are making as they are being made.

Ideally you want to have both. Develop and run your unit tests locally so you can isolate your changes until you're comfortable with them, then integrate them on the team server so you can check integration of changes before things go to the test systems.

Another benefit of a local server on your laptop is that you can work remote where you have no access to the company network and thus can't access the dev server.

Title: Dev Server vs Local Development

Body:
On the past 2 projects I've worked, teams prefer a local development environment over a development server.

The one project lead stated that local was better since it didn't require an internet connection. But, this seems assumed when developing.

Which is usually better?


问:
Is acoustic fingerprinting too broad for one audio file only?
We were looking for some topics related to audio analysis and found acoustic fingerprinting. As it is, it seems like the most famous application for it is for identification of music.

Enter our manager, who requested us to research and possible find an algorithm or existing code that we can use for this very simple approach (like it's easy, source codes don't show up like mushrooms):

Always-on app for listening

Compare the audio patterns to a single audio file (assume sound is a simple beep or beep-beep)

If sound is detected, send notification to server

With a flow this simple, do you think acoustic fingerprinting is a broad approach to use? Should we stop and take another approach? Where to best start?

We haven't started anything yet (on the development side) on this regard, so I want to get other opinion if this is pursuit is worth it or moot.

答:
If the audio you are searching for really is just a simple beep, you don't want to go to the trouble of using acoustic fingerprinting, there's a much simpler algorithm designed for exactly that purpose, its called the Goertzel Algorithm
. You most likely can find a library that implements the algorithm in your language of choice. This is the algorithm used by automated telephone systems to detect what digit on the phone keypad is pressed by listening to the beeps at various frequencies being sent.

For the algorithm to work best your beep should be "simple" in that it is either a sine wave at a single known frequency (or even better a "Dual Tone" beep with two sine waves at separate known frequencies which is what telephone keypad tones are). The algorithm will check a set of samples and determine if the frequencies are present above a preset loudness threshold. If they do, you will want to run an additional test to make sure that there isn't a lot of extraneous noise going on at the time since, for example, white noise will excite all frequencies.


答:
A lot depends on how you deliver your projects. Some arguments to have a central dev environment could be:

Quality Control: how far do you want to go on testing? Local dev environments have constraints on testing capabilities. Virtual test environments are better suited for load testing and automated system tests.

Central infrastructure can help on shortening your dev-test-deliver cycle. Thus implementing a continuous delivery.

Extra benefits from central development server can be source control, task management, central builds,..

Title: Dev Server vs Local Development


问:
Query something and return the reason if nothing has been found
Assume I have a Query - as in CQS that is supposed to return a single value.

Let's assume that the case that no value is found is not exceptional, so no exception will be thrown in this case. Instead, null is returned.

However, if no value has been found, I need to act according to the reason why no value has been found.

Assuming that the Query knows the reason, how would I communicate it to the caller of the Query?

A simple solution would be not return the value directly but a container object that contains the value and the reason:

```<code>public class QueryResult
{
    public TValue Value { get; private set; }
    public TReason ReasonForNoValue { get; private set; }
}
</code>```

But that feels clumsy, because if a value is found, ReasonForNoValue makes no sense and if no value has been found, Value makes no sense.

What other options do I have to communicate the reason? What do you think of one event per reason?

For reference: This is going to be implemented in C#.

答:
What other options do I have to communicate the reason?

If your result is a string, you can have the reason be there with some signature that indicates it's a bad result.

If your result is a number, you can have negative (or other bad values) be some error code.

You can have a separate query that users can call (if they so desire) to determine cause of null.

None of these seem clear cut better than your result/error object except perhaps the last depending on your usage.

What do you think of one event per reason?

I think that events are a largely terrible way to dispatch logic and a fairly rigid/coupled way of signaling a querying error which depends specifically on your data storage/format and would need to change if the query changes to cause different kinds of failure.


答:
I like the solution you propose.  You may later wish to refactor ReasonForNoValue into something more generic, but at least you have the structure to do so if necessary.

Advantages to your approach:

It's expandable if you ever need to return more data or metadata

It separates the actual data from the metadata

There are no magic numbers

It's easy to parse.

Telastyn suggested another good approach - just return a single TValue and support a new server call WhyWasThisNull()

Title: Query something and return the reason if nothing has been found

Body:
Assume I have a Query - as in CQS that is supposed to return a single value.

Let's assume that the case that no value is found is not exceptional, so no exception will be thrown in this case. Instead, null is returned.

However, if no value has been found, I need to act according to the reason why no value has been found.

Assuming that the Query knows the reason, how would I communicate it to the caller of the Query?

A simple solution would be not return the value directly but a container object that contains the value and the reason:

```<code>public class QueryResult
{
    public TValue Value { get; private set; }
    public TReason ReasonForNoValue { get; private set; }
}
</code>```

But that feels clumsy, because if a value is found, ReasonForNoValue makes no sense and if no value has been found, Value makes no sense.

What other options do I have to communicate the reason? What do you think of one event per reason?

For reference: This is going to be implemented in C#.


问:
Design pattern for logging changes in parent/child objects saved to database
I’ve got a 2 database tables in parent/child relationship as one-many.

I’ve got three classes representing the data in these two tables:

```<code>Parent Class
{
    Public int ID {get; set;}
    .. other properties
}

Child Class
{
    Public int ID {get;set;}
    Public int ParentID {get; set;}
    .. other properties
}

TogetherClass
{
    Public Parent Parent;
    Public List<Child> ChildList;
}
</code>```

Lastly I’ve got  a client and server application – I’m in control of both ends so can make changes to both programs as I need to.

Client  makes a request for ParentID and receives a Together Class for the matching parent, and all of the child records.

The client app may make changes to the children – add new children, remove or modify existing ones.  Client app then sends the Together Class back to the server app.

Server app needs to update the parent and child records in the database.

In addition I would like to be able to log the changes – I’m doing this by having 2 separate tables one for Parent, one for child; each containing the same columns as the original plus date time modified, by whom and a list of the changes.

I’m unsure as to the best approach to detect the changes in records – new records, records to be deleted, records with no fields changed, records with some fields changed.

I figure I need to read the parent & children records and compare those to the ones in the Together Class.

Strategy A:

If Together class’s child record has an ID of say 0, that indicates a new record; insert.
Any deleted child records are no longer in the Together Class; see if any of the comparison child records are not found in the Together class and delete if not found (Compare using ID).

Check each child record for changes and if changed log.

Strategy B:
Make a new Updated TogetherClass

```<code>UpdatedClass
{
    Public Parent Parent {get; set}
    Public List<Child> ListNewChild {get;set;}
    Public List<Child> DeletedChild {get;set;}
    Public List<Child> ExistingChild {get;set;} // used for no changes and modified rows
}
</code>```

And then process as per the list.

The reason why I’m asking for ideas is that both of these solutions don’t seem optimal to me and I suspect this problem has been solved already – some kind of design pattern ?

I am aware of one potential problem in this general approach – that where Client App A requests a record; App B requests same record; A then saves changes; B then saves changes which may overwrite changes A made.  This is a separate locking issue which I’ll raise a separate question for if I’ve got trouble implementing.

The actual implementation is c#, SQL Server and WCF between client and server - sharing a library containing the class implementations.

Apologies if this is a duplicate post – I tried searching various terms without finding a match though.

Update based on comments from svick and TimG:

To track change would the base class be something like:

```<code>public class ChangedRowBase
    {
        public enum StatusState
        {
        New, Unchanged, Updated, Deleted
    };

    protected StatusState _Status;

    public StatusState Status
    {
        get
        {
            return _Status;
        }
    }

    public void SetUnchanged()
    {
        _Status = StatusState.Unchanged;
    }

    public void SetDeleted()
    {
        _Status = StatusState.Deleted;
    }

}
</code>```

Then my Child class would have something like:

```<code>    public int SomeDumbProperty
    {
        get;
        set
        {
            base.Status = StatusState.Updated;
            // Missing line here to set the property itself
        }
    }

    private int _SomeIntelligentProperty;

    public int SomeIntelligentProperty
    {
        get { return _SomeIntelligentProperty; }

        set
        {
            if (value != _SomeIntelligentProperty)
            {
                _SomeIntelligentProperty = value;
                base.Status = StatusState.Updated;
            }
        }
    }
</code>```

The idea being that the intelligent one detects if there has indeed been a change; otherwise using the dumb one the client app would need to either detect change and only update if there has been a change, or use the setter anyway flagging a change which actually didn't occur.

I also know that my dumbproperty doesn't work (or compile) right now. If I want code in the getter or setter, does this mean I need to define a separate private variable myself ? I know the short hand {get; set;} does this behind the scenes.

答:
I think a good solution here would be for the client model to detect changes to itself and then send to the server only the changes.

This means that setters of your properties will have to at the very least record that something changed. And collections can't be simple List<T>s, but something that can have custom reaction to changes. (You can use Collection<T> with overridden methods like InsertItem() for this.)


答:
My suggestion is do one of this:

1. Use the QueryResult object but change the name of QueryResult.ReasonForNoValue() to QueryResult.Message().

```<code>public class QueryResult
{
    public TValue Value { get; private set; }
    public TMessage Message { get; private set; }
}
</code>```

2. Rise KeyUnknowException or NoTranslationException, although you already said you don't like this solution.

3. Always return a non-null value. Only that two special string values exist: "#UKNOWN_KEY" and "#NO_TRANSLATION".

EDIT: (thanx to @DanielHilgarth) You would need to document several things:

That a missing value doesn't return null but still a string.

That a missing value is indicated by several magic strings (with the same implications as magic constants).

What each of those magic strings means.

And finally, someone would have to actually read that documentation.

In general, this kind of architecture increases the possibility of bugs.

Body:
My suggestion is do one of this:

1. Use the QueryResult object but change the name of QueryResult.ReasonForNoValue() to QueryResult.Message().

public class QueryResult
{
    public TValue Value { get; private set; }
    public TMessage Message { get; private set; }
}

2. Rise KeyUnknowException or NoTranslationException, although you already said you don't like this solution.

3. Always return a non-null value. Only that two special string values exist: "#UKNOWN_KEY" and "#NO_TRANSLATION".

EDIT: (thanx to @DanielHilgarth) You would need to document several things:

That a missing value doesn't return null but still a string.

That a missing value is indicated by several magic strings (with the same implications as magic constants).

What each of those magic strings means.

And finally, someone would have to actually read that documentation.

In general, this kind of architecture increases the possibility of bugs.


答:
Actually there are 3 options:

Local development

advantages:

easy to work with most development tools

no need for internet connection

not affecting other devs

disadvantages:

depends on underlying OS

might need to run all kinds of server services on your local machine

environment might be quite different from production

Local virtual machine

advantages:

fairly easy to work with most development tools, provided you properly set up folder sharing

no need for internet connection

not affecting other devs

environment might be virtually identical as production

server services started/stopped within the virtual machine

disadvantages:

bit more resources required (mainly amount of RAM, CPU isn't an issue with modern hardware virtualization support).

some local debugging tools which would attach directly to server will not work

Shared development server

advantages:

environment might be virtually identical as production

server services on the server

disadvantages:

remote access

changes affecting other devs

much harder debugging (either by using remote tools, or logs)

Optimal solution

Use either of local development options and push to shared development server once you have completed self contained part of the feature and your have verified that your code isn't completely broken.

Title: Dev Server vs Local Development


答:
You could use your object and make something like:

```<code>public class QueryResult
{
    public TValue Value { get; private set; }
    public TQuerySuccess SuccesValue { get; private set; }
}
</code>```

You read the succesvalue to see whether query was sucessful, if it was, value will contain queryresult, if it wasn't value will contain failreason.

Body:
You could use your object and make something like:

public class QueryResult
{
    public TValue Value { get; private set; }
    public TQuerySuccess SuccesValue { get; private set; }
}

You read the succesvalue to see whether query was sucessful, if it was, value will contain queryresult, if it wasn't value will contain failreason.


答:
Many internet protocols are built around a response code that is always returned along with an associated message.  SMTP and HTTP being two well known examples.

Thus, public TReason ReasonForNoValue becomes something more along the lines of public TResponse ResponseCode

The response could be an integer and follow the SMTP and HTTP style example, or it could be an enum for some type safety, or even a string (though this imposes some dangers of not doing string comparisons correctly somewhere, or a typo).

When there is an error (and indicated by the ResponseCode), the value could then hold more specific information (akin to a 404 page in HTTP).


问:
What values in an application should be configurable?
What values in an application should be configurable, or otherwise not hard coded?  Does this differ based on application type (batch vs UI) and are there any published standards or guidance on this topic (IEEE, ACM, vendor, etc)?</p>

答:
There are two extremes:

Hard-code everything.  This has the advantage of being easy and avoids the overhead of configuration.  The disadvantages are obvious: maintainability, hot-deploying config changes, varying settings across environments, etc.

Make everything a configuration setting.  This has the most flexibility at the cost of having large configuration files with settings that rarely and sometimes never change.

A guideline is tough to have because it varies case-by-case.

Some questions to ask for each setting:

How likely is this to change?  More likely suggests config, less likely suggests a code constant may be acceptable.

If it changes, do we need immediate result or can we wait for a full build and redeploy?  If a rebuild and deploy is acceptable, then a code constant may be acceptable.

Would the value ever need to be different across different environments?  If so, you obviously can't put it in your code unless your code knows about environments, which is not a great idea in my mind.

Is the value itself dictated by a business rule?  For example, page size when paginating a list is likely to be spelled out by a requirements spec.  If it is, then the need to see a change take effect immediately is probably non-existent.  The change is likely to be tracked via product requirement change control and so embedding the value in code is probably wise.

If the setting is related to performance, you probably want it to be hot/field serviceable, so configuration is the way to go.

When I recommend storing settings in code, I presume you would use a centralized constant and not hard-code in each place that uses it.

I'll share a funny story of bad constant use that this reminds me of.  I have seen code where a constant is passed for page size.  The constant is named HUNDRED_STRING.  HUNDRED_STRING is of course set to "100".  I can't wait to see what happens when somebody sets HUNDRED_STRING = "200" and the world goes crazy.


问:
Gathering all data in single iteration vs using functions for readable code
Say I have an array of runners with which I need to find the tallest runner, the fastest runner, and the lightest runner. It seems like the most readable solution would be:

```<code>runners = getRunners();
tallestRunner = getTallestRunner(runners);
fastestRunner = getFastestRunner(runners);
lightestRunner = getLightestRunner(runners);
</code>```

..where each function iterates over the runners and keeps track of the largest height, greatest speed, and lowest weight. Iterating over the array three times, however, doesn't seem like a very good idea. It would instead be better to do:

```<code>int greatestHeght, greatestSpeed, leastWeight;
Runner tallestRunner, fastestRunner, lightestRunner;
for(runner in runners){
    if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
    if(runner.speed > ...
}
</code>```

While this isn't too unreadable, it can get messy when there is more logic for each piece of information being extracted in the iteration.

What's the middle ground here? How can I use only a single iteration while still keeping the code divided into logical units?

答:
The problem you are describing is very common: You have a loop that produces certain data, and you want to aggregate multiple "statistics" from the overall data. The straightforward implementation is, as you said, to have multiple local variables which are each updated in every iteration:

```<code>   int greatestHeight, greatestSpeed, leastWeight;
   Runner tallestRunner, fastestRunner, lightestRunner;
   for(...){
      runner = ... // the runner comes from somewhere, not necessarily a list
      if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
      if(runner.speed > ...
   }
</code>```

This doesn't have a good separation of concerns, because you have the aggregation logic inline with the data production. Extracting the aggregation logic into a method (as proposed in this answer) is an improvement, but the isolation is still not good: the intermediate results and (if needed) helper variables like greatestHeight still have to be local variables.

So IMHO the only good solution is to extract both the aggregation logic and the assignments into a method.

How can this be done? By first refactoring the local variables to fields. Then, you can e.g. extract a method updateStats(runner) which updates the tallestRunner/fastestRunner/... fields and corresponding greatestHeight/greatestSpeed/... fields.

But doesn't this make isolation worse? Yes, at first, but this can be fixed by an extract class refactoring: Move the the statistics fields and the updateStats method to a new (e.g. nested) class. So in the end you'll have the following readable, single-pass solution:

```<code>   RunnerStats stats = new RunnerStats();
   for(...){
       runner = ...
       stats.updateStats(runner);
    }
    ... = stats.tallestRunner;
 }

 static class RunnerStats{
      int greatestHeight, greatestSpeed, leastWeight = Integer.MAX_VALUE;
      Runner tallestRunner, fastestRunner, lightestRunner;

      void updateStats(Runner runner){
          updateTallest(runner);
          update...
      }

      void updateTallest(Runner runner){
           if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
      }
 }
</code>```

Body:
The problem you are describing is very common: You have a loop that produces certain data, and you want to aggregate multiple "statistics" from the overall data. The straightforward implementation is, as you said, to have multiple local variables which are each updated in every iteration:

   int greatestHeight, greatestSpeed, leastWeight;
   Runner tallestRunner, fastestRunner, lightestRunner;
   for(...){
      runner = ... // the runner comes from somewhere, not necessarily a list
      if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
      if(runner.speed > ...
   }

This doesn't have a good separation of concerns, because you have the aggregation logic inline with the data production. Extracting the aggregation logic into a method (as proposed in this answer) is an improvement, but the isolation is still not good: the intermediate results and (if needed) helper variables like greatestHeight still have to be local variables.

So IMHO the only good solution is to extract both the aggregation logic and the assignments into a method.

How can this be done? By first refactoring the local variables to fields. Then, you can e.g. extract a method updateStats(runner) which updates the tallestRunner/fastestRunner/... fields and corresponding greatestHeight/greatestSpeed/... fields.

But doesn't this make isolation worse? Yes, at first, but this can be fixed by an extract class refactoring: Move the the statistics fields and the updateStats method to a new (e.g. nested) class. So in the end you'll have the following readable, single-pass solution:

   RunnerStats stats = new RunnerStats();
   for(...){
       runner = ...
       stats.updateStats(runner);
    }
    ... = stats.tallestRunner;
 }

 static class RunnerStats{
      int greatestHeight, greatestSpeed, leastWeight = Integer.MAX_VALUE;
      Runner tallestRunner, fastestRunner, lightestRunner;

      void updateStats(Runner runner){
          updateTallest(runner);
          update...
      }

      void updateTallest(Runner runner){
           if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; }
      }
 }


问:
DDD and filtering
I am developing an app in ddd maner. So I have a complex domain model. Suppose I have a Fare object and Airline. Each Airline should contain several or much more Fares.

My UI should represent Model (only small part of complex model) as a list of Airline, when the user select the Airline, I must show the list of Fares. User can filtering the Fares (by travel time, cost, etc.).

What is the appropriate place for filtering Fares and Airlines?

I am assuming that I should do it in ViewModel. Like: My domain model has wrapped with Service Layer -> UI works with ViewModel -> ViewModel obtain data from Service Layer filtering it and create DTO objects for UI. Or I'm wrong?

答: Generally DDD and CQRS go hand in hand, so this would be the query portion of CQRS. The way I've always understood CQRS and DDD together is that the application service should have focused queries. If you're filtering at the UI level (on the initial get, not client side) then you would seem to be breaking this separation of concerns as you're now doing business logic in the UI. Ideally the filtering should be a very simple query.  But as always DDD and CQRS are but tools, do what works.</p>

Title: DDD and filtering


问:
Writing Large Portions Of Code Then Debugging?
Lately I have been writing a game engine, and I have been writing a lot of "foundation stuff" (standard interfaces, modules, a message system ect.), but I have noticed a pattern, a lot of the stuff is interdependent and I can not debug until everything is done, hence I do not debug for about 3 to 5 hours at a time. I am wondering if this is an acceptable practice for this part of the project, and if not, if anyone can give me some advice?

-----Update-----:

I downloaded some code metrics tools, and my programs cyclomatic complexity is 1.52 which as I understand it is good, and should correlate to high cohesion, if I am wrong please correct me/

答:
This is called coupling. You can reduce coupling by breaking everything into smaller pieces, which should increase the cohesion of each piece. It will make it easier and faster to develop and test each piece.

If you are developing something with dependencies on other pieces, try designing with Dependency Injection in mind. This should let you develop each piece individually, without needing to create all of its dependencies first.


答:
We have also recently started looking at CDC.  I'm not an expert on the subject, but I think I have some answers for your questions.

For the most part, CDC will help you achieve your goal of a completely traceable history, but I don't think it will get you all of the way there.

First off:

we frequently make changes to the database schema  ... Is there a mechanism to update the CDC table to the new schema

And this is where I think CDC will fail you.  The MSDN documentation under the section "Understanding Change Tracking Overhead" is pretty clear that it won't track the schema changes for you. For example, with Alter Table Add Column:

If a new column is added to the change tracked table, the addition of the column is not tracked. Only the updates and changes that are made to the new column are tracked.

Drop Column is a little bit more complex.

However, you should be using DB scripts to alter your schema so you don't necessarily have to rely upon CDC here.  That allows you to have consistency between your QA and Production schemas.  And change to QA should be performed by script so the exact same changes can be applied to Prod.  It shouldn't be too hard to extract out the schema changes from those scripts.  This may mean that the "time" dimension of your history be driven by version instead of actual time, but the end result will be the same.

If you don't have one already, create a table to track the version of your database schema. And then place that database schema version table under CDC so you can align macroscopic changes to the schema against the microscopic changes within a particular table.

To my understanding, you should still be seeing the data added to the new column(s) regardless of CDC not showing the schema change.  And the data migration from table to table should also be picked up by CDC.

are there any best practices to how you deal with captured data when migrating the database schema?

Treat it like you would treat an audit.  You need to understand what it is you're examining, why you're examining it, and how long you need to keep that information around.  Scope and retention are the two biggest bugaboos when it comes to a task like this.

CDC's reporting tools are understandably austere, so you have to know the context of the changes.  It's too easy to say "track everything!" and end up with nothing that's usable as a result.  Likewise, you could be doubling the size of your database by keeping a copy of every change.  On a high churn table with many inserts and deletes, you'll end up with astronomical growth.  That's not bad in and of itself, but you need to budget for that growth and have a means to examine all of the data that's generated.

So this gets you back to understanding why you are being pushed to have complete traceability.  There are certainly valid reasons for that requirement.  But you won't be able to structure your effective auditing of the database until you know why you must meet that requirement.

Title: Using Sql Server Change Data Capture with a frequently changing schema

Body:
We are looking into enabling Sql Server Change Data Capture for a new subsystem we are building.

It's not really because we need it, but we are being pushed for having a complete history traceability, and CDC would nicely solve this requirement with minimum effort on our parts.

We are following an agile development process, which in this case means that we frequently make changes to the database schema, e.g. adding new columns, moving data to other columns, etc.

We did a small test where we created a table, enabled CDC for that table, and then added a new column to the table. Changes to the new column is not registered in the CDC table.

Is there a mechanism to update the CDC table to the new schema, and are there any best practices to how you deal with captured data when migrating the database schema?


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
I'd answer your question with questions.

What do you expect to get or achieve in return for the free work?

and

Can you get the same results in a more cost effective or reliable way?

In short, if you can program, someone will employ you.  If you don't know how to program, then no company will want you around stopping their programmers from delivering.

Title: Working for free?


问:
Is this over-abstraction? (And is there a name for it?)
I work on a large Django application that uses CouchDB as a database and couchdbkit for mapping CouchDB documents to objects in Python, similar to Django's default ORM.  It has dozens of model classes and a hundred or two CouchDB views.

The application allows users to register a "domain", which gives them a unique URL containing the domain name that gives them access to a project whose data has no overlap with the data of other domains.  Each document that is part of a domain has its domain property set to that domain's name.

As far as relationships between the documents go, all domains are effectively mutually exclusive subsets of the data, except for a few edge cases (some users can be members of more than one domain, and there are some administrative reports that include all domains, etc.).

The code is full of explicit references to the domain name, and I'm wondering if it would be worth the added complexity to abstract this out.  I'd also like to know if there's a name for the sort of bound property approach I'm taking here.

Basically, I have something like this in mind:

Before

in models.py

```<code>class User(Document):
    domain = StringProperty()

class Group(Document):
    domain = StringProperty()
    name = StringProperty()
    user_ids = StringListProperty()

    # method that returns related document set
    def users(self):
        return [User.get(id) for id in self.user_ids]

    # method that queries a couch view optimized for a specific lookup
    @classmethod
    def by_name(cls, domain, name):
        # the view method is provided by couchdbkit and handles
        # wrapping json CouchDB results as Python objects, and
        # can take various parameters modifying behavior
        return cls.view('groups/by_name', key=[domain, name])

    # method that creates a related document
    def get_new_user(self):
        user = User(domain=self.domain)
        user.save()
        self.user_ids.append(user._id)
        return user
</code>```

in views.py:

```<code>from models import User, Group

# there are tons of views like this, (request, domain, ...)
def create_new_user_in_group(request, domain, group_name):
    group = Group.by_name(domain, group_name)[0]
    user = User(domain=domain)
    user.save()
    group.user_ids.append(user._id)
    group.save()
</code>```

in group/by_name/map.js:

```<code>function (doc) {
    if (doc.doc_type == "Group") {
        emit([doc.domain, doc.name], null);
    }
}
</code>```

After

models.py

```<code>class DomainDocument(Document):
    domain = StringProperty()

    @classmethod
    def domain_view(cls, *args, **kwargs):
        kwargs['key'] = [cls.domain.default] + kwargs['key']
        return super(DomainDocument, cls).view(*args, **kwargs)

    @classmethod
    def get(cls, *args, **kwargs, validate_domain=True):
        ret = super(DomainDocument, cls).get(*args, **kwargs)

        if validate_domain and ret.domain != cls.domain.default:
            raise Exception()

        return ret

    def models(self):
        # a mapping of all models in the application. accessing one returns the equivalent of

        class BoundUser(User):
            domain = StringProperty(default=self.domain)

class User(DomainDocument):
    pass

class Group(DomainDocument):
    name = StringProperty()
    user_ids = StringListProperty()

    def users(self):
        return [self.models.User.get(id) for id in self.user_ids]

    @classmethod
    def by_name(cls, name):
        return cls.domain_view('groups/by_name', key=[name])

    def get_new_user(self):
        user = self.models.User()
        user.save()
</code>```

views.py

```<code>@domain_view  # decorator that sets request.models to the same sort of object that is returned by DomainDocument.models and removes the domain argument from the URL router
def create_new_user_in_group(request, group_name):
    group = request.models.Group.by_name(group_name)
    user = request.models.User()
    user.save()
    group.user_ids.append(user._id)
    group.save()
</code>```

(Might be better to leave the abstraction leaky here in order to avoid having to deal with a couchapp-style //! include of a wrapper for emit that prepends doc.domain to the key or some other similar solution.)

```<code>function (doc) {
    if (doc.doc_type == "Group") {
        emit([doc.name], null);
    }
}
</code>```

Pros and Cons

So what are the pros and cons of this?

Pros:

DRYer

prevents you from creating related documents but forgetting to set the domain.

prevents you from accidentally writing a django view -> couch view execution path that leads to a security breach

doesn't prevent you from accessing underlying self.domain and normal Document.view() method

potentially gets rid of the need for a lot of sanity checks verifying whether two documents whose domains we expect to be equal are.

Cons:

adds some complexity

hides what's really happening

requires no model modules to have classes with the same name, or you would need to add sub-attributes to self.models for modules.  However, requiring project-wide unique class names for models should actually be fine because they correspond to the doc_type property couchdbkit uses to decide which class to instantiate them as, which should be unique.

removes explicit dependency documentation (from group.models import Group)

答:
This is really a question that only you can answer, over-abstraction is in the eye of the beholder. The below is my humble opinion.

To me Domain is an entity. It's an entity because it has identity that is critical to the lifecycle of the Domain concept. As such abstracting it out of other contexts is exactly the thing to do, but as its own first class object rather than as part of another class that you still pass around. Furthermore at first glance it would appear to me that Domain is an aggregate entity.

Document in my opinion exists in the same bounded context as Domain, but is a separate aggregate that will be referenced by ID only e.g. a document must be associated with a domain but since there is no need for transactional consistency between the two it's OK to have them as separate aggregates.


答:
Here are common design patterns to handle these scenarios.

Set up a base class. Child and parent will inherit from base.  Base class should do the following:

Have a .Status property (read-only) that tracks if an object is {unchanged, new, updated, deleted}  The status is set during {constructor, .delete() method, each Property's setter}.  You will need a factory method to generate an object instance with a status of "unchanged" or a method to mark itself as "unchanged".

btw. This approach makes an object more "atomic" because it is self-contained and it keeps track of its own changes.  This is also an example of why people use Properties (getters/setters) instead of public vars.

A commonly used pseudo locking mechanism is to use a combination of .LastModifiedDateTime (read only) and .LastModifier (read-only) columns on each DB table (non code-table/static-table).  These are also set in the constructor/factory method.  On Update/Save, compare the current LastModifiedDateTime & LastModifier to the DB.  If they don't match then reject this change.

#1 is similar to the way many ORMs maintain state (handle changes).  #2 is often referred-to as a "soft locking mechanism".

Title: Design pattern for logging changes in parent/child objects saved to database

Body:
I’ve got a 2 database tables in parent/child relationship as one-many.

I’ve got three classes representing the data in these two tables:

```<code>Parent Class
{
    Public int ID {get; set;}
    .. other properties
}

Child Class
{
    Public int ID {get;set;}
    Public int ParentID {get; set;}
    .. other properties
}

TogetherClass
{
    Public Parent Parent;
    Public List<Child> ChildList;
}
</code>```

Lastly I’ve got  a client and server application – I’m in control of both ends so can make changes to both programs as I need to.

Client  makes a request for ParentID and receives a Together Class for the matching parent, and all of the child records.

The client app may make changes to the children – add new children, remove or modify existing ones.  Client app then sends the Together Class back to the server app.

Server app needs to update the parent and child records in the database.

In addition I would like to be able to log the changes – I’m doing this by having 2 separate tables one for Parent, one for child; each containing the same columns as the original plus date time modified, by whom and a list of the changes.

I’m unsure as to the best approach to detect the changes in records – new records, records to be deleted, records with no fields changed, records with some fields changed.

I figure I need to read the parent & children records and compare those to the ones in the Together Class.

Strategy A:

If Together class’s child record has an ID of say 0, that indicates a new record; insert.
Any deleted child records are no longer in the Together Class; see if any of the comparison child records are not found in the Together class and delete if not found (Compare using ID).

Check each child record for changes and if changed log.

Strategy B:
Make a new Updated TogetherClass

```<code>UpdatedClass
{
    Public Parent Parent {get; set}
    Public List<Child> ListNewChild {get;set;}
    Public List<Child> DeletedChild {get;set;}
    Public List<Child> ExistingChild {get;set;} // used for no changes and modified rows
}
</code>```

And then process as per the list.

The reason why I’m asking for ideas is that both of these solutions don’t seem optimal to me and I suspect this problem has been solved already – some kind of design pattern ?

I am aware of one potential problem in this general approach – that where Client App A requests a record; App B requests same record; A then saves changes; B then saves changes which may overwrite changes A made.  This is a separate locking issue which I’ll raise a separate question for if I’ve got trouble implementing.

The actual implementation is c#, SQL Server and WCF between client and server - sharing a library containing the class implementations.

Apologies if this is a duplicate post – I tried searching various terms without finding a match though.

Update based on comments from svick and TimG:

To track change would the base class be something like:

```<code>public class ChangedRowBase
    {
        public enum StatusState
        {
        New, Unchanged, Updated, Deleted
    };

    protected StatusState _Status;

    public StatusState Status
    {
        get
        {
            return _Status;
        }
    }

    public void SetUnchanged()
    {
        _Status = StatusState.Unchanged;
    }

    public void SetDeleted()
    {
        _Status = StatusState.Deleted;
    }

}
</code>```

Then my Child class would have something like:

```<code>    public int SomeDumbProperty
    {
        get;
        set
        {
            base.Status = StatusState.Updated;
            // Missing line here to set the property itself
        }
    }

    private int _SomeIntelligentProperty;

    public int SomeIntelligentProperty
    {
        get { return _SomeIntelligentProperty; }

        set
        {
            if (value != _SomeIntelligentProperty)
            {
                _SomeIntelligentProperty = value;
                base.Status = StatusState.Updated;
            }
        }
    }
</code>```

The idea being that the intelligent one detects if there has indeed been a change; otherwise using the dumb one the client app would need to either detect change and only update if there has been a change, or use the setter anyway flagging a change which actually didn't occur.

I also know that my dumbproperty doesn't work (or compile) right now. If I want code in the getter or setter, does this mean I need to define a separate private variable myself ? I know the short hand {get; set;} does this behind the scenes.


问:
Is it a good practice to wrap all primitives and Strings?
According to Jeff Bay's Essay on Object Callisthenics,

One of the practices is set to be "Wrap all primitives and Strings"

Can anyone elaborate on this ?

In languages where we already have wrappers for primitives like C# and Java.
and In languages where Collections can have generics where you are sure of what type goes into the collection, do we need to wrap string's inside their own classes ?

Does it have any other advantage ?

答:
Trivially no. Absolutely not. It's a bad idea for the same reason that if(boolValue==true) is a bad idea. If it was a good idea, doing it twice would be even better: if((boolValue==true)==true) or WrappedWrappedString. But a boolean is already a boolean, and a string is already an abstraction that wraps a container of characters.

A successful design pattern modifies a primitive component to perform a related but different task. A design pattern which modifies a primitive component to perform the same task adds no value and causes entirely avoidable confusion.


答:
This cuts across industries, but working for free might seem like a way to gain experience and earn goodwill, yet often enough ends in bitterness and resentment when the parameters of work aren't clear. I've seen too many people do a favor and develop a simple website for friends, or colleagues, only to witness their relationships deteriorate because of unrealized expectations that the website would be further developed, supported, etc... </p>

<p>The point isn't that doing the work in and of itself for free is bad, but that working for free usually means working outside of a clearly defined scope. Contracts and employment agreements are invaluable resources when things go wrong, which they often do. When you work for free you're working in a realm of colliding and sometimes contradictory expectations. If you are considering doing it, and the project or opportunity seems worthwhile, I'd suggest you draft up a scope of work, or some document to which you can refer back to if your time starts being taken advantage of. </p>

Title: Working for free?

Body:
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

Body:
This cuts across industries, but working for free might seem like a way to gain experience and earn goodwill, yet often enough ends in bitterness and resentment when the parameters of work aren't clear. I've seen too many people do a favor and develop a simple website for friends, or colleagues, only to witness their relationships deteriorate because of unrealized expectations that the website would be further developed, supported, etc...

The point isn't that doing the work in and of itself for free is bad, but that working for free usually means working outside of a clearly defined scope. Contracts and employment agreements are invaluable resources when things go wrong, which they often do. When you work for free you're working in a realm of colliding and sometimes contradictory expectations. If you are considering doing it, and the project or opportunity seems worthwhile, I'd suggest you draft up a scope of work, or some document to which you can refer back to if your time starts being taken advantage of.


问:
Big project layout : adding new feature on multiple sub-projects
I want to know how to manage a big project with many components with version control management system.

In my current project there are 4 major parts.

Web

Server

Admin console

Platform.

The web and server part uses 2 libraries that I wrote.  In total there are  5 git repositories and 1 mercurial repository. The project build script is in Platform repository. It automates the whole building process.

The problem is when I add a new feature that affects multiple components I have to create branch for each of the affected repo. Implement the feature. Merge it back. My gut feeling is "something is wrong".

So should I create a single repo and put all the components there? I think branching will be easier in that case. Or I just do what I am doing right now. In that case how do I solve this problem of creating branch on each repository?

答:
If each of your repositories are stand-alone projects or libraries, then I'd say that there isn't anything inherently wrong with needing to create feature branches on each repo when adding new features that cross-cut across the projects. By being stand-alone, each one can be independently versioned and you can deprecate old APIs.

But in your particular case, it sounds like your repositories might not be grouping your code effectively. If changes to code in one repository requires changes to others (deprecation aside) then either your coupling is too tight or the repositories should be reorganized.

If all the repositories are really part of the same project (they can't stand alone) then maybe you should only have 1 repository. (Or maybe 2: the main project and one for generic/standardized functionality.)

OwnerDisplayName: Shiplu


问:
Best practice for storing HTML coming from text fields to a database?
I have an application that allows users to edit certain parts of text and then email that out. My question is what is the best way to store this in a Microsoft SQL Server database. Right now I have two tables, one holding the HTML data and one holding the plain text data. When the user saves the info, it replaces newlines with br's and puts it in the HTML-conntaining table and then puts the regular text in the other table. This way the text box has the newlines when they go to edit, but the table that contains the HTML data, has the BR's. This seems like a silly way to do things. What would be the best practice? Thanks. </p>

答: If it were me, I would just replace the newlines with br's as the text is being used. So, store the plain text (newlines), and then when you have to use it in an email, replace the newlines with br's on the fly.</p>


答:
It's not silly at all.

Consider the following possibilities:

Store just HTML. That 's silly! Once stored this way, editing it would be painful: you either should decode it, or simply forbid any edition or force users to write HTML.

Store just text. It may work. Until, maybe, you find that converting text to HTML is the bottleneck¹ which slows your application down. For small scale apps, this approach is still ok and probably the easiest one.

Store text and HTML. That's what you've chosen, and it has the benefits of both previous approaches: editing content is simple, and at the same time you don't slow the application down by doing the conversion every time the page is generated.

If there is a thing which is annoying, it's the fact that you are using two tables. Why not keeping this data in a single table, with one column for original text, and another column for HTML?

¹ Remember one rule: don't guess what is slowing the application down: use a profiler. Discussing which approach is faster is good for an informal talk with your friends, but not a good approach to develop a scalable application without doing unnecessary work. My example of saving HTML vs. generating it on the fly, for example, is only good in theory. In practice, (1) you'll cache the results anyway, and (2) maybe, who knows, loading the data from the database may be much slower than generating HTML.

Title: Best practice for storing HTML coming from text fields to a database?

Body: I have an application that allows users to edit certain parts of text and then email that out. My question is what is the best way to store this in a Microsoft SQL Server database. Right now I have two tables, one holding the HTML data and one holding the plain text data. When the user saves the info, it replaces newlines with br's and puts it in the HTML-conntaining table and then puts the regular text in the other table. This way the text box has the newlines when they go to edit, but the table that contains the HTML data, has the BR's. This seems like a silly way to do things. What would be the best practice? Thanks. </p>


答:
You might consider an implementation of BBCode. This will allow you to store plain text, which can be converted to HTML. No actual HTML tags would be allowed.

From Wikipedia:

[b]bolded text[/b]

would become

bolded text

and so on.

Body:
You might consider an implementation of BBCode. This will allow you to store plain text, which can be converted to HTML. No actual HTML tags would be allowed.

From Wikipedia:

[b]bolded text[/b]

would become

<b>bolded text</b>

and so on.


问:
Putting semicolons after while and if statements in C++
How come in C++ when you put:

```<code>while (expression);
</code>```

the while loop doesn't run no matter if the expression is true or not.

However if you put:

```<code>if (expression);
</code>```

the statement runs no matter if the expression is true or not.

It seems like they should both behave the same way.

答:
actually when you put

```<code>while(expr);
</code>```

then if expr is true then you get into an infinite loop that will never end (so the remaining code never executes)

you can understand it by replacing the empty statement ; with a no-op

```<code>void noop(){}

while(expr)noop();
</code>```

then the semantics make sense

Body:
actually when you put

while(expr);

then if expr is true then you get into an infinite loop that will never end (so the remaining code never executes)

you can understand it by replacing the empty statement ; with a no-op

void noop(){}

while(expr)noop();

then the semantics make sense


问:
Recommened design pattern to handle multiple compression algorithms for a class hierarchy
For all you OOD experts. What would be the recommended way to model the following scenario?

I have a certain class hierarchy similar to the following one:

```<code>class Base {
   ...
}

class Derived1 : Base {
   ...
}

class Derived2 : Base {
   ...
}
...
</code>```

Next, I would like to implement different compression/decompression engines for this hierarchy.  (I already have code for several strategies that best handle different cases, like file compression, network stream compression, legacy system compression, etc.)

I would like the compression strategy to be pluggable and chosen at runtime, however I'm not sure how to handle the class hierarchy. Currently I have a tighly-coupled design that looks like this:

```<code>interface ICompressor {
   byte[] Compress(Base instance);
}

class Strategy1Compressor : ICompressor {
   byte[] Compress(Base instance) {

      // Common compression guts for Base class
      ...
      //

      if( instance is Derived1 ) {
         // Compression guts for Derived1 class
      }
      if( instance is Derived2 ) {
         // Compression guts for Derived2 class
      }

      // Additional compression logic to handle other class derivations
      ...
   }

}
</code>```

As it is, whenever I add a new derived class inheriting from Base, I would have to modify all compression strategies to take into account this new class.  Is there a design pattern that allows me to decouple this, and allow me to easily introduce more classes to the Base hierarchy and/or additional compression strategies?

答:
You can try a combination of strategy and factory:

```<code>public abstract class Compressor {
    private Base base;

    public Compressor(BaseType baseType) {//BaseType can be an enum
        if (baseType == DERIVED1) {
            base = new Derived1();
        } else if (baseType == DERIVED2) {
            base = new Derived2();
        }
    }

    protected Base GetBase() {
        return base;
    }

    public abstract byte[] Compress();
}

public class Strategy1Compressor : ICompressor {
    public byte[] Compress() {
        Base base = super.GetBase();//hope this is legal in C#
        //do compression logic based on base
    }
}
</code>```

You can also provide a factory over the compressors:

```<code>public class CompressorFactory {
    public static Compressor CreateCompressor(CompressorType compressorType,
                                              BaseType baseType) {
        if (compressorType == STRATEGY1_COMPRESSOR) {//again enum
            return new Strategy1Compressor(baseType);
        } else if //...
    }
}
</code>```

Note: I hope that the code above is legal C# code, as I am familiar with Java.

Body:
You can try a combination of strategy and factory:

public abstract class Compressor {
    private Base base;

    public Compressor(BaseType baseType) {//BaseType can be an enum
        if (baseType == DERIVED1) {
            base = new Derived1();
        } else if (baseType == DERIVED2) {
            base = new Derived2();
        }
    }

    protected Base GetBase() {
        return base;
    }

    public abstract byte[] Compress();
}

public class Strategy1Compressor : ICompressor {
    public byte[] Compress() {
        Base base = super.GetBase();//hope this is legal in C#
        //do compression logic based on base
    }
}

You can also provide a factory over the compressors:

public class CompressorFactory {
    public static Compressor CreateCompressor(CompressorType compressorType,
                                              BaseType baseType) {
        if (compressorType == STRATEGY1_COMPRESSOR) {//again enum
            return new Strategy1Compressor(baseType);
        } else if //...
    }
}

Note: I hope that the code above is legal C# code, as I am familiar with Java.


答: I am currently working for free to gain experience and I don't mind working for free. I get to do something I really enjoy and will have a finished product I can call my own (my own projects always seem to stall). The problem can become the spouse/significant other. There have been a number of times where we get into arguments because I'm spending many hours doing something that will not pay out financially. </p>

Title: Working for free?


答:
Your statement that gets run (or not) is an empty statement, the ;. The other statements that follow the ; have nothing to do with your if- and while-statement. Your code would do the same when written as

```<code>while (expression)
{
    ;
}
</code>```

and

```<code>if (expression)
{
    ;
}
</code>```

The only difference is that your statement would be inside a block. You could add more statements inside the block (inside the curly brackets) that would get executed, if the expression was true.

Title: Putting semicolons after while and if statements in C++

Body:
How come in C++ when you put:

```<code>while (expression);
</code>```

the while loop doesn't run no matter if the expression is true or not.

However if you put:

```<code>if (expression);
</code>```

the statement runs no matter if the expression is true or not.

It seems like they should both behave the same way.

Body:
Your statement that gets run (or not) is an empty statement, the ;. The other statements that follow the ; have nothing to do with your if- and while-statement. Your code would do the same when written as

while (expression)
{
    ;
}

and

if (expression)
{
    ;
}

The only difference is that your statement would be inside a block. You could add more statements inside the block (inside the curly brackets) that would get executed, if the expression was true.