答:
There's a is a fairly large and varied set of conceptual and technical difficulties when trying to approach a relational database from an object oriented angle. These difficulties are collectively known as  object-relational impedance mismatch and the related Wikipedia article is extremely informative. The article identifies quite a few, I don't see any sensible way of describing them here. Just to give you a general idea, they are catalogued as:

Mismatches

Object-oriented concepts

Data type differences

Structural and integrity differences

Manipulative differences

Transactional differences

Solving impedance mismatch

Minimization

Alternative architectures

Compensation

Contention

Philosophical differences

I think if you take the time to read the article you'll understand that the fact that ORM is sometimes described as an anti-pattern is in fact inevitable. The two domains are so different that any approach to treat one as the other is by default an anti-pattern, in the sense that an anti-pattern is a pattern that goes against the philosophy of a domain.

But I don't think the term should apply to anything that essentially acts as a bridge between two vastly different domains. Labelling a pattern as anti-pattern makes sense only within its domain. So the question of whether it's an anti-pattern or not is irrelevant.

But is it useful? Yes ORM is one of the most useful anti-patterns out there. You will understand why only if you find yourself in a practical situation where you'll have to swap databases in a project. Or even upgrade to another version of the same database. ORM is one of those things, that you only fully understand when you actually need them.

Off course, as everything useful, ORM is highly prone to abuse. If you think it somehow replaces the need to know everything about the database you work on, then it will come back and bite you. Hard.

Finally, let me shamelessly plug another one of my answers, on the related "Does the ActiveRecord pattern follow/encourage the SOLID design principles?" question, which to me is a far more relevant question than "is it an anti-pattern".

Title: Is ORM an Anti-Pattern?


问:
Is it OK to use dynamic typing to reduce the amount of variables in scope?
Often, when I am initializing something I have to use a temporary variable, for example:

```<code>file_str = "path/to/file"
file_file = open(file)
</code>```

or

```<code>regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )
</code>```

However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body.

In these initialization cases, if I am using a dynamic language, I am then often tempted to reuse the same variable in order to prevent the initial (and now useless) value from being used latter in the function.

```<code>file = "path/to/file"
file = open(file)

regexp = ['...', '...']
regexp = new RegExp( regexp.join('|') )
</code>```

The idea is that by reducing the number of variables in scope I reduce the chances to misuse them. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename".

I think perhaps this would be a non issue if I could use non-nested scopes

```<code>begin scope1
   filename = ...
begin scope2
   file = open(filename)
end scope1
   //use file here
   //can't use filename on accident
end scope2
</code>```

but I can't think of any programming language that supports this.

What rules of thumb should I use in this situation?

When is it best to reuse the variable?

When is it best to create an extra variable?

What other ways do we solve this scope problem?

答:
You are quite correct to limit the scope of variables if you can. It's best to simply use short functions, but if you have several variables only used for a few lines, it can make sense to make a scope around them. However, it's a bit ugly in most languages I know, and the benefits are comparatively small if you follow the advice below, so most people don't bother most of the time.

However, you definitely should:

If you have a one-off variable, give it a longer name you're unlikely to use again accidentally, eg:

```<code>path_to_config_file = "blah/blah/blah";
cfg_fileh = open path_to_config_file;
</code>```

Always, always, avoid reusing variables (apart from using the same variable in multiple iterations of a loop):

```<code>// Do not do this:
val = get_value_from_user();
val = val*100; // Convery from cm to m
val = normalise_val_for_calc(val);

// Instead try this:
len_cm = get_value_from_user();
len_m = len_cm * 100;
len_normalised = normalise_val_for_calc(len_m);
</code>```

I've had, much, much more mistakes from doing #1 and forgetting which individual value was which than from accidentally re-using a variable later in a function

I find this more important than limiting scope, certainly not a good solution to it!

I think most languages than use scope (C and C++, and I think C#, perl, python, etc, although I don't know for sure) let you open a new block. It's especially useful in C++ where a variable going out of scope automatically clears up any memory or filehandles etc it stores (RAII).

For instance, in C++:

```<code> int main() {
      int len_m;
      {
           // long calculation with many temporary variables
           // consider moving this to a separate function
           // but it's ok here under some circumstances
           len_m = blah
      }
      // temporary variables have gone away
      // do stuff with len_m
 }
</code>```

(That's not perfect because you have to declare the variable before the block, and initialise it during, but it's sometimes useful. Some scripting lanuages will let you use an ad-hoc function instead, len_m = { /* calculation */ }...)

ContentLicense: CC BY-SA 3.0

Body:
You are quite correct to limit the scope of variables if you can. It's best to simply use short functions, but if you have several variables only used for a few lines, it can make sense to make a scope around them. However, it's a bit ugly in most languages I know, and the benefits are comparatively small if you follow the advice below, so most people don't bother most of the time.

However, you definitely should:

If you have a one-off variable, give it a longer name you're unlikely to use again accidentally, eg:

path_to_config_file = "blah/blah/blah";
cfg_fileh = open path_to_config_file;

Always, always, avoid reusing variables (apart from using the same variable in multiple iterations of a loop):

// Do not do this:
val = get_value_from_user();
val = val*100; // Convery from cm to m
val = normalise_val_for_calc(val);

// Instead try this:
len_cm = get_value_from_user();
len_m = len_cm * 100;
len_normalised = normalise_val_for_calc(len_m);

I've had, much, much more mistakes from doing #1 and forgetting which individual value was which than from accidentally re-using a variable later in a function

I find this more important than limiting scope, certainly not a good solution to it!

I think most languages than use scope (C and C++, and I think C#, perl, python, etc, although I don't know for sure) let you open a new block. It's especially useful in C++ where a variable going out of scope automatically clears up any memory or filehandles etc it stores (RAII).

For instance, in C++:

 int main() {
      int len_m;
      {
           // long calculation with many temporary variables
           // consider moving this to a separate function
           // but it's ok here under some circumstances
           len_m = blah
      }
      // temporary variables have gone away
      // do stuff with len_m
 }

(That's not perfect because you have to declare the variable before the block, and initialise it during, but it's sometimes useful. Some scripting lanuages will let you use an ad-hoc function instead, len_m = { /* calculation */ }...)


问:
Is ORM an Anti-Pattern?
I had a very stimulating and interessting discussion with a colleague about ORM and its pros and cons. In my opinion, an ORM is useful only in the rarest cases. At least in my experience.

But I don't want to list my own arguments at this time. So I ask you, what do you think about ORM? What are the pros and the cons?

答:
My experience: I'm using NHibernate with Linq2NHibernate.

Pros:

It gets rid of "Magic Strings", or at least offers a once-and-only-once place to put them

It allows me to work in an OO paradigm the entire time

The code is easier to read

The code built on top is easier to change

It allows you to swap out your actual relational database without maintaning 2 separate repositories (rarely done, but that's one big benefit if you need it).

Cons:

The code is harder to write, because

It is not a sufficient abstraction -- you still have to be intimately familiar with what it's doing in the background

I will say that it doesn't live up to the promise that most people initially hope for.  I wouldn't blame someone for saying that it's an anti-pattern.  I find, in my case, that I still need to do integration tests against a SQLite database to make sure that my Linq2NHibernate queries actually work.  So really, if you're doing integration tests against a real relational database anyway, then that kind of eliminates the problem with "magic strings".

If I were to start a new project, I'm not sure if I'd use an ORM or not.  I probably would, but I can't say for sure you should.  I would say it's like the difference between choosing C++ or Java/.NET for your project: are you going to need the flexibility you get with working at a lower level, or would you rather work at a higher level and (supposedly) be more productive?  The normal answer is to work at as high of a level as you can get away with.  That usually means using an ORM.

Title: Is ORM an Anti-Pattern?


问:
Trying to learn how to use WCF services in a WPF app, using MVVM
We're working on a major re-write of a legacy VB6 app, into a WPF app.  I've written several WCF services, which are meant to be used with the new WPF app.  We want to use the MVVM design pattern to do this, but we don't have experience at that.  So, in order to learn MVVM we've watched a video on WindowsClient called How Do I: Build Data-driven WPF Application using the MVVM pattern. This is a great introduction, and we refer to it a lot, but for our situation it doesn't quite give us enough.  For example, we're not certain how to use datasets returned by my WCF services in our new WPF app using the ideas that Todd Miranda introduced in the video I referenced.  If we did as we think we're supposed to do, then we should design a class that is exactly like the class of data returned in my WCF service.  But we're wondering, why do that, when the WCF service already has such a class?  And yet, the class in the WPF app has to at least implement the INotifyPropertyChanged interface.  So, we're not sure what to do.</p>

答:
WCF's data objects should ideally be light-weight data transfer objects only. I would only re-use WCF's data objects if:

My Models are always going to be simple POCO objects. No validation, no business logic, no property change notification, etc

I don't care that the entire class as visible and fully accessible to whoever used it (You can't have read-only properties in a WCF data model)

My View does not bind directly to the Model, and instead binds to ViewModel properties which expose Model properties. This is the "MVVM-purist" approach, however if it often more trouble to implement than it is worth, so binding your View to your Model is also acceptable

That being said, I have never actually used WCF data objects as my Models. Usually I create Model objects separately, and my client-side data access layer converts the WCF data objects into Models for my application to use.

I usually use something Automapper for this, which will automatically map data from one class to another, providing the names and types are the same.


答:
ORM is a tool. Like all tools, when used appropriately, they work quite well. When used inappropriately, it needs a bigger hammer and some duct tape. </p>

<p>In the case of the current project I'm working on, it will be maintained by non-developers (mechanical engineers, to be precise) and so it needs to be simple and easy to figure out. It will be several years before this group has a budget to hire developers (presuming the next President doesn't abolish the agency involved), so the future maintenance capabilities is a major factor in our considerations. </p>

Title: Is ORM an Anti-Pattern?

Body:
I had a very stimulating and interessting discussion with a colleague about ORM and its pros and cons. In my opinion, an ORM is useful only in the rarest cases. At least in my experience.

But I don't want to list my own arguments at this time. So I ask you, what do you think about ORM? What are the pros and the cons?

Body:
ORM is a tool. Like all tools, when used appropriately, they work quite well. When used inappropriately, it needs a bigger hammer and some duct tape.

In the case of the current project I'm working on, it will be maintained by non-developers (mechanical engineers, to be precise) and so it needs to be simple and easy to figure out. It will be several years before this group has a budget to hire developers (presuming the next President doesn't abolish the agency involved), so the future maintenance capabilities is a major factor in our considerations.


答:
The strength of an ORM is that it allows you to model application behavior using object-oriented techniques. In a carefully engineered world, you have one layer of the application where the language of the business neatly meets the language of the development team. The ORM is an enabler of that, if the ORM is used sensibly.

The weakness is that the number of people who actually really, really get object-oriented programming is pretty small. A lot of people write spaghetti and meatballs, with highly coupled objects that have little behavior of their own and the actually behavior ends up in hideous 8000-line "Service" and "Manager" classes, and that code is often so convoluted that everyone's afraid of changing it because they can't figure out what the side effects will be.

Additionally, a lot of people don't really get the relational model. An ORM will not help them get it, and it won't help them by abstracting out the relational model. It just allows you to focus on your domain layer early on and get that right before you start getting too concerned about the database design. If applied well, with the help of sensible schema migration tools, and ORM can help you prevent code debt from building up.

I've built applications in which an ORM kept application code simple, readable, and testable, and had reasonable performance. I've also maintained applications where the pattern was misused and the code was convoluted, untestable, slow, and fragile; it turns out the ORM itself had little to do with this, except that instead of writing bad code that poorly modeled the application domain, the legacy engineering team wrote bad code that poorly modeled the application domain AND bad service-layer code that neglected all of the value that their ORM could provide them.

ORMs won't make you smarter, but in the hands of the right developer, can lead to more maintainable and higher-quality code.

Title: Is ORM an Anti-Pattern?


问:
What are the differences between the Unified Process and the Rational Unified Process?
Are there any differences between the Rational Unified Process (RUP) and the Unified Process (UP)? What does "Rational" mean, in this context?</p>

答:
The Unified Process is a generic name for a family of process models that meet a number of criteria, such as being iterative and incremental, driven by use cases, and focus on addressing risks early. It defines four project phases: Inception, Elaboration, Construction, and Transition.

The Rational Unified Process is a refinement of the Unified Process that was created by Rational Software (now owned by IBM). It uses a series of software tools along with a process framework to define how to carry out the activities needed to run a software project, yet still provides a framework for tailoring to meet an organization's (or team's) needs.

Other refinements on the Unified Process include Scott Ambler's Agile Unified Process and the Eclipse Foundation's Open Unified Process.


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

Returning null is usually the best idea if you intend to indicate that
no data is available.

An empty object implies data has been returned, whereas returning null
clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you
attempt to access members in the object, which can be useful for
highlighting buggy code - attempting to access a member of nothing
makes no sense. Accessing members of an empty object will not fail
meaning bugs can go undiscovered.

Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.


答:
Return null if you need to know if the item exists or not. Otherwise, return the expected data type. This is especially true if you're returning a list of items. It's usually safe to assume if the caller is wanting a list, they'll want to iterate over the list. Many (most? all?) languages fail if you try to iterate over null but not when you iterate over a list that is empty.

I find it frustrating to try and use code like this, only to have it fail:

```<code>for thing in get_list_of_things() {
    do_something_clever(thing)
}
</code>```

I shouldn't have to add a special case for the case when there are no things.

Title: Is it better to return NULL or empty values from functions/methods where the return value is not present?

Body:
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

Body:
Return null if you need to know if the item exists or not. Otherwise, return the expected data type. This is especially true if you're returning a list of items. It's usually safe to assume if the caller is wanting a list, they'll want to iterate over the list. Many (most? all?) languages fail if you try to iterate over null but not when you iterate over a list that is empty.

I find it frustrating to try and use code like this, only to have it fail:

for thing in get_list_of_things() {
    do_something_clever(thing)
}

I shouldn't have to add a special case for the case when there are no things.


答:
It depends on the semantics of the method. You could possibly specify, your method accepts only "Not null". In Java you can declare that using some metadata annotations:

string ReverseString(@NotNull String stringToReverse)
```

<p>You should somehow specify the return value. If you declare, you accept only NotNull values, you are bound to return empty string (if the input was empty string too).</p>

<p>The second case is a little bit complicated in its semantics. If this method is to return some person by it's primary key (and the person is expected to exist), better way is to throw exception.</p>

<pre class="lang-java prettyprint-override"><code>Person FindPerson(int personID)
</code>```

If you search person by some guessed id (which seems to me odd), you would better declare that method as @Nullable.

Body:
It depends on the semantics of the method. You could possibly specify, your method accepts only "Not null". In Java you can declare that using some metadata annotations:

string ReverseString(@NotNull String stringToReverse)

You should somehow specify the return value. If you declare, you accept only NotNull values, you are bound to return empty string (if the input was empty string too).

The second case is a little bit complicated in its semantics. If this method is to return some person by it's primary key (and the person is expected to exist), better way is to throw exception.

Person FindPerson(int personID)

If you search person by some guessed id (which seems to me odd), you would better declare that method as @Nullable.


答:
You could try Martin Fowler's Special Case pattern, from Paterns of Enterprise Application Architecture:

Nulls are awkward things in object-oriented programs because they
  defeat polymorphism. Usually you can invoke foo freely on a variable
  reference of a given type without worrying about whether the item is
  the exact type or a sub-class. With a strongly typed language you can
  even have the compiler check that the call is correct. However, since
  a variable can contain null, you may run into a runtime error by
  invoking a message on null, which will get you a nice, friendly stack
  trace.

If it's possible for a variable to be null, you have to remember to
  surround it with null test code so you'll do the right thing if a null
  is present. Often the right thing is same in many contexts, so you end
  up writing similar code in lots of places - committing the sin of code
  duplication.

Nulls are a common example of such problems and others crop up
  regularly. In number systems you have to deal with infinity, which has
  special rules for things like addition that break the usual invariants
  of real numbers. One of my earliest experiences in business software
  was with a utility customer who wasn't fully known, referred to as
  "occupant." All of these imply altering the usual behavior of the
  type.

Instead of returning null, or some odd value, return a Special Case
  that has the same interface as what the caller expects.


答:
Perhaps the answer lies in the converse of your question: Is storing your application data in something other than a relational database a good idea?  What problems are you eliminating, and what other problems will you pick up?  Can you live without the ability to easily cross-reference your data (joins) or quickly filter out the records you want based on multiple criteria?  Do you not need solid transaction support (assuming your alternative doesn't have it)?  Not all applications need an always-consistent-and-complete data store.

I think the real anti-pattern here may be using a relational DB when you don't need one.  If you need one, then you need ORM, and it's definitely not an anti-pattern.

Title: Is ORM an Anti-Pattern?


答:
In all the code I write, I avoid returning null from a function.  I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);
```

<p>Now I know people have said they <em>hate</em> the <code>Try...</code> pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:</p>

<pre class="lang-csh prettyprint-override"><code>class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);
</code>```

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework.  That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);
```

...and then I'd throw an exception if it was invalid.  The Get... prefix implies that the caller knows it should succeed.

Body:
In all the code I write, I avoid returning null from a function.  I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);

Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:

class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework.  That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);

...and then I'd throw an exception if it was invalid.  The Get... prefix implies that the caller knows it should succeed.


问:
How can I convince my managers to enforce documentation standards?
I'm trying to convince another group in my company— that's about to hand code off to my group—that they need to provide more documentation in their source code,  but they're treating it as a "nice to have".

In my view, it's a necessity. Of course, I also support intuitive naming conventions, but I think I'll have less difficulty getting the original authors to add comments than I would getting them to rename their functions and variables.

I've run a source code analysis tool and it's showing about 10% comment line, but looking at the source code, most of that is coming from entire functions that the author has commented out.

How can I convince my managers to enforce documentation standards on this other team? Have there been studies or work done to prove that code documentation increases profitability or productivity?

答:
The problem is that the issue is subjective. You will always have people who think you should write code so clear it doesn't need comments or that any good programmer worth his salt should be able to decipher your algorithms.

If someone believes you don't need comments you are likely not going to convince them. You can only hope to convert the indifferent and get non-believers to follow suit by simply being outnumbered. Which might mean leading by example of taking time to do it yourself and showing the difference/benefit after you have enough to compare and contrast.

One solution might be to promote the adoption of something like doxygen. The benefit being browsable documentation for future team members to browse. This only achieves interface level comments and not implementation level but once you get the ball rolling it's easier to grow from there than with nothing in place.

Otherwise you will just have to build documentation in your favor. Referring to multiple best practices blogs or company blogs. Google says it is important, so it must be!

Ultimately it is you against an established culture and you may not succeed.

Good luck!

ContentLicense: CC BY-SA 4.0


问:
How do you keep SOA DRY?
In our organization, we've shifted to a more "service oriented architecture". To give an example, let's assume we need to retrieve a "Quote" object. This quote has a shipper, a consignee, phone numbers, contacts, email addresses, and other location information. In other words, a Quote object is made up of many other objects.

So, it seems like it would make sense to make a "Quote Retrieval Service". In our situation, we've accomplished this by creating a .NET solution and writing the service. The service API looks something like this (in pseudo-code):

```<code>Function GetQuote(String ID) Returns Quote
</code>```

So, so far so good. Now, when this service is consumed, to keep things "de-coupled", we are creating essentially a duplicate of the Quote object and mapping from the QuoteService version of the Quote into the consumer's version of the Quote. In many cases, these classes will have the exact same properties.

So, if the Quote service is consumed by 5 other applications, we would have 6 definitions of what a "Quote" is. One for each consumer, and one for the service. This feels wrong. I thought code was supposed to be DRY, but it seems like our method of SOA is forcing us to create tons of duplicated class definitions. What are we doing wrong, or is the code duplication just a "necessary evil" of SOA?

答: You should not be handcoding the duplicated definition in the consumer. Instead use a tool like Visual Studios to import a reference to the web service a machine generated proxy class. There is repeated code, but it is machine generated and you don't have to maintain it, just reimport when the master definition changes.</p>

Title: How do you keep SOA DRY?


答:
If you're having to many variables in a scope, it's probably an indication that too much is happening in that scope.

Take this:

```<code>regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )
</code>```

Make it this (assuming JS here):

```<code>function matchAnyOf() {
    var parts = [];
    for (var i = 0; i < arguments.length; i++)
        parts = parts.concat(arguments[i]);
    return new RegExp(parts.join('|'));
}
//And any of these self-explanatory oneliners will do what you want
regexp = matchAnyOf('foo', 'bar');
regexp = matchAnyOf(['foo', 'bar']);
regexp = matchAnyOf('foo|bar');//granted, this won't work if you choose to escape '|' in matchAnyOf (which probably makes sense)
</code>```

Before, you had a helper variable, which cluttered your scope, now you have an isolated, reusable function (notice how parts no longer requires a prefix in contrast to regexp_parts, because context is now very clear) instead.

I assume such a thing is possible for the file example, although more context would be necessary, because as is, I would say that a variable who's sole purpose is to store a literal which is being used exactly once is a bit of an overkill ;)

Title: Is it OK to use dynamic typing to reduce the amount of variables in scope?

Body:
Often, when I am initializing something I have to use a temporary variable, for example:

```<code>file_str = "path/to/file"
file_file = open(file)
</code>```

or

```<code>regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )
</code>```

However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body.

In these initialization cases, if I am using a dynamic language, I am then often tempted to reuse the same variable in order to prevent the initial (and now useless) value from being used latter in the function.

```<code>file = "path/to/file"
file = open(file)

regexp = ['...', '...']
regexp = new RegExp( regexp.join('|') )
</code>```

The idea is that by reducing the number of variables in scope I reduce the chances to misuse them. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename".

I think perhaps this would be a non issue if I could use non-nested scopes

```<code>begin scope1
   filename = ...
begin scope2
   file = open(filename)
end scope1
   //use file here
   //can't use filename on accident
end scope2
</code>```

but I can't think of any programming language that supports this.

What rules of thumb should I use in this situation?

When is it best to reuse the variable?

When is it best to create an extra variable?

What other ways do we solve this scope problem?

Body:
If you're having to many variables in a scope, it's probably an indication that too much is happening in that scope.

Take this:

regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )

Make it this (assuming JS here):

function matchAnyOf() {
    var parts = [];
    for (var i = 0; i < arguments.length; i++)
        parts = parts.concat(arguments[i]);
    return new RegExp(parts.join('|'));
}
//And any of these self-explanatory oneliners will do what you want
regexp = matchAnyOf('foo', 'bar');
regexp = matchAnyOf(['foo', 'bar']);
regexp = matchAnyOf('foo|bar');//granted, this won't work if you choose to escape '|' in matchAnyOf (which probably makes sense)

Before, you had a helper variable, which cluttered your scope, now you have an isolated, reusable function (notice how parts no longer requires a prefix in contrast to regexp_parts, because context is now very clear) instead.

I assume such a thing is possible for the file example, although more context would be necessary, because as is, I would say that a variable who's sole purpose is to store a literal which is being used exactly once is a bit of an overkill ;)


问:
is there a term for doing this: func1(func2(), func3());
I know that obj.func1().func2() is called method chaining, but what is the technical term for:

```<code>func1(func2(), func3());
</code>```

Where return of a function is used as an argument to another.

答:
I really am not that good with terms, but I just read an article a few days ago that referred to the term Higher order functions, and here's an abstract of the definition per Wikipedia:

http://en.wikipedia.org/wiki/Higher-order_function

In mathematics and computer science, higher-order functions,
functional forms, or functionals are functions which do at least one
of the following:

take one or more functions as an input

output a function

All other functions are first-order functions. In mathematics
higher-order functions are also known as operators or functionals. The
derivative in calculus is a common example, since it maps a function
to another function.

so in this case, since that scenario does take at least one function as an input/param, it'd be considered a higher order function, i believe.


答:
JGWiessman is correct in that the lack of DRYness in auto-generated proxies is not costly, because you do not maintain the client's generated code. Change it on the server, update your references on the clients, job done.

However, there is an alternative, if both the client and the server are .NET. You can put all your objects in a separate assembly, referenced by both the client and server. If you then auto-generate the client code, it is simply an interface, using the same objects that the server uses.

Only do this if the objects you are sharing are dumb data objects and don't include any server-side code though, otherwise you're exposing that code to your client.

If both client and server are using the same version of .NET, you can take this one step further and include the interface purely by configuration. But you need to be careful here. The interface on the server side requires the ServiceContract attribute and thus references the ServiceModel assembly, so if the versions are different, you can get into trouble.

Title: How do you keep SOA DRY?

Body:
In our organization, we've shifted to a more "service oriented architecture". To give an example, let's assume we need to retrieve a "Quote" object. This quote has a shipper, a consignee, phone numbers, contacts, email addresses, and other location information. In other words, a Quote object is made up of many other objects.

So, it seems like it would make sense to make a "Quote Retrieval Service". In our situation, we've accomplished this by creating a .NET solution and writing the service. The service API looks something like this (in pseudo-code):

```<code>Function GetQuote(String ID) Returns Quote
</code>```

So, so far so good. Now, when this service is consumed, to keep things "de-coupled", we are creating essentially a duplicate of the Quote object and mapping from the QuoteService version of the Quote into the consumer's version of the Quote. In many cases, these classes will have the exact same properties.

So, if the Quote service is consumed by 5 other applications, we would have 6 definitions of what a "Quote" is. One for each consumer, and one for the service. This feels wrong. I thought code was supposed to be DRY, but it seems like our method of SOA is forcing us to create tons of duplicated class definitions. What are we doing wrong, or is the code duplication just a "necessary evil" of SOA?


答:
I would think ReverseString() would return the reversed string and it would throw an IllegalArgumentException if passed in a Null.

I think FindPerson() should follow the NullObject Pattern or raise an unchecked exception about not finding something if you should always be able to find something.

Having to deal with Null is something that should be avoided. Having Null in languages has been called a Billion Dollar Mistake by it's inventor!

I call it my billion-dollar mistake. It was the invention of the null
  reference in 1965. At that time, I was designing the first
  comprehensive type system for references in an object oriented
  language (ALGOL W).

My goal was to ensure that all use of references should be absolutely
  safe, with checking performed automatically by the compiler. But I
  couldn't resist the temptation to put in a null reference, simply
  because it was so easy to implement.

This has led to innumerable errors, vulnerabilities, and system
  crashes, which have probably caused a billion dollars of pain and
  damage in the last forty years.

In recent years, a number of program analysers like PREfix and PREfast
  in Microsoft have been used to check references, and give warnings if
  there is a risk they may be non-null. More recent programming
  languages like Spec# have introduced declarations for non-null
  references. This is the solution, which I rejected in 1965.

Tony Hoare


问:
Introducing Programming To a Mathematician
I currently am a programmer, I'm almost 16 years of age and have pretty much narrowed my careers down to something involving a Computer Science degree or Electrical Engineering degree (I know they are quite different but this question is about my friend) but my friend isn't so sure.

He is very interested in maths and is very good at it and I think he would enjoy programming but he isn't willing to try it (edit he is willing to try but has never done before). Can anyone give me an suggestions for a language or tool that he could dabble in programming (at a reasonably basic level I assume) to solve maths problems or involve some kind of maths.

As I say he enjoys maths a lot but I think he would enjoy programming, the problem is I don't want him to be put off by the stuff that isn't relevant at introductory levels such as memory allocation et al. I know that is very important but the point is that I want him to learn a bit of programming with maths then hopefully if he is interested enough he can start learning programming as programming.

Edit:
Its not that he's completely uninterested - more that he hasn't actively explored the area before, maybe because he isn't informed about it. I wouldn't want to force him to do something he doesn't want to, I see this as more of a little push so that he can learn about programming. If he doesn't like it - fair enough, I can't control that and don't want to but if he turns out to enjoy it - this push will have been the right thing.

答:
As someone who studied math (I have a B.S. in pure mathematics and just received my M.S. in Applied Math/Statistics) and later realized the fun/practicality/importance of programming further along in my career, I really appreciate this question. I wish I had a friend like you 10 years ago to push me towards programming.

You should both check out Project Euler. What is it?

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

Although it is not a language specific suggestion, it would be a great motivator for getting started with programming (especially if there is already an interest in math). The problems start off very easy and approachable but quickly become very tricky and/or difficult. A good challenge and motivation that you both are likely to enjoy.

As for which language to use, I have experience with C++, R, Matlab and Mathematica which are all great and widely used within the math community. But more specifically, I strongly suggest learning Python which is very useful for math but isn't quite as restricted to math as some of the others (in case he wants more options later on in life). It is easy to get started with Python but there are tons of things to learn. It's also free unlike some of the others. C++ might be a good choice as well but could have more hurdles from the beginning.


问:
Releasing an open source project without getting embarrassed
I've been working by myself on a fairly large open source project for quite a while and it's nearing the point where I'd like to release it. However, I'm self-taught and I don't really know anyone who could adequately review my project.

A few years ago, I had released a small bit of code which pretty much got ripped apart (in a critical sense) on the forum where I released it. Even though the code worked, the criticism was accurate but brutal. It prompted me to begin searching for best practices for everything and in the end I feel that it made me a much better developer. I've gone over everything in my project so many times trying to make it perfect that I've lost count.

I believe in my project and think it has the potential to help a lot of people and I feel like I've done some cool things in interesting ways with it. Still, because I'm self-taught, I can't help but wonder what gaps exist in my self-education. The way my code was ripped apart last time isn't something I'd like to repeat. I think my two biggest fears with releasing my project that I've poured countless hours into are being absolutely embarrassed because I missed some patently obvious things because of my self-education or, worse, releasing it to the sound of crickets.

Is there anyone who has been in a similar situation? I'm not afraid of constructive criticism, so long as it is constructive and not just a rant on how I screwed up. I know there is a code review site on StackExchange, but it's not really set up for large projects and I didn't feel like the community there is large enough yet to get good feedback if I were to post parts of my project piecemeal (I tried with one file). What can I do to give my project at least some measure of success without getting embarrassed or devestated in the process?

答:
Some wise words from Reid Hoffman, co-founder of LinkedIn:

“If you’re not embarrassed by your first product release, you’ve released too late.”

“Getting engagement with members and seeing what is actually important is completely key… So you get out the minimum viable product as soon as you can.”

I think this especially applies to open source projects where having a great idea with a promising start encourages people to contribute and participate. Something that's so polished it makes you put on your sunglasses might not evoke such feelings. But the most important thing about releasing early is to shatter all your preconceptions about what should be done and start moving in the right direction.


答:
If all else fails, I've always been able to get to DRY code by code generation.  pdr has a good solution for when what you want to do fits with what Microsoft gives you, but if it doesn't you can always do your own code generation.

Then you can handle things like code generating for clients not using .NET, making explicit, coded rules like "Client B gets the generic client version of Quote except the email address, but they add a carrier pigeon homing code field", (rather than manually adding new fields to all 302 client's services) etc.

Title: How do you keep SOA DRY?


答:
I see both sides of this argument, and I realize some rather influential voices (e.g., Fowler) advocate not returning nulls in order to keep code clean, avoid extra error-handling blocks, etc.

However, I tend to side with proponents of returning null. I find there is an important distinction in invoking a method and it responding with I don't have any data and it responding with I have this empty String.

Since I've seen some of the discussion referencing a Person class, consider the scenario where you attempt to look up an instance of the class. If you pass in some finder attribute (e.g., an ID), a client can immediately check for null to see if no value was found. This is not necessarily exceptional (hence not needing exceptions), but it should also be documented clearly. Yes, this requires some rigor on the part of the client, and no, I don't think that's a bad thing at all.

Now consider the alternative where you return a valid Person object... that has nothing in it. Do you put nulls in all of its values (name, address, favoriteDrink), or do you now go populate those with valid but empty objects? How is your client to now determine that no actual Person was found? Do they need to check if the name is an empty String instead of null? Isn't this sort of thing actually going to lead to as much or more code clutter and conditional statements than if we'd just checked for null and moved on?

Again, there are points on either side of this argument I could agree with, but I find this makes the most sense to the most people (making the code more maintainable).


问:
Is error suppression acceptable in role of logic mechanism?
This came up in code review at work in context of PHP and @ operator. However I want to try keep this in more generic form, since few question about it I found on SO got bogged down in technical specifics.

Accessing array field, which is not set, results in error message and is commonly handled by following logic (pseudo code):

```<code>if field value is set
   output field value
</code>```

Code in question was doing it like:

```<code>start ignoring errors
output field value
stop ignoring errors
</code>```

The reasoning for latter was that it's more compact and readable code in this specific case. I feel that those benefits do not justify misuse (IMO) of language mechanics.

Is such code is being "clever" in a bad way?

Is discarding possible error (for any reason) acceptable practice over explicitly handling it (even if that leads to more extensive and/or intensive code)?

Is it acceptable for programming operators to cross boundaries of intended use (like in this case using error handling for controlling output)?

Edit

I wanted to keep it more generic, but specific code being discussed was like this:

```<code>if ( isset($array['field']) ) {
    echo '<li>' . $array['field'] . '</li>';
}
</code>```

vs the following example:

```<code>echo '<li>' . @$array['field'] . '</li>';
</code>```

答: I don't think this is acceptable for code deployed to production. In development and testing stages, this might be OK if there are errors you are expecting and want to avoid for now, but suppressing errors will eventually lead to important errors getting suppressed and at that point, debugging will get a lot harder because any error message that would otherwise alert you to something bad happening has been suppressed and you might not even know where to start looking.


问:
What, if anything, to do about bow-shaped burndowns?
I've started to notice a recurring pattern to our team's burndown charts, which I call a "bowstring" pattern.  The ideal line is the "string" and the actual line starts out relatively flat, then curves down to meet the target like a bow.

My theory on why they look like this is that toward the beginning of the story, we are doing a lot of debugging or exploratory work that is difficult to estimate remaining work for.  Sometimes it even goes up a little as we discover a task is more difficult once we get into it.  Then we get into implementation and test which is more predictable, hence the curving down graph.  Note I'm not talking about a big scale like BDUF, just the natural short-term constraint that you have to find the bug before you can fix it, coupled with the fact that stories are most likely to start toward the beginning of a two-week iteration.

Is this a common occurrence among scrum teams?  Do people see it as a problem?  If so, what is the root cause and some techniques to deal with it?

答:
If it is consistent and predictable, I don't see it as being a problem.

Unless you detect that this is causing your quantifiable project harm, are there not more pressing issues to spend time considering? If there are not, I am envious of you :)


答:
It's an extremely bad habit:

Code is essentially un-testable: I can barely understand people that don't unit test, but altogether suppress errors?

It carries a performance penalty, something that's addressed in php5.4.

The operator will suppress critical errors, that lead to script exit (good luck finding that mistyped function name)

As for your specific questions:

Is such code is being "clever" in a bad way?

Yes it is, it's a prime example of being "clever". We're using a PHP_CodeSniffer pre-commit hook to detect such "cleverness".

Is discarding possible error (for any reason) acceptable practice over explicitly handling it (even if that leads to more extensive and/or intensive code)?

There is only one acceptable scenario for error suppression, and that's when your intention is to catch the error and throw an exception instead. Especially when you suppress a third party or undocumented function.

Is it acceptable for programming operators to cross boundaries of intended use (like in this case using error handling for controlling output)?

I've seen error suppression being used instead of isset, as discussed in this article. The performance penalty alone makes it a bad practice.

Update: It seems that MikeSchinkel took the time to verify if there's actually a performance hit when using error suppression, and it's a fairly significant one*:

It is slower, but not in all cases; the case where it exists it can be faster. Where it is slower it can be up to ~5 times slower, but typically more like ~3 times slower

Any approach that's potentially 5 times slower than another approach, without adding any other value whatsoever, is of course counter-intuitive, to say the least.

* Extracted from the comments. The script is extremely inaccurate, as all tests are run on the same script, but it does give a general idea.

Title: Is error suppression acceptable in role of logic mechanism?

Body:
This came up in code review at work in context of PHP and @ operator. However I want to try keep this in more generic form, since few question about it I found on SO got bogged down in technical specifics.

Accessing array field, which is not set, results in error message and is commonly handled by following logic (pseudo code):

```<code>if field value is set
   output field value
</code>```

Code in question was doing it like:

```<code>start ignoring errors
output field value
stop ignoring errors
</code>```

The reasoning for latter was that it's more compact and readable code in this specific case. I feel that those benefits do not justify misuse (IMO) of language mechanics.

Is such code is being "clever" in a bad way?

Is discarding possible error (for any reason) acceptable practice over explicitly handling it (even if that leads to more extensive and/or intensive code)?

Is it acceptable for programming operators to cross boundaries of intended use (like in this case using error handling for controlling output)?

Edit

I wanted to keep it more generic, but specific code being discussed was like this:

```<code>if ( isset($array['field']) ) {
    echo '<li>' . $array['field'] . '</li>';
}
</code>```

vs the following example:

```<code>echo '<li>' . @$array['field'] . '</li>';
</code>```


问:
How does PHP5 fare with earlier versions of the language
I would like to learn PHP for web development but have been drawn back because of comments like the following*:

PHP is good but generates spaghetti code

PHP is nice but Python is marriage material

PHP lacks stuff that you get in other languages like C# or Java

But for PHP5 I have seen some promising comments. So, my question is: How does PHP5 fare with earlier versions of the language and is it good enough now to learn for web development.

* Comments are just for reference not to incite a flame war. No comparison of PHP with other languages is asked for here. Please comment just on PHP5 and how it compares with earlier versions.

答: PHP has some significant issues within itself, but those are primarily of the annoyance variety: Its library is inconsistent and somewhat schizophrenic, it lacks strings as first class objects, things like that. It does not force you to write poor code, and it does work fairly well for what it does -- write web pages. Your PHP will be as good as you strive for it to be; it's quite possible to write PHP that's terribly procedural and looks like C code, and it's quite possible to write PHP that's overly Object Oriented and looks like Java. As someone who develops in PHP daily, I like some things about it and hate some things about it and can't wait for some 5.4 functions (like Traits and sane function return dereferencing), but I'd wholeheartedly encourage someone who's thinking about picking it up to do so.</p>


问:
How to improve your ability to debug existing code
A common task in the working world is dealing with existing, but buggy code. What are some tips to improve your skills as a debugger?</p>

答:
Know your tools.  For example, Visual Studio's debugger has an awesome feature called TracePoints that are like breakpoints but instead of stopping your code instead inserts a trace statement into the debug output.

Reading books or taking a class on how to use your debugger is highly recommended.  I took a couple of classes and read a few books by John Robbins that made a big difference in my effectiveness as a debugger.

ContentLicense: CC BY-SA 2.5


答:
I personally prefer a slightly different approach. I'm convinced that in enterprise of a large size, business domain is way too large, so the DDD is the way to go. When the entities on the service side (or whatever the tier service talks to) are defined in a way required for the service, the logic is defined to retrieve them from persistence and perform logic of any kind, it always provide a mapped entity (aka "binding context", "dto", "data contract" etc) which is the most suitable in size and internals "sibling" for the original entity, yet not bloated with the details that will never be exposed to the outer world.

Then, when the service is to be exposed, the contract of the service goes to a separate DLL (lightweight library that you can ship to a client, no logic inside, just interfaces). You also ship entity containing library to a client. Those two distinctly describe the conversation contract and the messages format.

If I feel that there are too few pairs to be shipped now, and they are of different structure, then this is not SOA anymore, because your blackbox-service is now telling too much about itself to the consumers and moreover the consumers ask blackbox-service to change it shape. I usually employ REST in this case to reduce problems with data contracts or override serialization methods on DTO objects and depending on supplied StreamingContext, provide a different shape of the entity.

Title: How do you keep SOA DRY?


问:
Why not Green Threads?
Whilst I know questions on this have been covered already (e.g. https://stackoverflow.com/questions/5713142/green-threads-vs-non-green-threads), I don't feel like I've got a satisfactory answer.

The question is: why don't JVM's support green threads anymore?

It says this on the code-style Java FAQ:

A green thread refers to a mode of operation for the Java Virtual
  Machine (JVM) in which all code is executed in a single operating
  system thread.

And this over on java.sun.com:

The downside is that using green threads means system threads on Linux
  are not taken advantage of and so the Java virtual machine is not
  scalable when additional CPUs are added.

It seems to me that the JVM could have a pool of system processes equal to the number of cores, and then run green threads on top of that.  This could offer some big advantages when you have a very large number of threads which block often (mostly because current JVM's cap the number of threads).

Thoughts?

答:
A single process faking multiple threads has a lot of problems. One of them is that all the faked threads stall on any page fault.

The alternative that you suggest, a pool of processes, has some advantages and some disadvantages. The biggest advantage, isolation of the 'threads', really wouldn't get you much here. The big disadvantage, extreme difficulty of implementation and less efficient synchronization, is the deal-killer here.

However, I do agree that there exist some applications (not Java) where a pool of processes that you could use like a pool of threads (but with more isolation) would be a great thing to have. Threads share pretty much everything. With processes, you can specifically choose what to share. To my knowledge, nobody has gone to the effort of implementing it yet.

Title: Why not Green Threads?


答:
I would recommend using the Null Object pattern whenever possible. It simplifies the code when calling your methods, and you don't get to read ugly code like

if (someObject != null && someObject.someMethod () != whateverValue)

For instance, if a method returns a collection of objects who fit some pattern, then returning an empty collection makes more sense than returning null, and iterating over this empty collection will have virtually no performance penalty. Another case would be a method that returns the class instance used to log data, returning a Null object rather than null is preferable in my opinion, as it does not force users to always check if the returned reference is null.

In cases where returning null makes sense (calling the findPerson () method for example), I'd try to at least provide a method that returns if the object is present (personExists (int personId) for example), another example would be the containsKey () method on a Map in Java). It makes callers' code cleaner, as you can easily see that there is a possibility that the desired object might not be available (person does not exist, key is not present in map). Constantly checking if a reference is null obfuscates the code in my opinion.


答:
One way to address this issue is to create smaller stories and realistically add research & debugging tasks. What my team has done is to break down stories so that they generally don't last for any more than two to three days.

If you create small stories that can be "consumed" rapidly and hold the usual daily meetings, your team should be able to quickly whittle away at the amount of work remaining in the sprint. Your burndown chart should start to reflect this state as well. Naturally, not all stories can be broken down like this, but if most of the stories are small, you'll probably see a more linear chart. I'm assuming that the devs will be closing tasks & stories as they wrap up work. My team usually does this before our daily scrum - the scrum master collects small fines from those that forget!

Title: What, if anything, to do about bow-shaped burndowns?

Body:
I've started to notice a recurring pattern to our team's burndown charts, which I call a "bowstring" pattern.  The ideal line is the "string" and the actual line starts out relatively flat, then curves down to meet the target like a bow.

My theory on why they look like this is that toward the beginning of the story, we are doing a lot of debugging or exploratory work that is difficult to estimate remaining work for.  Sometimes it even goes up a little as we discover a task is more difficult once we get into it.  Then we get into implementation and test which is more predictable, hence the curving down graph.  Note I'm not talking about a big scale like BDUF, just the natural short-term constraint that you have to find the bug before you can fix it, coupled with the fact that stories are most likely to start toward the beginning of a two-week iteration.

Is this a common occurrence among scrum teams?  Do people see it as a problem?  If so, what is the root cause and some techniques to deal with it?


问:
Is '@' Error Suppression a Valid Technique for Testing for an Optional Array Key?
Rarst and I were debating offline about the use of the '@' error suppression operator in PHP, specifically for use to test for existence of "optional" array keys, i.e. array keys that are being used as a switch here a their lack of existence in the array is functionally equivalent to the array having the key with a value equaling false.

Here is pseudo-code for this scenario:

```<code> function do_something( $args = array() ) {
   if ( @$args['switch'] ) {
      // Do something with this switch
   }
   // continue on...
 }
</code>```

vs. this approach:

```<code> function do_something( $args = array() ) {
   if ( ! empty( $args['switch'] ) && $args['switch'] ) {
      // Do something with this switch
   }
   // continue on...
 }
</code>```

Of course in most use-cases, suppressing errors would not be A Good Thing(tm). However in this use-case where an array is passed with an optional element, it seems to me that it is actually a very good technique but I could be wrong and would like to hear other's opinions on the subject before I make up my mind.

I do know that there are alleged performance hits for using the former approach but I'd like to know how they compare with the alternative and if they performance hits really matter in real world scenarios?

P.S. I decided to post this because, after debating this offline with Rarst, he asked a more general question here on Programmers but didn't actually give a detailed example of the specific use-case we were debating. And since I'm pretty sure he'll want to use the out-of-context answers on that other question as justification for why the above is "bad" I decided I needed to get opinions on this specific use-case.

答:
First, when talking about performance penalties, you cannot get a sensible answer unless there is context to where it is to happen.

To illustrate, is a 100ms delay to log a stackdump when a program terminates acceptable? More than likely.

Is that same 100ms delay acceptable in a tight loop that runs each time you process a record from 100 million? Of course not.

Second, how is someone to know you have suppressed the error because you are actually using it for logic-flow control as opposed to not knowing any better and just trying to implement 'See no evil'. Self-documenting code is better than needing explicit comments to assure people of your intentions.

Third, as noted by Yannis in the other question, you are really setting yourself up for failure because of the potential for unintended consequences.

So, for the sake of those poor souls that have to maintain your code in the future, just don't do it!

After all, what are you really gaining?


问:
Python MVC framework for desktop applications
I'm used to program with Python and GTK using pygtk library.

I feel like my programs are not well separated according to MVC model.
I think following a framework it would help me to design better desktop
applications.

I'd like to know which Python MVC framework for desktop apps you're using and
why.

答:
You don't need a framework. Create a class called Model, another one called View and a third one named Controller and start coding. Put all of the UI code in the View class, your data structures in the Model class, and make sure they communicate only via the Controller. I think going through that exercise might teach you a lot.

I'm not trying to be funny here, it's really not very complicated, and doesn't require a fancy framework.


答:
This is not an optimal SOA architecture.

The service provider should provide the same service for all consumers.

Consumers should use what they need from the Replies and ignore what they don't need.

I don't see why each consumer should need their own version of the service.

Even in the case of a security requirement that only some consumers are allowed to see certain data you can place this data in an optional group and simply not send it to unauthorized consumers. Thus preserving a single interface for all clients.

Title: How do you keep SOA DRY?


答:
There'll be no benefit at all for an average Java code. Java is not Erlang, and Java programmers are not in the same mindset as Erlang programmers. The language was never intended to be used this way.

If you want the true lightweight processess - use Erlang and create thousands of threads communicating via messages. In Java you'll have a dozen of threads sharing a common memory with mutexes and semaphores. It is just a different programming model, designed for a different set of problems.

Title: Why not Green Threads?

Body:
Whilst I know questions on this have been covered already (e.g. https://stackoverflow.com/questions/5713142/green-threads-vs-non-green-threads), I don't feel like I've got a satisfactory answer.

The question is: why don't JVM's support green threads anymore?

It says this on the code-style Java FAQ:

A green thread refers to a mode of operation for the Java Virtual
  Machine (JVM) in which all code is executed in a single operating
  system thread.

And this over on java.sun.com:

The downside is that using green threads means system threads on Linux
  are not taken advantage of and so the Java virtual machine is not
  scalable when additional CPUs are added.

It seems to me that the JVM could have a pool of system processes equal to the number of cores, and then run green threads on top of that.  This could offer some big advantages when you have a very large number of threads which block often (mostly because current JVM's cap the number of threads).

Thoughts?


问:
University teaches DOS-style C++, how to deal with it
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!

答:
They have to cater to the students. Most students can't program. So they're not pushed to go technical there.

They have their own specialised areas of research too, but they're not teaching that. And anyhow many researchers are not good teachers anyway, so you could consider yourself lucky if they're teaching stuff you already know!

Anyhow, you don't seem to know what computer science is. It's not about what's practical for industry.

OwnerDisplayName: gaidal


问:
What is the good explanation of Tennent's Correspondence Principle?
I found myself struggling to see what is this principle about and why is it so important for language design.

Basically, it states, that for every expression expr in language should be exactly the same as this construct:

```<code>(function () { return expr; })()
</code>```

Also, I have heard that Ruby obeys this principle, while Python doesn't. I don't understand why this is true, or if it is true at all.

答:
I have never heard before of "Tennent's Correspondence Principle" and even less of it being important in language design. Googling the expressions seems all to lead to one Neal Gafter blog of 2006  that lays down what he thinks it is and how he thinks it should apply to closures as well. And most all others in forums seem to refer to Gafter's entry.

Here is however a mentioning of said "T.C.P." by Douglas Crockford (a name i know and trust): http://java.sys-con.com/node/793338/ . In part

There are some things that can't be enclosed that way, such as return statements and break statements, which the advocates of Tennent's Correspondence Principle (or TCP) claim is a symptom of a bad smell. Yow! Language design is already difficult enough without having to cope with olfactory hallucinations. So to better understand the problem, I bought a copy of Tennent's 1981 book, Principles of Programming Languages.

It turns out that the Correspondence Principle is descriptive, not prescriptive. He uses it to analyze the (by now forgotten) Pascal programming language, showing a correspondence between variable definitions and procedure parameters. Tennent does not identify the lack of correspondence of return statements as a problem.

So seems therefore the name "Tennent's Correspondence Principle" is mis-used, and whatever Neal talks about possibly should be called "Gafter's Imagined and Possibly Generalized T.C.P."... or some such. In any event not enough to hide behind an out-of-print book name-curtain

OwnerDisplayName: Andrew


问:
How to increase the bus factor and specialize at the same time?
In agile pair programming it is recommended to switch pairs every now and then so as to increase the bus factor of the team. That means, most people in the team should work on different parts of the system at different times so that everyone has an understanding of it.

Now it is impssible that everyone has an expert level of understanding of each part of the system. That's because people are urged to specialize in one area of expertise. If you are an expert database admin, what's the point of working on the user interface of the system when you switch pairs? You will not be able to do such a high quality job as someone who has extensive experience in UI design.

How can you increase the bus factor and make sure that you have specialization in your team?

答:
For the main, I'd keep the pairs within discipline - so, UI guys would predominantly pair with another UI person, DB guys would pair with another DB person. If you only have one or two in a discipline, then so be it - you can't always pair when you don't have the numbers. You are right that a UI specialist would not want or be needed to fill in for a DB specialist.

But, it is a good idea to sometimes mix it up a bit - your web service experts might have an idea for the UI, or the UI might have an idea about the DB structure which would simplify something back up on the UI layer - a different perspective can be extremely useful.

Also, DB and UI are quite far apart on the chain - you would get some advantage of the middle layers pairing more frequently with either DB or UI.

As with any work methodology - pair programming isn't something to implement slavishly just to tick a box of to say "yeah, we've done that" - it's there as a tool, and needs thinking to implement.


答: Return an Option. All the benefits of returning a different invalid value (like being able to have empty values in your collections) without any risk of NullPointerException.</p>


问:
Threading models when talking to hardware devices
When writing an interface to hardware over a communication bus, communications timing can sometimes be critical to the operation of a device.
As such, it is common for developers to spin up new threads to handle communications.

It can also be a terrible idea to have a whole bunch of threads in your system, an in the case that you have multiple hardware devices you may have many many threads that are out of control of the main application.

Certainly it can be common to have two threads per device, one for reading and one for writing.

I am trying to determine the pros and cons of the two different models I can think of, and would love the help of the Programmers community.

Each device instance gets handles it's own threads (or shares a thread for a communication device). A thread may exist for writing, and one for reading. Requested writes to a device from the API are buffered and worked on by the writer thread. The read thread exists in the case of blocking communications, and uses call backs to pass read data to the application. Timing of communications can be handled by the communications thread.

Devices aren't given their own threads. Instead read and write requests are queued/buffered. The application then calls a "DoWork" function on the interface and allows all read and writes to take place and fire their callbacks. Timing is handled by the application, and the driver can request to be called at a given specific frequency.

Pros for Item 1 include finer grain control of timing at the communication level at the expense of having control of whats going on at the higher level application level (which for a real time system, can be terrible).

Pros for Item 2 include better control over the timing of the entire system for the application, at the expense of allowing each driver to handle it's own business.

If anyone has experience with these scenarios, I'd love to hear some ideas on the approaches used.

答:
There are three contesting patterns usually considered as concurrency patterns.

1. Active Object

If you take up the first approach - it is further possible to encapsulate the existence of thread "behind" the object (or context) and API still remains accessible for Application to be able to query and communicate. This is called as Active Object pattern. The primary read/write calls that application makes can be made blocking or non-blocking depending on requirement. However, making it non-blocking is where Active object pattern is a must.

2. Thread Pool

On the other hand, if there is a serious constraints on exact number of threads than an alternative pattern can be used called as "thread pool" pattern. This method requires that tasks needs to be clearly abstracted out and queued. Whenever a working thread finishes, takes next best task from the queue.

3. Asynchronous I/O

The third pattern is called Asynchronous I/O where which shows least coupling between IO performing tasks and the application.

Active object makes life of application quite easy. Where as thread pools is about disciplined execution. Asynchronous I/O is essentially to minimize all communication overhead (or rather assumes minimal communication).

There is a lot of literature on each of this subject so i am not going very long here - however, i would add if there are specific queries.

While, some of the pointers i have given are in JAVA, the patterns are pretty much implementation in C or C++.

These patterns are grounded on firm and validated principles (like most design patterns) that should help bring good focus on the design.


问:
Most readable way to format long if conditions?
Long winding if conditions should be avoided if at all possible, yet sometimes we all end up writing them. Even if it's a very simple condition, the involved statements are sometimes simply very wordy, so the whole condition ends up being very lengthy. What's the most readable way to format those?

```<code>if (FoobarBaz::quxQuux(corge, grault) || !garply(waldo) || fred(plugh) !== xyzzy) {
    thud();
}
</code>```

or

```<code>if (
    FoobarBaz::quxQuux(corge, grault)
 || !garply(waldo)
 || fred(plugh) !== xyzzy
) {
    thud();
}
</code>```

or

```<code>if (FoobarBaz::quxQuux(corge, grault)
    || !garply(waldo)
    || fred(plugh) !== xyzzy) {
    thud();
}
</code>```

or

```<code>thudable = FoobarBaz::quxQuux(corge, grault);
thudable ||= !garply(waldo);
thudable ||= fred(plugh) !== xyzzy;

if (thudable) {
    thud();
}
</code>```

or any other preferences?

答:
I break out the messier subexpressions, or all of them, as bool variables.  Then the top-level boolean logic of the 'if' statement can be made clear.  In the kind of work I do, it's not always several things ORed or ANDed.

```<code>bool goodblah = some_mess < whatever;
bool frobnacious = messy_crud != junky_expression;
bool yetanother = long_winded_condition;

if (goodblah || (frobnacious && yetanother))   {
    ...
}
</code>```

This is especially good in a debugger, where I can look at all the bools before executing the 'if'.

Body:
I break out the messier subexpressions, or all of them, as bool variables.  Then the top-level boolean logic of the 'if' statement can be made clear.  In the kind of work I do, it's not always several things ORed or ANDed.

bool goodblah = some_mess < whatever;
bool frobnacious = messy_crud != junky_expression;
bool yetanother = long_winded_condition;

if (goodblah || (frobnacious && yetanother))   {
    ...
}

This is especially good in a debugger, where I can look at all the bools before executing the 'if'.


问:
Why aren't postfix and primary expressions symmetrical?
Every primary expression is a postfix expression but a postfix expression is not primary expression.

But in mathematics, equality seems to be symmetrical. That is:

If A is B, then B is A

Why isn't this the case for postfix and primary expressions?

答:
But In mathematic sense, when A is B then B is also A.

Not necessarily. Any asymmetric relation fails that equation.

What kind of logic is applied in programming?

It depends what is being done. Mathematics logic would fit that best in signal processing.


问:
What's the benefit of object-oriented programming over procedural programming?
I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two.

I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these?

I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable.

Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well:

```<code>if ( login == "admin") {
    // invoke the function
}
</code>```

Why is this not ideal?

Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?

答: In one word, project management. What I mean is that C++ helps me enforce rules of how my code is used by others. Working on a 5.5 million lines project I find object oriented programming very helpful. Another advantage is the compiler that makes me (and everybody else) follow certain rules and catch minor errors in compile time. All the theoretical advantages are there as well but I just wanted to focus on everyday practical things. After all it all compiles into machine code.</p>


问:
Being prepared for a code review as a developer?
I am looking for some ideas here.

I read the article How should code reviews be Carried Out and Code Reviews, what are the advantages? which were very informative but I still need more clarity on the question below.

My Question is,

Being the target developer, can you suggest some best practices a developer can incorporate before his code is going get reviewed.

Currently I practice the following methods

PPT for a logical flow

Detailed comments.

Issue: Even though I have implemented the above practices, they do not help on the review. The problem I faced is, when certain logic is referred, I keep searching for the implementation and the flow and too much time is wasted in the process and I get on people’s nerve.

I think a lot of developers would be going through what I am going through as well.

答:
Practices vary, but in my experience:

Don't do anything special to the code. It's natural to spiff up your code a little more when you learn that it's going to be reviewed, and there's no harm in fixing obvious things like spelling mistakes and such. But don't go in and add a lot of detailed comments or otherwise change the code just because it's scheduled for review.

Code is prepared and distributed to reviewers well in advance of the review. This is usually done by a neutral third party, probably the code review facilitator. If printed out, the code should be small enough that lines aren't wrapped too often, but large enough that everyone can read it easily. Print it in landscape format if that's what it takes.

Code should be printed or displayed with line numbers. Preferably, the number should continue from one file to the next. It's so much easier to refer to "line 3502" than "line 238 of foo.c", and having the numbers lets everyone talk about specific lines without wasting time finding those lines.

There should definitely be a facilitator, btw. His or her job is to keep the review from getting bogged down in minutia, prevent it from getting personal or heated, and strictly limit the length of the review.

As the author, you should review the code yourself before the review meeting. Write down the changes you'd suggest if this were someone else's code. This jogs your memory of code that you might not have looked at in a few days, and it also helps you practice looking at your own code with a critical eye. After you've been through a few reviews, both as reviewer and as author, you'll find that your own notes will more closely match those of the rest of the group.

Be prepared to take notes during the review. This shouldn't be your main concern -- someone else should be recording the action items that the group agrees on so that you can focus on explaining the code and listening to the feedback. But there will be times when you get some valuable feedback that isn't an action item, and you should right such things down as they occur.

Remember that it's not personal. It's hard to avoid feeling (and acting) defensive during a review. It's fine to explain your code if you think it was misunderstood, but more than anything else try to just listen.


问:
Are there any language agnostic unit testing frameworks?
I have always been skeptical of rewriting working code - porting code is no exception to this.  However, with the advent of TDD and automated testing it is much more reasonable to rewrite and refactor code.

Does anyone know if there is a TDD tool that can be used for porting old code? Ideally you could do the following:

Write up language agnostic unit tests for the old code that pass (or fail if you find bugs!).

Run unit tests on your other code base that fail.

Write code in your new language that passes the tests without looking at the old code.

The alternative would be to split step 1 into "Write up unit tests in language 1" and "Port unit tests to language 2", which significantly increases effort required and is difficult to justify if the old code base is going to stop being maintained after the port (that is, you don't get the benefit of continuous integration on this code base).

EDIT: It's worth noting this question on StackOverflow.

答:
Such framework doesn't exists, because it needs to be written in the language of the code that is used.

For example, a framework for testing c++ code needs to be written in c or c++. Using framework written in c++ might, but it is not going to test a c code if it uses c++ features.


答:
I don't think it's possible to write unit tests in a different language.

However, what you can do is write integration/acceptance/user interface / whaterver_you_name_it tests that would be very high level and would not be tied to the language your software is written with.

If your application is a webservice, you can test it with whatever language you want, providing it supports your protocol.
If your application runs in a browser, you can use selenium (that's the first that came to my mind, but there are others.
Etc.
There might be some cases where it would not work I imagine (maybe hardware stuff), it all depends on the type of application you are working on.

Of course, you won't have the same coverage as you would have with unit level tests (unless spending a lot of time), but at least, you would have a test harness.

Title: Are there any language agnostic unit testing frameworks?

Body:
I have always been skeptical of rewriting working code - porting code is no exception to this.  However, with the advent of TDD and automated testing it is much more reasonable to rewrite and refactor code.

Does anyone know if there is a TDD tool that can be used for porting old code? Ideally you could do the following:

Write up language agnostic unit tests for the old code that pass (or fail if you find bugs!).

Run unit tests on your other code base that fail.

Write code in your new language that passes the tests without looking at the old code.

The alternative would be to split step 1 into "Write up unit tests in language 1" and "Port unit tests to language 2", which significantly increases effort required and is difficult to justify if the old code base is going to stop being maintained after the port (that is, you don't get the benefit of continuous integration on this code base).

EDIT: It's worth noting this question on StackOverflow.


答:
I think what comes closest to your idea is unit test frameworks on virtual machine based ecosystems such as the Java VM. At least Scala (and I believe Groovy too - I am not quite sure about Clojure) is almost perfectly interoperable with Java. That is, Scala code can be tested with JUnit and Java code can be tested with ScalaTest. This way you can (gradually or at once) rewrite Java code in Scala and keep using the same old Java unit tests to verify its correctness. (Or the other way around - although I can't imagine a valid reason to migrate from Scala back to Java.)

Probably the same is true to languages on the .NET CLI, e.g. C#, F#, ASP.NET et al.

Outside of a VM/CLR, however, it is more difficult. In theory, one could compile unit tests and/or code under test into another language such as C (as was and is common with new languages such as early C++ etc.), but I haven't heard of anyone trying this out specifically with unit tests.


问:
What is a benefit of having source code for ICS?
People are so happy the source code of Ice Cream Sandwich became available for syncing. Why is that cool?</p>

答: It means they can understand how the OS is working and if they want to modify it for their devices, they can.</p>


答:
A well-written class should be a little "island of trust": You can use it and assume that it does "the right thing" and that it shields you from common pitfalls. That makes a good class a building block, which is much more reusable as a bunch of functions and variables, which might work well but show you all their ugly guts, and force you to understand how they work together, how they need to be initialized etc. A good class should be like an USB plug, while the procedural solution is like a bunch of wires, chips, tin and a soldering bit.

One point that wasn't discussed in depth is the interface / implementation aspect. An interface describes the behavior, but not the realization. So a list interface describes the concept of a list and its behavior: You would expect things like add, remove and size methods. Now there are a lot of different ways to implement this list, e.g. as a linked list or using an array buffer. The power of OO programming is that by using an interface you can reason about the behavior without knowing about the implementation. Accessing internal variables or methods would destroy this abstraction, you couldn't replace one list implementation by another, and you couldn't improve an existing implementation without touching the code using the class. That's one of the main reasons why private variables and methods are needed: To protect internal details of the implementation, so the abstraction stays intact.

OO goes even one step further: E.g. for libraries you can define an interface for things that not even exist yet, and write code that works with that interface. The users can write classes implementing the interface, and use the services provided by the library. This allows a degree of flexibility that isn't possible with procedural programming.

Title: What's the benefit of object-oriented programming over procedural programming?

Body:
I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two.

I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these?

I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable.

Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well:

```<code>if ( login == "admin") {
    // invoke the function
}
</code>```

Why is this not ideal?

Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?


答:
Claus Reinke: regarding Tennent's "Language Design based on Semantic Principles"

Gives interesting interpretation of the principles:

"Correspondence is the principle that lets us say that

```<code>let(this=obj, x=5) { .. }
</code>```

and

```<code>((function(x) { .. }).call(obj,5))
</code>```

should be equivalent, and that anything we can do in
formal parameter lists, we should also be able to do in
declarations, and vice versa." [see also, Reinke, below.]

R. D. Tennent: Language design methods based on semantic principles

"Two language design methods based on principles derived from the denotational approach to programming language semantics are described and illustrated by an application to the language Pascal. The principles are, firstly, the correspondence between parametric and declarative mechanisms, and secondly, a principle of abstraction for programming languages adapted from set theory. Several useful extensions and generalizations of Pascal emerge by applying these principles, including a solution to the array parameter problem, and a modularization facility."

Claus Reinke: "On functional programming, language design, and persistence" on Haskell

Title: What is the good explanation of Tennent's Correspondence Principle?

Body:
I found myself struggling to see what is this principle about and why is it so important for language design.

Basically, it states, that for every expression expr in language should be exactly the same as this construct:

```<code>(function () { return expr; })()
</code>```

Also, I have heard that Ruby obeys this principle, while Python doesn't. I don't understand why this is true, or if it is true at all.

Body:
Claus Reinke: regarding Tennent's "Language Design based on Semantic Principles"

Gives interesting interpretation of the principles:

"Correspondence is the principle that lets us say that

let(this=obj, x=5) { .. }

and

((function(x) { .. }).call(obj,5))

should be equivalent, and that anything we can do in
formal parameter lists, we should also be able to do in
declarations, and vice versa." [see also, Reinke, below.]

R. D. Tennent: Language design methods based on semantic principles

"Two language design methods based on principles derived from the denotational approach to programming language semantics are described and illustrated by an application to the language Pascal. The principles are, firstly, the correspondence between parametric and declarative mechanisms, and secondly, a principle of abstraction for programming languages adapted from set theory. Several useful extensions and generalizations of Pascal emerge by applying these principles, including a solution to the array parameter problem, and a modularization facility."

Claus Reinke: "On functional programming, language design, and persistence" on Haskell


问:
What are the disadvantages of test-first programming?
It's all the rage nowadays. "Everyone" recommends it. That in and of itself makes me suspicious.

What are some disadvantages you have found when doing test-first (test-driven) development? I'm looking for personal experiences from knowledgeable practitioners--I can read the hypothetical musings of a hundred wannabes elsewhere on the internet.

I ask not because I am looking to hate TDD, but because it is my job to improve software development process, and the more we can learn about the problems people encounter, the better chance we have of improving the process.

答:
The biggest drawback I've seen is not with TDD itself but with practitioners. They take a dogmatic and zealot approach where everything must be tested. Sometimes (many times that is), that is not necessary. Also, it might not be practical (.ie. introducing an organization to TDD.)

A good engineer finds trade-offs and applies the right balance of when/where/how to apply test-first. Also, if you find yourself constantly spending much more time developing tests instead of actual code (by a factor of 2-3 or more), you are in trouble.

In other words, be pragmatic and reasonable with TDD (or anything in software development for that matter.)