答:
I find unit testing useful in two distinct stages and in two distinct usage patterns.

When you are building new code, it is difficult to even see if anything is working because the code that exercises or depends on your code, is not done.  So, you write unit tests, that test your code in a black box fashion.  The test assumes that someone somewhere will call your function with appropriate parameters ( right now, provided by the unit test system ) and your function will respond with an appropriate, non exceptional, non crashing, correct response.  So this way you can develop code in parallel with other system activities ( sometimes even in parallel with design and architecture, but, alas )

Once you have the system working and producing some kind of value for users or being shown as a prototype, then, you have to change some underlying infrastructure, like the database connection.  In this case, regression tests are invaluable.  The working code you have actually has probably hundreds of hours of testing because as you develop, you test.  Once you change the underlying assumptions in your infrastructure, you lose all those hours of reliability testing.  It is really useful to have an automated regression testing system to rerun all those little unit test, over and over , while you tweak some parameters, such as the new database timeout or debug fundamental errors in low level code.

Title: How to use unit testing?

Body:
How to use unit testing?

There are a lot of frameworks for different languages, which provide functionality of unit testing. There is a lot of information on how to use each of them technically. Just like "import to your project this lib, type assert, compile, run and blah-blah-blah". And it all is easy to learn.

The place I’m confused in is how to get it: which test to write, to cover large amount of possible bugs?

For example, assume we use jasmine framework for JS, and we are to test email validation function.

Great. Our simple code will look like this:

```<code>describe("Email validation test", function() {
  it("isEmailValid(\"mytestname@gmail.com\") should be true", function() {
    expect(isEmailValid("mytestname@gmail.com")).toBe(true);
  });
});
</code>```

But actually we have no ideas how does isEmailValid function is written and where can it fail. Maybe it works only if we have gmail.com domain? So we should include another one test with any other domain.

Or maybe it doesn't work if we have some very specific domain, just like "warhammerhobbitbanachspace.am"? In that case it would be rather difficult to catch a bug. Or, even, impossible.

Or maybe it'll fail if we have more than 42 symbols in the string with email? Or maybe it'll fail if we have exactly 9 symbols?
And that is only a little amount of examples of places which it would be useful to test. And that is just a simple string validation function...
And how can we really test some complex objects then? Yeah, I know, it is impossible to test everything. But how then to choose what really should be tested, and what not?

Are there any books or articles, which explain ... some patterns/techniques/principals of covering the code with useful tests?


问:
How to use unit testing?
How to use unit testing?

There are a lot of frameworks for different languages, which provide functionality of unit testing. There is a lot of information on how to use each of them technically. Just like "import to your project this lib, type assert, compile, run and blah-blah-blah". And it all is easy to learn.

The place I’m confused in is how to get it: which test to write, to cover large amount of possible bugs?

For example, assume we use jasmine framework for JS, and we are to test email validation function.

Great. Our simple code will look like this:

```<code>describe("Email validation test", function() {
  it("isEmailValid(\"mytestname@gmail.com\") should be true", function() {
    expect(isEmailValid("mytestname@gmail.com")).toBe(true);
  });
});
</code>```

But actually we have no ideas how does isEmailValid function is written and where can it fail. Maybe it works only if we have gmail.com domain? So we should include another one test with any other domain.

Or maybe it doesn't work if we have some very specific domain, just like "warhammerhobbitbanachspace.am"? In that case it would be rather difficult to catch a bug. Or, even, impossible.

Or maybe it'll fail if we have more than 42 symbols in the string with email? Or maybe it'll fail if we have exactly 9 symbols?
And that is only a little amount of examples of places which it would be useful to test. And that is just a simple string validation function...
And how can we really test some complex objects then? Yeah, I know, it is impossible to test everything. But how then to choose what really should be tested, and what not?

Are there any books or articles, which explain ... some patterns/techniques/principals of covering the code with useful tests?

答:
In the general case, it is impossible to prove correctness by testing.

Testing shows the presence, not the absence of bug

--Dijkstra

That being said, you can test your method with likely inputs and at least know that it works and have something with which to check for regressions (see Andyz answer). If you later discover a bug in your code, add another test case for that bug so you know you will at least not encounter that problem again.

ContentLicense: CC BY-SA 3.0

Title: How to use unit testing?


问:
Offline data transaction processing capabilities in a context of poor internet connectivity
We have a core banking product developed with ASP.NET with C# using Microsoft SQL Server 2008 database. Product is hosted on a centralized server and works well at all locations (bank branches) where connectivity is good and stable.

We need to implement this solution at a region where connectivity is always an issue. Since it is a core-banking solution, there should not be any service lapse to the customer because of technical issues (viz., connectivity).

How to design the architecture for this and ensure that there is no transactional issues at any given point of time, and at the same time the centralized database contains the latest data from all branches?

答:
In addition to perhaps designing an overnight sync process, another option might be to use a distributed queuing approach.  That is, a queue at the branch site can queue up requests when the connectivity is down and these can be dequeued by the receiving system when connectivity is up. This article provides a pretty good overview.  There are a number of products/projects that support this capability - some possibilities include Apache ActiveMQ, RabbitMQ, and MSMQ. In this case, MSMQ is probably the most relevant.

From a front-end application standpoint, you need to design for this kind of asynchronous operation.  That is, the transaction needs to be considered complete by the application when it is placed on the queue and the assumption is that the queue is completely reliable.

As for the central location, it will always have the latest information available given network availability, subject to any lag introduced by the time it takes to process  the queued requests.  This is the best you can do in terms of recency of information if the network isn't reliable.

This kind of asynchronous queuing can be useful for a range of reasons beyond dealing with network connectivity and is a useful pattern to know.  For example, it can be used to effectively smooth load for a system that is servicing work from multiple requestors that don't require immediate response.  The "server" in this case doesn't need to be able to handle all of the load as it comes in so you can be more efficient from a resource utilization and not spec servers to handle "peak" loads while mostly sitting idle.


答:
I simply write the test, than have a look at what is covered and if not all is covered, I write another test to cover parts missed by the previous tests.

I use TestNG because it has some nice feature JUnit hasn't (e.g. groups) and than check the coverage with EclEmma. Both plugins work smooth together in
eclipse.

Title: How to use unit testing?


问:
From a high level programming perspective, where does the 'different-paradigm' barrier between C# and F# really kick in?
I'm aware that they both use different programming paradigms, but from a high level perspective apart from differing syntax it seems most basic tasks can be achieved in similar fashion.

I only say this because when I've previously touched functional programming languages such as Haskell, writing code for basics tasks was (at first) difficult, frustrating, and required a completely different mindset.

For example the following took some time to get to grips with using recursive syntax:

```<code>loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
</code>```

Where as an F# loop is recognisable and understandable almost immediately:

```<code>let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
   printfn "%d" i
</code>```

When C# programmers start learning F# they are advised to completely re-think their thought pattern (which was definitely required for Haskell), but I've now written several F# programs dealing with conditions, loops, data sets etc to perform practical tasks, and I'm wondering where the 'different-paradigm' barrier really kicks in?

答:
F# supports Object Oriented Programming but OOP isn't really idiomatic F#. OOP encourages bundling of data and behavior while functional programming encourages separating them.

Take a look at the difference between the System.Collections.Generic.List<T> and Microsoft.FSharp.Collections.List<'T> classes.

The regular (OOP) class has a large list of methods and extension methods for example, List<T>.Add(T). In contrast, the F# list has only a few properties while all of the related functions are grouped into a List module.

Let's looks at a familiar OOP example:

```<code>public interface IAnimal
{
    void Speak();
}

public class Duck : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Quack!");
    }
}

public class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Meow!");
    }
}
</code>```

You could translate that to F# (non-idiomatic):

```<code>type IAnimal =
    abstract member Speak : unit -> unit

type Duck =
    interface IAnimal with
        member this.Speak () -> printfn "Quack!"

type Cat =
    interface IAnimal with
        member this.Speak () -> printfn "Meow!"
</code>```

You can see that the code is shorter but not really any different. If you find yourself writing code like this, you're thinking like a C# dev :) Here's a more idiomatic translation:

```<code>type Animal =
    | Duck
    | Cat

let speak animal =
    match animal with
    | Duck -> printfn "Quack!"
    | Cat -> printfn "Meow!"
</code>```

Here's a alternative version of speak:

```<code>let speak = function
    | Duck -> printfn "Quack!"
    | Cat -> printfn "Meow!"
</code>```

At this point, the code looks very different than the C# version largely because we have separated the behavior (speak or Speak()) from the data (in this case, just the type of Animal or IAnimal we have). One other difference is that we have expressed the possible states of data (animal kinds) in a way the compiler (and type-system) understand more intimately than the C# compiler/typesystem. Consider a function which gets the first item in a list:

```<code>public T GetHead(List<T> list)
{
    return list[0];
}
</code>```

vs:

```<code>let getHead = function
    | head :: tail -> head
</code>```

Both take a idiomatic list and return the first item in it (:: is the list destructuring operator).

If you were to compile both of these, the C# version would compile with no errors or warnings and the F# version would warn you that you haven't considered all of the cases (what about the empty list?). The F# compiler realizes you haven't accounted for all possible inputs and warns you accordingly.

This is one of the other differences between the languages, as a programmer (if you have idiomatic code), you can lean on the compiler a lot more for detecting errors and bugs which C#/OOP wouldn't catch until runtime.

Body:
F# supports Object Oriented Programming but OOP isn't really idiomatic F#. OOP encourages bundling of data and behavior while functional programming encourages separating them.

Take a look at the difference between the System.Collections.Generic.List<T> and Microsoft.FSharp.Collections.List<'T> classes.

The regular (OOP) class has a large list of methods and extension methods for example, List<T>.Add(T). In contrast, the F# list has only a few properties while all of the related functions are grouped into a List module.

Let's looks at a familiar OOP example:

public interface IAnimal
{
    void Speak();
}

public class Duck : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Quack!");
    }
}

public class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Meow!");
    }
}

You could translate that to F# (non-idiomatic):

type IAnimal =
    abstract member Speak : unit -> unit

type Duck =
    interface IAnimal with
        member this.Speak () -> printfn "Quack!"

type Cat =
    interface IAnimal with
        member this.Speak () -> printfn "Meow!"

You can see that the code is shorter but not really any different. If you find yourself writing code like this, you're thinking like a C# dev :) Here's a more idiomatic translation:

type Animal =
    | Duck
    | Cat

let speak animal =
    match animal with
    | Duck -> printfn "Quack!"
    | Cat -> printfn "Meow!"

Here's a alternative version of speak:

let speak = function
    | Duck -> printfn "Quack!"
    | Cat -> printfn "Meow!"

At this point, the code looks very different than the C# version largely because we have separated the behavior (speak or Speak()) from the data (in this case, just the type of Animal or IAnimal we have). One other difference is that we have expressed the possible states of data (animal kinds) in a way the compiler (and type-system) understand more intimately than the C# compiler/typesystem. Consider a function which gets the first item in a list:

public T GetHead(List<T> list)
{
    return list[0];
}

vs:

let getHead = function
    | head :: tail -> head

Both take a idiomatic list and return the first item in it (:: is the list destructuring operator).

If you were to compile both of these, the C# version would compile with no errors or warnings and the F# version would warn you that you haven't considered all of the cases (what about the empty list?). The F# compiler realizes you haven't accounted for all possible inputs and warns you accordingly.

This is one of the other differences between the languages, as a programmer (if you have idiomatic code), you can lean on the compiler a lot more for detecting errors and bugs which C#/OOP wouldn't catch until runtime.


问:
I've never interviewed anybody before... HELP?
There were 3 developers at this GIS tracking company, but now there's 2. Last week my boss was fired. Today, new developers will be coming in for interviews. They'll be coming in from a placement agency. I don't really know how to be on this side of a hiring interview. Any advice or sample questions I can ask?

Company Background: The 2 of us wear many hats.  We are the MySQL DB admins, we write C# web services including APIs, there's C# back end processes that generate reports and issue alerts, and we also have a few VB6 projects that I personally am hoping to replace. Our web app is just under 10K lines of javascript, almost 2K lines of HTML and just under 4K lines of CSS. We don't use a lot of frameworks or libraries aside from jQuery and Bing Maps. I've been here a year as just a developer and at no place have I ever worked with any sort of management responsibilities.

What kinds of questions can I ask that can really show me that somebody knows how to develop in these languages? I'm really drawing a blank here.

答:
Read Joel's excellent blog posting The Guerrilla Guide to Interviewing

When interviewing, focus on getting to know the person. You're trying to learn two things:

Will this person do good work?

Will I want to work with this person?

If you absolutely must use a programming test, try FizzBuzz.  I've had candidates fail it.  I tend to politely end the interview very quickly after that.

Don't forget that interviewing is a two-way street.  The candidate is evaluating you and your company as well.  Spend some time outlining what's important to you, how the company works, etc.  Treat the candidate with courtesy and respect.

Never make the hiring decision on the spot - when finished with the interview after the candidate has left, write down your thoughts and impressions.

Don't worry too much about this, you'll get better with practice.

ContentLicense: CC BY-SA 4.0


问:
Writing a CSS parser in C#. What do you think is the best strategy?
I'm in the middle of writing a CSS parser in C#. I'm well under way, but I also have those times where I wonder if I'm taking the best approach. The things I've considered are:

Feed the CSS grammar from the W3C into a parser generator and working off that.

Hand-code a CSS parser off the grammar.

Use a generated tokenizer, but hand-code the parsing of the productions.

The reverse of (3) - generate the productions, but hand-code the tokenizer.

Without revealing my current approach, I was wondering how others feel about this, and appreciate any comments and guidance from your experience. Part of this is also to see what questions people ask and compare the questions to what I asked myself.

答:
I just did this and I simply wrote C# statements to process the rules of CSS.

My code was very simple but it did what I needed. It starts by stripping out all the comments. Then I just look for the next { character and assume the selectors came before, and the declarations are between that character and the next } character.

I also added simple support for the @media rule.

My code was published in the article A Simple CSS Parser.


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
One-click compilation

Debugging

Code templates

Code completion

Integration with version control and refactoring tools

Simpler unit testing

to name a few

ContentLicense: CC BY-SA 2.5


问:
Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?

答:
Documentation for Object-oriented classes often involves tradeoff between giving the maintainers of the class flexibility to change its design, versus allowing consumers of the class to make full use of its potential.  If an immutable class will have a number of properties which will have a certain exact relationship with each other (e.g. the Left, Right, and Width properties of an integer-coordinate grid-aligned rectangle), one might design the class to store any combination of two properties and calculate the third, or one might design it to store all three.  If nothing about the interface makes clear which properties are stored, the programmer of the class may be able to change the design in the event that doing so would prove helpful for some reason.  By contrast, if e.g. two of the properties are exposed as final fields and the third isn't, then future versions of the class will always have to use the same two properties as being the "basis".

If properties do not have an exact relationship (e.g. because they're float or double rather than int), then it may be necessary to document which properties "define" the value of a class.  For example, even though Left plus Width is supposed to equal Right, floating-point math is often inexact.  For example, suppose a Rectangle which uses type Float accepts Left and Width as constructor parameters is constructed with Left given as 1234567f and Width as 1.1f.  The best float representation of the sum is 1234568.125 [which may display as 1234568.13]; the next smaller float would be 1234568.0.  If the class actually stores Left and Width, it may report the width value as it was specified.  If, however, the constructor computed Right based upon the passed-in Left and Width, and later computed Width based upon Left and Right, it would report the width as 1.25f rather than as the passed-in 1.1f.

With mutable classes, things can be even more interesting, since a change to one of the inter-related values will imply a change to at least one other, but it may not always be clear which one.  In some cases, it may be best to avoid having methods which "set" a single property as such, but instead either have methods to e.g. SetLeftAndWidth or SetLeftAndRight, or else make clear what properties are being specified and which are changing (e.g. MoveRightEdgeToSetWidth, ChangeWidthToSetLeftEdge, or MoveShapeToSetRightEdge).

Sometimes it may be useful to have a class which keeps track of which properties' values have been specified and which have been computed from others.  For example, a "moment in time" class might include an absolute time, a local time, and a time zone offset.  As with many such types, given any two pieces of information, one may compute the third.  Knowing which piece of information was computed, however, may sometimes be important.  For example, suppose that an event is recorded as having occurred at "17:00 UTC, time zone -5, local time 12:00pm", and one later discovers that the time zone should have been -6.  If one knows that the UTC was recorded off a server, the record should be corrected to "18:00 UTC, time zone -6, local time 12:00pm"; if someone keyed in the local time off a clock it should be "17:00 UTC, time zone -6, local time 11:00am".  Without knowing whether the global or local time should be considered "more believable", however, it's not possible to know which correction should apply.  If, however, the record kept track of which time was specified, changes to the time zone could leave that one alone while changing the other.


问:
Is Python Cookbook for python 2.4 applicable to python 2.7.5?
My college has a course on Introduction to programming using python and we are using Python 2.7.5.

I would like to know if it will be helpful to read Python Cookbook which is for python 2.4?

There are no separate cookbooks for python 2.7.x, to my knowledge. But, are there any similar books? There is a later edition to python cookbook for Python 3, but it turns out that python 3 and python 2 are quite different.

答:
I wanted to know if it will be helpful to read python Cookbook which is for python 2.4?

In short: Yes, start with the book that you have. Later, i would definitely look and  cover the points introduced in what's new in Python 2.7 .

The fundamentals of the Python language are going to stay same. There will not be big shifts/changes between 2.4 and 2.7 versions. However, new features of language might be added in a beta version.

What you need to be aware of are the core versions (2.0, 3.0, etc..) of the programming language. Because, they may introduce much efficient or renewed approach on how to build the app.


问:
Should I use semicolons to delimit Scala statements?
I'm used to delimit statements by a semicolon from Java, so naturally I do it in Scala code too. I also feel that the code is easier to read, because it's evident where one statement ends and another begins. But many times when I post a piece of Scala code on SO, the code gets edited just to get semicolons removed.

Should I use semicolons or not? Are there any "official" guidelines or coding style?

Are there cases where semicolons are required, otherwise the code is ambiguous?

答:
How much do you want to understand the languages you use?  Do you want to play to its strengths or not?  Scala's syntax encourages clear and concise code; the few edge cases where taking advantage of this causes problems for the Scala parser are instructive (that is, you learn more about Scala by encountering and learning how to avoid them) and gradually being fixed (e.g. suffix notation).  Defensively using the semi-colon may mean you won't ever have to learn about these issues but do you really see that as a good thing? The fixes for these issues usually have other implications but you will miss out on these possibilities.

Another consideration is that, as Kilian concedes, most Scala developers omit semi-colons by default. How do you expect to work with other people's code if you avoid using idiomatic Scala yourself?  You're going to find it much harder than it need be.

I can't emphasis enough that these features of the Scala parser were chosen to encourage clean, re-usable and functional (in the fp sense) code.  Take infix operator syntax as an example; it encourages developers to furnish classes with simple, single-purpose methods which compose well together.  Scala's collection library shows just how beatifully that can work.  Classically-trained Java devs who embrace this will tend to develop better habits and new ways of thinking about their code.  Those who stick to all those familiar dots and brackets will miss out.  I contend that this is also true for those too timid to abandon the semi-colon.


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答:
MSDN class documentation often uses "you" to refer to developers.

When you inherit from WebRequest, you must override the following members...

You do not typically inherit from ButtonBase. To create your own button class, inherit from the Button, CheckBox, or RadioButton class....

You can also simply state what the requirements are for descendent classes. It is implied that developers are your audience.

Classes that inherit IDbConnection must implement all inherited members, and typically define additional members to add provider-specific functionality.

In your example, instead of "Implementers should implement this", write "Descendent classes must override InternalExecute to..." or "In descendent classes, you must override InternalExecute to...".


答:
I don't know if it we meet your needs for real-time transactions, but you might want to look into using SQL Server Replication.

You could have a Web Server and SQL Server running at your remote location. The users there would connect to that instance. Using Replication, SQL Server would keep your data in sync between the two locations. If there was a drop in the connection, SQL Server would handle reconciling the data when the connection was available again.

I can't guarantee that this is the best solution for you without knowing all of your requirements or your access to SQL Server licenses. But it something you might want to investigate.

If it meets your needs, it would be a solution that wouldn't require any additional development.

Title: Offline data transaction processing capabilities in a context of poor internet connectivity

Body:
We have a core banking product developed with ASP.NET with C# using Microsoft SQL Server 2008 database. Product is hosted on a centralized server and works well at all locations (bank branches) where connectivity is good and stable.

We need to implement this solution at a region where connectivity is always an issue. Since it is a core-banking solution, there should not be any service lapse to the customer because of technical issues (viz., connectivity).

How to design the architecture for this and ensure that there is no transactional issues at any given point of time, and at the same time the centralized database contains the latest data from all branches?


问:
Self reference using a new table vs concatenated list of ids
At my current workplace there is a common pattern in database design: they don't use foreign keys but they list all corresponding ids in a column like this:

```<code>some_table
id  name image_ids
1   a    1,2,3
2   b    4,6,7

images
id url
1  ...
2  ...
...
</code>```

They store self references in a same manner:

```<code>some_table
id  name  some_table_id
1   a     2,3
2   b     1,3
...
</code>```

They encourage me to use this pattern but it does not feel right for me. I would never design a database like that. I have some counter arguments against it:

What if some day I would add some arbitrary data to a self reference? Using this model I would not be able to.

It does not ensure referential integrity. I can easily add non-existent ids which will lead to problems

Searching through strings is not fast either

I need to justify my complaints so my question is:
What persuasive counter-arguments can you come up with against this hacky design approach?

答:
Some of the arguments I can think of against this design:

It's probably impossible to index on the references IDs. Sometimes you want to index a table not only by it's primary key, but also by what it references. I don't see an easy way to do that here.

Queries that join on these fields are going to get ugly. I'm guessing there's a lot of usage for in and string manipulation functions (like instr , substr, etc...).

Updating these lists of IDs is going to be ugly, since you have to update records and remove/add strings instead of simply inserting/deleting records, if this had been done properly with auxiliary tables storing these relations.

As you mentioned, this approach can also lead to data integrity problems.

All of the above could lead to performance problems.

It's counter-intuitive and will make be more difficult when new members join the team.

I don't know which of these you've already tried on them. The best approach might be to do a demo of a small set of their tables (maybe some_table and images): rebuild the tables with proper foreign keys and relation tables and show the performance gains, the ease-of-querying, they way you can't introduce invalid data... And I hope you are able to show some significant gains. If this design pattern is already so entrenched, it might be very hard to break them of it without a good demonstration.


答:
It appears you have your complaints in order. I would come up with more, but I don't think you've identified why they chose this solution.

There are many benefits to normalizing and denormalizing a database. Look into how they feel this structure benefits the application. Hopefully they're trying to do more to sell you on these methods instead of just making you do it.

There could be a lack of relational database knowledge. They've already gone to the trouble of handling the relationships and referencial integrity in the application code. If this is causing a lot of bugs because they coded things that a RDBDMS handles almost out of the box, it makes sense to change the code instead of trying to maintain what you have.

Maybe there is a new module to the application where you have an opportunity to do things differently and show them the benefits? It's a hard sell on code that supposedly works.

Everyone is aware of best practices, technical debt, ease of debugging and enhancing, but these can be a hard-sell in situations where they may not apply (e.g. a legacy code system with a legacy team who are adept at their inefficient methods enough to convice those in charge they are getting things done on time and can't get any faster.).

Title: Self reference using a new table vs concatenated list of ids

Body:
At my current workplace there is a common pattern in database design: they don't use foreign keys but they list all corresponding ids in a column like this:

```<code>some_table
id  name image_ids
1   a    1,2,3
2   b    4,6,7

images
id url
1  ...
2  ...
...
</code>```

They store self references in a same manner:

```<code>some_table
id  name  some_table_id
1   a     2,3
2   b     1,3
...
</code>```

They encourage me to use this pattern but it does not feel right for me. I would never design a database like that. I have some counter arguments against it:

What if some day I would add some arbitrary data to a self reference? Using this model I would not be able to.

It does not ensure referential integrity. I can easily add non-existent ids which will lead to problems

Searching through strings is not fast either

I need to justify my complaints so my question is:
What persuasive counter-arguments can you come up with against this hacky design approach?


问:
How to model an arbitrary number of types
I'm currently in the process of modelling a generic form of RNA and RNA transcription and I'm having difficulty finding a proper OO modeling of this area.

Human RNA has 4 types of Nucleotides (A, G, U, and C).  An RNA strand is just a string of these 4 types.  eg, AAGACAUUCUA...

What I'm trying to model is more generic in the sense that I want to be able to decide the number of Nucleotide types at runtime.  So, my object model needs to be able to represent an arbitrary number Nucleotide types.

Initially, I thought I'd just have a Nucleotide class which had a int TypeId member.  This way, I could have a sequence of Nucleotide instances of arbitrary types... but this doesn't feel right.

I'm not a huge fan of storing type in a variable.  I'm also not comfortable with what is essentially definition information being set on every instance (instead of being defined in the a class).

So, how do I get around this?  Here's what I've come up with so far:

On a previous project, we would have Singleton objects which represented another object's type.  The other object would simply reference the singleton and that was it.  It prevented us from having multiple instantiations of the "definition" of our types.  Not too great IMO.

I remember Entity Framework generating Dynamic Proxies at runtime.  I could so something similar.  I could have a NucleotideBase base class and, at runtime, define derived classes.  I believe this is possible through reflection.  I'm not sure what the performance impact is with this approach, but I would assume it's all just one-time overhead when defining the classes.

Are there better, more OO, approaches?

答:
I would try the following for starters.

A, G, U, and C should all derive from a base class nucleotide - they are specific instances of the abstract class that nucleotide represents.  In OO modeling parlance "A is a nucleotide"

This gives you the ability to extend all 4 classes of nucleotides at once, or just the individual nucleotide.

You'll need another class to model the Strand as a strand is composed of a series of nucleotides.  "Strand has a (list of) nucleotides".  You can likewise extend the Strand class to perform operations that a strand would be responsible for but that a nucleotide would not be responsible for.

I also added an interface for "just in case" purposes.  For the immediate uses, the base nucleotide class should be sufficient, but if not, then an interface is there to help guarantee behavior.

Likewise I used a List collection in the Strand so I don't have to worry about particulars such as the strand length when first modeling.  Most OO languages should have an equivalent generic collection to use.

```<code>class Program
{
    static void Main(string[] args)
    {
        Strand myStrand = new Strand();

        myStrand.Add(new A());
        myStrand.Add(new G());
        myStrand.Add(new U());
        myStrand.Add(new C());
    }
}

public interface INucleotide
{
}

public class Nucleotide : INucleotide
{
    public byte TypeID;
}

public class A : Nucleotide {}
public class G : Nucleotide {}
public class U : Nucleotide {}
public class C : Nucleotide {}

public class Strand
{
    private List<INucleotide> Nucleotides = new List<INucleotide>();
    public void Add(INucleotide nuc)
    {
        Nucleotides.Add(nuc);
    }
}
</code>```

The above sample is in C#.

Singletons really aren't appropriate for this modeling exercise - there isn't anything "single" about what you're modeling.  You'll have potentially many instantiations of A, G, U, and C as well as the Strands.

Body:
I would try the following for starters.

A, G, U, and C should all derive from a base class nucleotide - they are specific instances of the abstract class that nucleotide represents.  In OO modeling parlance "A is a nucleotide"

This gives you the ability to extend all 4 classes of nucleotides at once, or just the individual nucleotide.

You'll need another class to model the Strand as a strand is composed of a series of nucleotides.  "Strand has a (list of) nucleotides".  You can likewise extend the Strand class to perform operations that a strand would be responsible for but that a nucleotide would not be responsible for.

I also added an interface for "just in case" purposes.  For the immediate uses, the base nucleotide class should be sufficient, but if not, then an interface is there to help guarantee behavior.

Likewise I used a List collection in the Strand so I don't have to worry about particulars such as the strand length when first modeling.  Most OO languages should have an equivalent generic collection to use.

class Program
{
    static void Main(string[] args)
    {
        Strand myStrand = new Strand();

        myStrand.Add(new A());
        myStrand.Add(new G());
        myStrand.Add(new U());
        myStrand.Add(new C());
    }
}

public interface INucleotide
{
}

public class Nucleotide : INucleotide
{
    public byte TypeID;
}

public class A : Nucleotide {}
public class G : Nucleotide {}
public class U : Nucleotide {}
public class C : Nucleotide {}

public class Strand
{
    private List<INucleotide> Nucleotides = new List<INucleotide>();
    public void Add(INucleotide nuc)
    {
        Nucleotides.Add(nuc);
    }
}

The above sample is in C#.

Singletons really aren't appropriate for this modeling exercise - there isn't anything "single" about what you're modeling.  You'll have potentially many instantiations of A, G, U, and C as well as the Strands.


问:
Why should IQueryProvider implementations throw NotSupportedExceptions?
Searching the web, we can find plentiful examples of various ORMs (nHibernate, EF, LinqToSql, etc.) that implement but don't actually support the full IQueryable<T> interface, throwing NotSupportedExceptions when they encounter something they don't like, such as LinqToSql and SkipWhile. My question is this: why do ORM providers opt to throw a NotSupportedException instead of letting certain query operators (that do not translate well or at all to the target data source) trip a query execution and then let Linq to objects handle the rest?

I understand that some heavy physical resource usage could occur as a result, but if IQueryable<T> instances were truly swappable, would we not be better off?

答:
Well, because

You would lose control of the query process, and

You would get an unexpected, and inaccurate, result.

The NotSupportedException is there so that you, the developer, can be notified of the unsupported feature.  You can then re-work your query in some way to get the result you want, without using the unsupported feature.


答:
One of the purpose of the IQueryable<T> interface is also to allow differed execution of the query, i.e., the functions applied to the collection are not actually applied but converted internally, in the case of LINQ to SQL for example, in an SQL query (a string).

If there is no way of expressing the given function in the source, then you can't support the operation, and you better have the programmer know that by throwing the NotSupportedException. He might then decide to switch to a specific data structure and carry on from there, but at least he knows what he's doing.

Title: Why should IQueryProvider implementations throw NotSupportedExceptions?

Body:
Searching the web, we can find plentiful examples of various ORMs (nHibernate, EF, LinqToSql, etc.) that implement but don't actually support the full IQueryable<T> interface, throwing NotSupportedExceptions when they encounter something they don't like, such as LinqToSql and SkipWhile. My question is this: why do ORM providers opt to throw a NotSupportedException instead of letting certain query operators (that do not translate well or at all to the target data source) trip a query execution and then let Linq to objects handle the rest?

I understand that some heavy physical resource usage could occur as a result, but if IQueryable<T> instances were truly swappable, would we not be better off?


问:
Will high reputation on Programmers help to get a good job?

Possible Duplicate:

  Will high reputation in Stack Overflow help to get a good job?

In reference to this question, do you think that having a high reputation on this site will help to get a good job?

Aside silly and humorous questions, on Programmers we can see a lot of high quality theory questions. I think that, if Stack Overflow will eventually evolve in "strictly programming related" (which usually is "strictly coding related"), the questions on Programmers will be much more interesting and meaningful ("Stack Overflow" = "I have this specific coding/implementation issue"; "Programmers" = "Best practices, team shaping, paradigms, CS theory").

So could high reputation on this site help (or at least be a good reference)? And then, more o less than Stack Overflow?

答:
We only have two users with five-digit reputations on this site, but one of them has definitely built a reputation with his answers about agile, team management, and automated testing.

If he is approached by someone about a consulting opportunity in any of the above areas, that will sure not be a surprise.


问:
What's the best approach to building a db schema for profile, but to track changes?
I'm working on a site where companies can create a profile then add locations for each profile.

Those first two tables are simple enough.

But any changes to their profiles or locations have to go through an approval process.  This is where I'm torn.

The end result would be an employee going through a worklist and seeing the requested changes and clicking "approve" or "deny".  Approve applying the new data to the existing record, deny setting a flag on the request record(s) and sending a response.

What I'm wondering is the best way to go about the change requests.  I would definitely like to keep the change requests in a separate table than the profile or location table.

I can't decide if it's best to just create duplicates with a few extra columns of the profile and the location tables and use those for change tracking.

Or if I should just create a simple table with just the columns to capture the change target id, field, and value, plus a few extras like changeset, datetime, flag, etc.

What do you think?

答:
From the viewpoint of database design (ignoring the database features and the application architecture ) I will prefer having a table for audit trail (change history) having changes per Entity and per field by implementing a flat table called Trail_History with no foreign key to any table, columns will be:

UserCode: Application user unique identifier. (mandatory)

TransactionCode: Any CRUD operation will need to have a unique transaction code (like GUID) (mandatory)

ChangeDate: Transaction date. (mandatory)

EntityName: Entity (table) that is being manipulated.(mandatory)

ObjectId: Entity that is being manipulated primary key.

FieldName: Entity field name.

OldValue: Entity field old value.

NewValue: Entity field new value

OperationType: CRUD operation discriminator. (mandatory)

Adopting this approach will be beneficial for:

Any entity (table) could be traced

Reports will be readable

Only changes will be logged

Transaction code will be the key point to detect changes by a single action


问:
SOLID Principles and code structure
At a recent job interview, I couldn't answer a question about SOLID -- beyond providing the basic meaning of the various principles. It really bugs me. I have done a couple of days worth of digging around and have yet to come up with a satisfactory summary.

The interview question was:

If you were to look at a .Net project that I told you strictly followed SOLID principles, what would you expect to see in terms of the project and code structure?

I floundered around a bit, didn't really answer the question, and then bombed out.

How could I have better handled this question?

答:
Distract them with Jon Skeet's discussion of how the 'O' in SOLID is "unhelpful and poorly understood" and get them talking about Alistair Cockburn's "protected variation" and Josh Bloch's "design for inheritance, or prohibit it".

Short summary of Skeet's article (though I wouldn't recommend dropping his name without reading the original blog post!):

Most people don't know what 'open' and 'closed' in 'open-closed principle' mean, even if they think they do.

Common interpretations include:

that modules should always be extended through implementation inheritance, or

that the source code of the original module can never be changed.

The underlying intention of OCP, and Bertrand Meyer's original formulation of it, is fine:

that modules should have well-defined interfaces (not necessarily in the technical sense of 'interface') that their clients can depend on, but

it should be possible to expand what they can do without breaking those interfaces.

But the words "open" and "closed" just confuse the issue, even if they do make for a nice pronounceable acronym.

The OP asked, "How could I have better handled this question?" As a senior engineer conducting an interview, I would be immeasurably more interested in a candidate who can talk intelligently about the pros and cons of different code design styles than someone who can rattle off a list of bullet points.

Another good answer would be, "Well, that depends on how well they've understood it. If all they know is the SOLID buzzwords, I'd expect abuse of inheritance, overuse of dependency injection frameworks, a million small interfaces none of which reflect the domain vocabulary used to communicate with product management...."

OwnerDisplayName: S-Unit

Title: SOLID Principles and code structure


答:
How about an enum for the Type?

```<code>[Flags]
public enum Nucleotide : byte {
    undefined =0,
    A = 1,
    G = 1 << 1,
    U = 1 << 2,
    C = 1 << 3
    . . .
    Z = 1 << 25   // of course a byte can't handle this
}
</code>```

Easily extensible as shown. The notation keeps me from having to actually write out the value of 2^25 for Z

I can see manipulating List<byte> or List<Nucleotide> or Stream as needed and casting if/when necessary.

Handy for passing to a Factory to build Nucleotide-specific behavior objects

A Nucleotide Property in some other class effectively makes sub-classing unnecessary.

The Flags attribute will allow us to define simple Nucleotide combinations, or even separate enums of those. You can go kinda crazy abstracting bit manipulation via enum I suppose. Direct bitwise manipulation could mitigate execution time issues and make the code expressive in Nucleotide terms.

enums are essentially constants and compile to constants in IL, i.e. good performance. Casting is quick.

.

```<code>[Flags]
public enum Pairs : byte {
    AC = Nucleotide.A | Nucleotide.C,
    GC = Nucleotide.G | Nucleotide.C,
    . . .
}
</code>```

EDIT

@MichaelT comment got me thinking about structure vis-a-vis classification; that, and I'm with DocBrown's comment "..don't over complicate things." It seems to me that structure is classification.

Tuple class may be useful. It is intended as a generic data structure.

```<code>var Phenylalanine =
   Tuple.Create(Nucleotide.T,Nucleotide.T,Nucleotide.T);
</code>```

"there is no practical limit to the number of components a tuple may have ... you can create tuples of eight or more elements by nesting tuple objects in the Rest property "

Tuple is immutable so it can be treated kinda like a singleton.

Implement IStructuralEquatable for those codons. The 3-Tuple class explicitly implements IStructuralEquatable.

It is Typed of course so this seems to fit the need to create types at runtime. Perhaps use a Factory to encapsulate a specific Tuple object with its IStructrualEquatable implementation.

Title: How to model an arbitrary number of types

Body:
I'm currently in the process of modelling a generic form of RNA and RNA transcription and I'm having difficulty finding a proper OO modeling of this area.

Human RNA has 4 types of Nucleotides (A, G, U, and C).  An RNA strand is just a string of these 4 types.  eg, AAGACAUUCUA...

What I'm trying to model is more generic in the sense that I want to be able to decide the number of Nucleotide types at runtime.  So, my object model needs to be able to represent an arbitrary number Nucleotide types.

Initially, I thought I'd just have a Nucleotide class which had a int TypeId member.  This way, I could have a sequence of Nucleotide instances of arbitrary types... but this doesn't feel right.

I'm not a huge fan of storing type in a variable.  I'm also not comfortable with what is essentially definition information being set on every instance (instead of being defined in the a class).

So, how do I get around this?  Here's what I've come up with so far:

On a previous project, we would have Singleton objects which represented another object's type.  The other object would simply reference the singleton and that was it.  It prevented us from having multiple instantiations of the "definition" of our types.  Not too great IMO.

I remember Entity Framework generating Dynamic Proxies at runtime.  I could so something similar.  I could have a NucleotideBase base class and, at runtime, define derived classes.  I believe this is possible through reflection.  I'm not sure what the performance impact is with this approach, but I would assume it's all just one-time overhead when defining the classes.

Are there better, more OO, approaches?

Body:
How about an enum for the Type?

[Flags]
public enum Nucleotide : byte {
    undefined =0,
    A = 1,
    G = 1 << 1,
    U = 1 << 2,
    C = 1 << 3
    . . .
    Z = 1 << 25   // of course a byte can't handle this
}

Easily extensible as shown. The notation keeps me from having to actually write out the value of 2^25 for Z

I can see manipulating List<byte> or List<Nucleotide> or Stream as needed and casting if/when necessary.

Handy for passing to a Factory to build Nucleotide-specific behavior objects

A Nucleotide Property in some other class effectively makes sub-classing unnecessary.

The Flags attribute will allow us to define simple Nucleotide combinations, or even separate enums of those. You can go kinda crazy abstracting bit manipulation via enum I suppose. Direct bitwise manipulation could mitigate execution time issues and make the code expressive in Nucleotide terms.

enums are essentially constants and compile to constants in IL, i.e. good performance. Casting is quick.

.

[Flags]
public enum Pairs : byte {
    AC = Nucleotide.A | Nucleotide.C,
    GC = Nucleotide.G | Nucleotide.C,
    . . .
}

EDIT

@MichaelT comment got me thinking about structure vis-a-vis classification; that, and I'm with DocBrown's comment "..don't over complicate things." It seems to me that structure is classification.

Tuple class may be useful. It is intended as a generic data structure.

var Phenylalanine =
   Tuple.Create(Nucleotide.T,Nucleotide.T,Nucleotide.T);

"there is no practical limit to the number of components a tuple may have ... you can create tuples of eight or more elements by nesting tuple objects in the Rest property "

Tuple is immutable so it can be treated kinda like a singleton.

Implement IStructuralEquatable for those codons. The 3-Tuple class explicitly implements IStructuralEquatable.

It is Typed of course so this seems to fit the need to create types at runtime. Perhaps use a Factory to encapsulate a specific Tuple object with its IStructrualEquatable implementation.


答:
I think the main reason is that such behavior could have very unexpected performance. Namely, if you tried to skip over most of some table, the query would need to load most of the table (or at least the relevant columns).

When the choice is between something that is unexpected and reporting error that can be easily fixed (by adding AsEnumerable() before the TakeWhile()), I think it makes sense to choose the latter.

If you don't like this, you could create your own IQueryable wrapper, that behaves exactly the way you want: if the underlying IQueryable throws NotSupportedException, call the equivalent method from LINQ to Objects (by using AsEnumerable()).


问:
What would be negative test case for this scenario?
Let's say we have some requirements

Req1: User name will accept 6-10 character alpha value.

Req2: On click of Submit button, application will show error message "Please enter value or character between 6 to 10 including" for invalid boundary value.

In this case if we are designing test cases for invalid boundary values of 5 and 11, those would be positive test cases, since we are also verifying the error message, which is mentioned in requirement.

What would be negative test case for this scenario?

答:
The phrase negative testing refers to the intent of the tester. It's testing that tries to break the system.

In your example it could be:

Entering 1000s of characters into the password field to overflow a buffer

Passing back a form where the password has been removed from the form

Entering characters that are outside the normal character set

Found this definition of negative testing:

But another surprise is how little companies are doing in the way
   of “negative” testing. By this I mean testing that tries to break the
   system, validate fault and exception handlers or otherwise force the device
   in to an unusual state or "edge condition".


问:
Multi-Thread Return Single SQL Result
I am having some difficulty with MySQL and returning a unique row to a thread. I want it so the thread will search for a row from the table where the bit (see below) is false and only one row is returned. But I don't want the other threads to return the same result should there might be some race condition where the same result is returned to the thread; because the thread will then do lots of processing off the back of this result and I don't want duplication.

Background:
I have a MySQL database that contains 3 columns (id, text, bit).
The id is auto-incremented.
I have a multi-threaded Ruby application that reads, updates and inserts rows into the table.

Pseudo code for the thread is as follows:

```<code>select a row from the table where the bit is false
do some processing with the text returned from that row
insert more rows with bit set to false
</code>```

I have tried a simple test with a multi-threaded script that uses the following:

```<code>SELECT id, text FROM table WHERE bit =FALSE LIMIT 1 FOR UPDATE
</code>```

But each thread returns the same row. I have disabled autocommit as per the recommendation. Since I am omitting any commit I would expect the other threads to have a different result since the row is locked.

Am I missing something or should I be looking at using another method?

答:
You can add another column that tracks whether or not a particular row is 'checked out' by your application.  This might be a good place for a stored proc.  Other threads would then select the first row where 'bit' is false and 'checked_out' is false.

Another option is to dedicate a single thread to pulling the id's and distributing them to worker threads.

It sounds like you might be implementing a queue, in which case you may also want to research the various queue/messaging systems.

Further options...

If you know you'll always have a fixed number of threads, you can add a mod condition to your query.  eg, "where (bit = false) and (id % 4 = 0)".  This runs the risk of missing items if one of the threads stops or falls behind.

Yet another thing to look at is perhaps consider only doing your work in a single thread.  Your MySQL server will only handle so much, so you should profile to see if you are actually getting more done with multiple threads.  So if the threads are just doing basic db read & writes, there may not be an advantage.  On the other hand, if what you are doing is processor intensive, something like image processing, the threads will likely help.

Title: Multi-Thread Return Single SQL Result


答:
Because of it's complexity. If query throws NotSupportedException that probably means you query is extremely complex. And as such, it would be really hard to separate what can be run over DB and what must be done in-memory. In simplest way, you just fetch the whole table or maybe half of the DB, thanks to joined records. And you must be crazy to think that is good idea, especially when it happens without you knowing. Implementing such detection algorithm would be quite complex, probably even more complex than implementing query feature itself.

Also, implementing IQueryable is quite complex in itself (as proven by NHibernate devs), so they probably haven't had time to implement this specific feature of whole complex query system.


问:
Multiple Dispatch and CLOS
I have never written software in Common Lisp, but in Scheme and Clojure as well as C++ and Python. Yet I have had a look at the Common Lisp Object System (CLOS) in Common Lisp and Dylan. Now when comparing it to OOP in the Simula tradition, CLOS and lets say C++ and Python class system have polymorphism as a common trait.

They seem to differ in the way how data and methods are organized, in the Simula family, methods are an integral part of classes, sub-items if you will while with CLOS they are defined outside of classes and are rather generalized procedures.

Common Lisp proponents typically argue that virtual methods in Simula-family programming languages are quite limited since they are invoked only according to the first-argument object (this or self). CLOS generic functions are selected for several arguments, thus something like (pseudo code)

```<code>method draw(c : Device, d : Drawable) ...
</code>```

can be implemented for arbitrary Canvas and Drawable combinations.

```<code>method draw(c : Printer, t : Triangle)....
method draw(c : Printer, t : Image)....
method draw(c : Screen, t : Image) ....
</code>```

In Simula-family languages, this would be more difficult, since draw would have to be associated with either the Device or the Drawable family of objects. The canonical solution seems to be the Visitor Pattern http://en.wikipedia.org/wiki/Visitor_Pattern .

Upon learning CLOS, I was quite amazed that most OO programming languages do not offer multiple dispatch - and - wondered if there are specific reasons, why one might associate methods so closely with one specific class. Are there specific advantages for single dispatch?

ambiguity of multiple dispatch: i.e. lets say I have a subclassing A and b subclassing B. The method foo(A,B) implemented as foo(a,B) and foo(A,b), which implementation would a call of  foo(a,b) invoke? Is this the only reason?

"Modularizing", methods in the class are near.

Is there more to it? Have language designers and creators taken a stance on this matter?

答:
Single dispatch is somewhat easier to implement, and multiple dispatch is rather rarely needed in practice according to research by Muschevici et al.

You can find more information in the Wikipedia article on multiple dispatch; for instance, it also explains why the CLOS method of defining multimethods may be a better fit for Lisp's extremely uniform syntax, rather than for the more prevalent nesting of methods within classes.

Title: Multiple Dispatch and CLOS


问:
Should you write automated tests to check that data is correct (the contents of config files, databases, etc.)?
Simply put: is there a best practice for whether developers should write automated tests to check that data is correct (the contents of config files, databases, etc.)? If so, what is it?

Assume that the data is static for a given release, and specified as part of requirements.

答:
In most cases this will make no sense, a test if your data is correct may end up in comparing file A1 to a copy of the file itself A2. Lets say you need a new version of A1 because the format of your data has evolved in version 2.0 of your software, you would change it to A1_V2, and now your test tells you that A2 is different from A1_V2 - so you copy A1_V2 to A2_V2 (or edit it until both files are equal again). But if you made an error in the first transition from A1 to A1_V2, you now introduced the same error into A2_V2 - and the test does not prevent that. The only form of quality assurance related to the content of A1 that will work (especially if A1 is part of the requirements, as you wrote), is to let a second person proofread A1.

However, if A1 is in a data format which can be checked for consistency (for example, an XML file, maybe with a schema), then it makes sense to have a test for A1 beeing consistent with that file format. Of course, you probably have already such a test, because if A1 is already part of an automatic test of some production code, then this code reads A1. And if the reading routine is designed to be robust and fail-safe, as any reading code should be, then it does already this kind of consistency checking and will show up an error is A1 is broken. So in most cases, this means you don't need any extra tests especially for data. But beware: such a test does not guarantee that the contents of A1 are correct, it only gives you a formal check.

There is, however, no rule without exceptions. There can be special cases (which I expect to be rare) where your specific test data can be checked for containing some content, maybe in a non-obvious form, to make sure the test will work as intended. For example, you may have a complex test database, and you want to make sure later manual edits of that database don't destroy your set of ten well-designed, non-obvious test cases contained in that database. Then it would make sense to write an  automatic test to verify that.

Also, if your data is itself some kind of "code" (for example, some scripts or functions written in some kind of DSL), then it is obvious that automatic tests make sense here.

I would like to mention that it does not make a difference if we don't think about test data or data to be released to production as part of your product (since such data can be always used a test data).

To summarize: in most real-world cases I guess it won't make sense, but the more complex your data is and the more implicit redundancies or formal constraints your data has got, the more tests maybe a good idea. So think about your real case and apply some common sense - that will surely help ;-)


问:
Why aren't more desktop apps written with Qt?
As far as I know and have understood in my experience with Qt, it's a very good and easy to learn library. It has a very well designed API and is cross-platform, and these are just two of the many features that make it attractive. I'm interested to know why more programmers don't use Qt. Is there a deficiency which speaks against it? Which feature makes other libraries better than Qt? Is the issue related to licensing?</p>

答:
on my own opinion, learning C++ programming is simpler than falling into other languages that hide their complexity, and programmer does not know what really happens in background. Qt on the other hand, adds some benefits over C++, to make it higher level than native C++. Thus Qt C++ is a great framework for who wants to develop low-level tasks, or high-level ones, with a same manner.
C++ is (by some practices) a complex and simple language. Complex for who wants not to challenge with it, simple for one who likes it. Don't leave it for it's complexity!</p>


问:
Importance of diffing and merging for design specifications documentation
The context of this question is choosing tools for writing design specifications for software projects.

These documents will be written and maintained by architects and developers, I'm not talking about marketing requirements. Some of them may be shared outside the team, but only in a processed, non-editable form (PDF, all the docs are assumed being able to be exported to this format).

These are architecture documents, describing the structure of code components, implementation methods, protocols, data formats, etc. They take the form of text with diagrams and identifier names and the occasional code snippets, this isn't about API documentation that might be generated from source files.

The docs will be under source control, fortunately nobody here needs to be educated about that. It's inevitable that versioning will arise over time: we do maintain old versions of the software. Issue tracking might not be adhered to as strictly for documentation as for code.

How important is it to be able to easily compare and merge such documents? We have diverging opinions in the team, ranging from “nobody ever merges documentation and if needed Word has a merge tool” to “merging is crucial and git merge must work”. Note “Word has a merge tool” is something that I quote but don't agree with, having had the painful experience of merging two bugfixes that I had made to two copies of the same document

I have a vague memory of a rule in some company (Google, perhaps, since it's so often cited) that “if you can't merge it, it doesn't exist”, but I'm unable to find it now.

I'm looking for either well-reasoned arguments, or authoritative-looking (and preferably motivated) citations.

答:
For your particular case, I'd say it doesn't matter that much for the following reasons:

It's already a version controlled document, so you can reach back in time to review old versions as necessary.

It's already strictly access controlled for writable copies.

The pain driving you to consider a more easily merged form appears to be a low frequency event as evidenced by the conflicting responses from your fellow teammates.  If they had all experienced that problem on a regular basis then they would support a more easily merged format.

As an alternative solution, consider generating an additional redline document that highlights the changes between versions.  Despite it's many frustrations, MS Word provides change tracking capabilities and can track changes from multiple users within a document. To keep your main line document branch clean, you could create a separate branch for redline documents.

Here are some contraindications that would make me change my answer to "yes, it matters incredibly!"

If the document could be edited by outside of your core team and injected back into the workflow stream, I would insist on easy merge & compare capabilities.  For example, if you were exchanging design documents with a client and the requirements were in high flux then merging would be critical.

If multiple versions of the document exist and are edited at the same time.  The classic scenario here is emailing out a draft spec which is edited by multiple recipients. Those editors then email out to their changes only to their own cadre of reviewers who then repeat the cycle.  (And I've been there, done that on this one.  Document control here hurts!)

If you didn't have a central repository to provide a known, good, latest copy of the document.

If there was a lot of content overlap in the various documents and the overlapping content was subject to frequent change so multiple document updates were required for a single code change.


问:
Is there too much abstraction in the Ruby on Rails community?
Rails, to me, seems like a perfect level of abstraction for most types of web development. However, having watched some seasoned Rails consultants build an application, I'm finding that they use Gems to an extent that it's often pretty difficult to figure out what's going on in the code. As an intermediate-level Rails developer, I've had a pretty hard time digging through their code to figure out how things work, and I'm really struggling to see the payoff of this approach.

So is it me, or does Rails, by dint of the fact that it has such a vibrant community of contributors, kind of encourage over-abstraction?

答:
Staying current is very challenging in the Rails community because of the proliferation of frameworks/components and the speed with which they are adopted by the mainstream. It means it takes work to stay current enough to understand new code, and that old code gets old very fast...

I program Rails only as a hobby and I don't have a prayer of keeping up; I average only one significant project per major release since .11 and I would not even call myself a Rails developer.


问:
What about using MVC as the way to provide Responsive Web Design?
Responsive Web Design shows the user different elements -- or elements arranged in different ways -- by using media queries (if the device is a desktop or laptop, show them this; if a tablet, show them that; if a "phone," show them the other thing) or other methodologies.

What about, though (especially if your app/site uses MVC anyway), leveraging MVC to return different Views based on the type of device / user agent?

Each Model/Controller pair could have at least three Views (desklaptop, tablet, phone, as well as perhaps more granular gradations and/or Views tailored to larger devices) and, based on the size of the user agent's real estate, invoke the appropriate View.

I'm thinking this might be a more natural and easier to implement way of optimizing the experience for all users, at least for those conversant with MVC. How exactly this is implemented (how the user agent is determined and the appropriate Controller ActionResult is invoked) I'm not sure, though... thoughts?

UPDATE

Response to the comment and answer:

I'm thinking more along the lines of this scenario, for which, IMO, media-queries won't satisfactorily handle:

Your app/site has as its centerpiece a map. There are ancillary but vital pieces that are placed around the map (top, botton, and side) that all fit on a tablet (barely) and larger devices just fine. On a phone, though - no way - there's only room for the map, and even then the map is almost too puny.

The only way I can think of to deal with this is to show the map full-screen on the phone, with buttons or links in states like Wyoming, Montana, and Nevada that will invoke the parts that surround the map on larger devices but will monopolize the screen on a phone. In each case, the currently displaying View will need links to [re]open the other portions of the app/site.

Otherwise, the only way it could be usable with a phone is if the user is carrying a magnifying glass around with him (or zooming and swiping around the screen like a madman, but IMO that's a pain in the gluteus maximus).

And so, in such a scenario it seems to me that Views would be easier to implement than altering the CSS, as this is a major renovation of the screen, not just a rearranging of furniture.

答:
I implement responsive design by viewing width, not device or browser type.  This way it's future-proof and useful in unexpected scenarios.  For example, when a new phone comes out with a huge screen and resolution my sites will still be optimized to use it well.

Also, my HTML is identical for every device / resolution.  In the MVC architecture only my CSS is responsible for the responsive design.  There's nothing on the server side which cares, making implementation much easier.  The only possible advantage of pushing some of the work into your controllers might be to not prepare data which isn't visible on smaller screens, but this is rare in my experience and not worth the added complexity.  Then add the fact that browser / device detection is unreliable and you're introducing bugs.

To summarize, responsive design is only a responsibility of the view in MVC, and then it's best handled by just CSS.

UPDATE

In response to your update, your issue is still confined to only the view.  You could still solve this example with only media queries and javascript.  You could also break up your HTML into components that load separately.  But your site's basic functionality is unchanged, keeping your model, controller, and most of your view the same on every device.

Also consider that on an HTTP request to your web app you don't know the resolution of the screen.  You could load an empty page, then use JS to get the current resolution, and AJAX to load the rest of the page (with screen res as a parameter), but that's inefficient and would have to be rerun on every page resize.


问:
things to think of when moving into C-land
Hello

Over the years have I made a programming journey from C in 1990 to Pascal, C++ with I programmed commercially, java VHDL, C# and now I'm taking a look on F#.

In the spring I will go back to study embedded programming in C in a university course so before I do that I will refresh my knowledge in C.

I don't remember much of the C that I learnt and I think I am thankful for that for probably learned some bad habits back then.

I have some questions to get me on the way.

--edit--

To clarify: I am thankful for tips that have been given regarding embedded programming but now I am more interested in relearning C in general. Sorry if my question was unclear,

Compiler, Debugger, IDE? As a microslave I was thinking about 2010 C++ Express, any alternatives?

Where do you find good libraries with code for C. I'm thinking something similar to Boost, POCO in C++

Source for procedural programming patterns and best practices. Where can you find good code learn from?

Thanks in advance

Gorgen

答:
There is a very good chance for embedded C programming that you will end up with using the GNU C compiler to target the destination platform, so you might as well learn to use gcc along with gdb to debug (perhaps even using Emacs as both a C IDE which is pretty good, and as the gdb frontend).

For this you essentially just need any modern Linux distribution which contain all of the above - usually as optional packages just requiring a single command to install.

This looks like a good C tutorial : http://www.faqs.org/docs/learnc/

You will naturally need the K&R manual.  Use ANSI C if you can.


问:
Is it possible to write an operating system in C?
A while back I saw a comment on a Stack Overflow question that surprised me:

No one can write an operating system in C. It is not possible. What
  one can do is write an operating system in a C-based/C-like language
  that adds/defines a considerable amount of non-standard capabilities
  on top of C core.

Is it useful to define C so narrowly? People say Linux, or a GPU driver, or an embedded system was "written in C", not "written in C-with-some-extensions-to-accommodate-the-hardware."

Is it incorrect to do so?

答:
If you allow for the possibility of using device drivers (having a C interface) to communicate with the hardware, there's no reason you couldn't write an OS in ANSI C.  Anything you might need (like naked pointer) that's not present in ANSI C could be provided by the device driver.

I think the writer of that comment is being pedantic to make a point.  He's saying that you can't capture every possible thing that you might need to do in an operating system in the ANSI C language.  I'm not sure I agree; ANSI C is a Turing-complete language, and has many low-level constructs including bit twiddling.

In any case, you quoted him out of context.  Look at one of the additional comments further down in the thread:

...you're making it sound more drastic than it is. A small amount of
  assembly language (inline or in separate files) and a good linker are
  really all you need on most architectures. Other non-standard stuff
  that kernels use (like fiddling with output sections, packing,
  alignment, branch-prediction hints, crazy pointer arithmetic,
  undefined union behaviour) is for optimisation.


答:
Is it incorrect to do so?

It is not "incorrect" to define C that way ... in a particular context.

My intention isn't to snipe at a particular commenter, but to suss out the boundaries of when one can say "X was written in C" and when you really need to say "X was written in a C-like language."

One can say what one likes!  There are no IT terminology laws that say what words mean.

The guy is making a (somewhat pedantic) point by equating "C" with the language that is strictly defined by the ANSI C standards.  But that's OK.  We know what he means.

And the flips-side is that the rest of us can use "C" to mean practical implementations of the C language ... if we want to.

Title: Is it possible to write an operating system in C?

Body:
A while back I saw a comment on a Stack Overflow question that surprised me:

No one can write an operating system in C. It is not possible. What
  one can do is write an operating system in a C-based/C-like language
  that adds/defines a considerable amount of non-standard capabilities
  on top of C core.

Is it useful to define C so narrowly? People say Linux, or a GPU driver, or an embedded system was "written in C", not "written in C-with-some-extensions-to-accommodate-the-hardware."

Is it incorrect to do so?


问:
Why does division and multiplication by 2 use the shift operator rather than division operator?
While looking at the code in C for division/multiplication by 2, it is found that shift operator is used rather than division operator. What is the advantage of using shift over division operator?</p>

答:
Multiplication is complex typically... unless one of the multiplicands is the base the numbers are in themselves.

When working with base 10 math, multiplying by 10 is trivial: "append the same number of zeros as the 10 has".  2 * 10 = 20 and 3 * 100 = 300

This is very easy for us.  The exact same rule exists in binary.

In binary, 2 * 3 = 6 is 10 * 11 = 110,  and 4 * 3 = 12 is 100 * 11 = 1100.

For a system already working with bits (ANDs and ORs), operations such as shift and roll already exist as part of the standard tool set.  It just happens that translating N * 2^M into binary becomes shift N by M places

If we are doing something that isn't a power of 2 in binary, we've got to go back to the old fashioned multiply and add.  Granted, binary is a bit 'easier', but a bit more tedious at the same time.

11 * 14 becomes (from Wikipedia on binary multiplier - a good read as it links to other multiplication algorithms for binary... shifting powers of two is still much easier):

```<code>       1011   (this is 11 in decimal)
     x 1110   (this is 14 in decimal)
     ======
       0000   (this is 1011 x 0)
      1011    (this is 1011 x 1, shifted one position to the left)
     1011     (this is 1011 x 1, shifted two positions to the left)
  + 1011      (this is 1011 x 1, shifted three positions to the left)
  =========
   10011010   (this is 154 in decimal)
</code>```

You can see, we're still doing shifts, and adds.  But lets change that to 11 * 8 to see how easy it becomes and why we can just skip to the answer:

```<code>       1011   (this is 11 in decimal)
     x 1000   (this is  8 in decimal)
     ======
       0000   (this is 1011 x 0)
      0000    (this is 1011 x 0, shifted one position to the left)
     0000     (this is 1011 x 0, shifted two positions to the left)
  + 1011      (this is 1011 x 1, shifted three positions to the left)
  =========
   1011000   (this is 88 in decimal)
</code>```

By just skipping to that last step, we have drastically simplified the entire problem without adding lots of 0s that are still 0s.

Dividing is the same thing as multiplying, just the reverse.  Just as 400 / 100 can be summarized as 'cancel the zeros', so too can this be done in binary.

Using the example of 88 / 8 from the above example

```<code>         1011 r0
     ________
1000 )1011000
      1000
      ----
       0110
       0000
       ----
        1100
        1000
        ----
         1000
         1000
         ----
         0000
</code>```

You can see the steps in the long way of doing long division for binary is again quite tedious, and for a power of two, you can just skip to the answer by in effect, canceling the zeros.

(as a side note, if this is an interesting area for you, you may find browsing the binary tag on Math.SE, well... interesting.)

Body:
Multiplication is complex typically... unless one of the multiplicands is the base the numbers are in themselves.

When working with base 10 math, multiplying by 10 is trivial: "append the same number of zeros as the 10 has".  2 * 10 = 20 and 3 * 100 = 300

This is very easy for us.  The exact same rule exists in binary.

In binary, 2 * 3 = 6 is 10 * 11 = 110,  and 4 * 3 = 12 is 100 * 11 = 1100.

For a system already working with bits (ANDs and ORs), operations such as shift and roll already exist as part of the standard tool set.  It just happens that translating N * 2^M into binary becomes shift N by M places

If we are doing something that isn't a power of 2 in binary, we've got to go back to the old fashioned multiply and add.  Granted, binary is a bit 'easier', but a bit more tedious at the same time.

11 * 14 becomes (from Wikipedia on binary multiplier - a good read as it links to other multiplication algorithms for binary... shifting powers of two is still much easier):

       1011   (this is 11 in decimal)
     x 1110   (this is 14 in decimal)
     ======
       0000   (this is 1011 x 0)
      1011    (this is 1011 x 1, shifted one position to the left)
     1011     (this is 1011 x 1, shifted two positions to the left)
  + 1011      (this is 1011 x 1, shifted three positions to the left)
  =========
   10011010   (this is 154 in decimal)

You can see, we're still doing shifts, and adds.  But lets change that to 11 * 8 to see how easy it becomes and why we can just skip to the answer:

       1011   (this is 11 in decimal)
     x 1000   (this is  8 in decimal)
     ======
       0000   (this is 1011 x 0)
      0000    (this is 1011 x 0, shifted one position to the left)
     0000     (this is 1011 x 0, shifted two positions to the left)
  + 1011      (this is 1011 x 1, shifted three positions to the left)
  =========
   1011000   (this is 88 in decimal)

By just skipping to that last step, we have drastically simplified the entire problem without adding lots of 0s that are still 0s.

Dividing is the same thing as multiplying, just the reverse.  Just as 400 / 100 can be summarized as 'cancel the zeros', so too can this be done in binary.

Using the example of 88 / 8 from the above example

         1011 r0
     ________
1000 )1011000
      1000
      ----
       0110
       0000
       ----
        1100
        1000
        ----
         1000
         1000
         ----
         0000

You can see the steps in the long way of doing long division for binary is again quite tedious, and for a power of two, you can just skip to the answer by in effect, canceling the zeros.

(as a side note, if this is an interesting area for you, you may find browsing the binary tag on Math.SE, well... interesting.)


答: It will not get you a good job (assuming in programming here), but then neither will having a degree.  What matters most is knowledge and experience in the field.  Social sites aren't going to get you the job, they might make a difference in a tie-breaker kind of situation.

Title: Will high reputation on Programmers help to get a good job?

Body:
Possible Duplicate:

  Will high reputation in Stack Overflow help to get a good job?

In reference to this question, do you think that having a high reputation on this site will help to get a good job?

Aside silly and humorous questions, on Programmers we can see a lot of high quality theory questions. I think that, if Stack Overflow will eventually evolve in "strictly programming related" (which usually is "strictly coding related"), the questions on Programmers will be much more interesting and meaningful ("Stack Overflow" = "I have this specific coding/implementation issue"; "Programmers" = "Best practices, team shaping, paradigms, CS theory").

So could high reputation on this site help (or at least be a good reference)? And then, more o less than Stack Overflow?


答:
This a specific optimization that is made in the case that the programmer knows the divisor will be a power of 2.

If the divisor is anything but a power of 2, then this optimization is not possible and code must be rewritten to use regular division.

So, for example, if we have a function that is

dividebyNumberOFWeekendDays ( dividend )

Return dividend >> 1;

We had better hope that our magic number of weekend days never becomes something other than a power of two because then we need to rewrite and unit test the function all over again.

Title: Why does division and multiplication by 2 use the shift operator rather than division operator?

Body: While looking at the code in C for division/multiplication by 2, it is found that shift operator is used rather than division operator. What is the advantage of using shift over division operator?</p>


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
When I started, I searched online for options and it proved challenging to find something you can sink your teeth in as a beginner.

Some projects are difficult to contribute to not because they are too advanced but because the community is not welcoming. So, don't be discouraged when you hit a wall.

During the search, I decided to put together a list of 10 open source projects that beginners can start supporting without much stressful processes. Here is the link to use:

Ten Projects for beginners to support and learn from

I hope you find it helpful and you can always add more if you find cool ones!


问:
What are the reasons to create UIView subclass?
I've noticed that there are a lot of UIView subclasses in my legacy project. Mostly the only reason of such a subclass is to split bigger view into custom subviews and provide layout for its subviews and delegation of UIButtons actions through the view delegate protocol. So I'm wondering, is it a correct design?  </p>

答:
In XCode, every UIButton, UiLabel are UIViews only those predefined UIViews, so when you want to add those to your ViewController, they will be added like:

```<code>[self.view addSubview:aView];
</code>```

We can also create custom UIViews which allow you to design your own complex views like tableViews, GridViews, Charts and so on...

Body:
In XCode, every UIButton, UiLabel are UIViews only those predefined UIViews, so when you want to add those to your ViewController, they will be added like:

[self.view addSubview:aView];

We can also create custom UIViews which allow you to design your own complex views like tableViews, GridViews, Charts and so on...


答:
If you write

```<code> b=a/2;
</code>```

you have to trust the compiler for optimizing it to a "shift" operation on the machine code level (which is typically faster that a general division instruction). And about 25 years ago, when I started working with C compilers, you could not be sure that the compiler worked like this. Today, any decent C compiler knows how to optimize this (at least, when you don't disable the optimizer).

If, however, you write

```<code> b=a>>1;
</code>```

you can be (almost) sure that the compiler generates a shift operation, if you activate the optimizer or not.

Body:
If you write

 b=a/2;

you have to trust the compiler for optimizing it to a "shift" operation on the machine code level (which is typically faster that a general division instruction). And about 25 years ago, when I started working with C compilers, you could not be sure that the compiler worked like this. Today, any decent C compiler knows how to optimize this (at least, when you don't disable the optimizer).

If, however, you write

 b=a>>1;

you can be (almost) sure that the compiler generates a shift operation, if you activate the optimizer or not.


问:
Get rid of long/Complex if..else statements using Chain of Responsibility?
I've an HttpHandler, which allows users to login to a system by passing in an encrypted code.

Inside the ProcessRequest it performs quite a few steps.

Retrieve the encrypted code from request (could be in Form/X-Header/Query)

Decrypt it. (Results in an JSON string)

Deserialize to a dynamic type

Determine the type of request, could be login/register/activate

Validate request

Load user subscription

Load User entity

If Req.Type = Login -> Login using FormsAuth

If Req.Type = Register -> Create user

If Req.Type = Register -> Send Activation email

This goes on. Currently this is something like a long if/else statement which I'm trying to refactor.
I'm thinking of using the Chain Of Responsibility pattern to convert these steps in if/else to a chain which executes sequentially.
However, this will be different from original CoR as only last few steps will actually "handle" the request, first steps will just do some pre-processing and make stage for last steps to perform it's job.

My main problem is, different steps in the chain will work on different input data. First few steps (Decryption, Deserialization, etc) will work on strings while latter half should ideally work on deserialized dynamic object. I don't like the way it sounds.

Am I trying to fit a round lid to an square bottle? Is this not a scenario where CoR can/should be applied? Are there any other patterns/strategies I could use to solve such scenarios.

I thought of using the decorator pattern as well, but that doesn't suite me very well, as I'd like to be able to switch certain steps in and out (ex: email activation) for some scenarios.

NOTE: I've seen this question as well, but not sure if it answers my question.

答:
The question you linked to gives an answer which will probably apply to your situation as well: introducing CoR will have a a high risk of making complicated things even more complicated. "CoR pattern" is fine if you want to modify the chain sequence at run time, which I guess is not the case in your situation above.

So my advice here is:

have a method for each of the first seven steps (with a return value if the step fails).

group the calls of that methods together (perhaps all 7 calls, or you first group intermediate steps together). May result in a method like

```<code> StatusCode PreprocessRequest()
 {
    if(!RetrieveEncryptedCodeFromRequest())
        return StatusCode.RetrieveEncryptedFailed;

    if(!Decrypt())
       return StatusCode.DecryptFailed;

    //...
    return StatusCode.OK;
  }
</code>```

Then call that method like

```<code>  ProcessRequest processor = new ProcessRequest();
  // ...
  StatusCode state = processor.PreprocessRequest();
  if(state==StatusCode.OK)
  {
      Request req = processor.GetRequest();
      HandleRequest(req);
  }
  else
  {
       LogError(state);
  }
</code>```

(Of course, the details may look different in your case, especially the error handling, but I hope you get the idea.)

So, here is the gist: try to make your "if"s less complex by simply grouping things together into methods, make the error handling uniform on each level, make sure to have parts of a method all on the same level of abstraction (otherwise introduce another intermediate method). I guess that will help you to improve the code to a degree where the "complex if/else statements" vanish.

OwnerDisplayName: BuddhiP

Body:
The question you linked to gives an answer which will probably apply to your situation as well: introducing CoR will have a a high risk of making complicated things even more complicated. "CoR pattern" is fine if you want to modify the chain sequence at run time, which I guess is not the case in your situation above.

So my advice here is:

have a method for each of the first seven steps (with a return value if the step fails).

group the calls of that methods together (perhaps all 7 calls, or you first group intermediate steps together). May result in a method like

 StatusCode PreprocessRequest()
 {
    if(!RetrieveEncryptedCodeFromRequest())
        return StatusCode.RetrieveEncryptedFailed;

    if(!Decrypt())
       return StatusCode.DecryptFailed;

    //...
    return StatusCode.OK;
  }

Then call that method like

  ProcessRequest processor = new ProcessRequest();
  // ...
  StatusCode state = processor.PreprocessRequest();
  if(state==StatusCode.OK)
  {
      Request req = processor.GetRequest();
      HandleRequest(req);
  }
  else
  {
       LogError(state);
  }

(Of course, the details may look different in your case, especially the error handling, but I hope you get the idea.)

So, here is the gist: try to make your "if"s less complex by simply grouping things together into methods, make the error handling uniform on each level, make sure to have parts of a method all on the same level of abstraction (otherwise introduce another intermediate method). I guess that will help you to improve the code to a degree where the "complex if/else statements" vanish.


问:
Whats the real overhead of TDD once the entire team is used to it?
What percentage of time is saved and costed doing TDD.

I assume this percentage of cost and reward changes during a projects life-cycle.

I'd imagine the initial phase has a lot more cost but little rewards attached. Further on (during re-factoring) you get the benefit of your tests.

I've heard anywhere from 30-50% of your time is writing unit tests. However that doesn't take into account the time saved from writing those tests. Whats the time saved as well as the time cost? In bug fixing and refactorablity?

答:
I've heard anywhere from 30-50% of your time is writing unit tests. However that doesn't take into account the time saved

In my experience, it's more than 50%.

Once you've written the test, the solution has a tendency to come very easy. So I don't think it's odd to spend 70% - 75% of your time writing tests, but you're spending much less time writing the 'production code' (code-being-tested) and spending virtually no time in the debugger.

The sooner you find a bug, the cheaper it is to fix, and TDD helps with that tremendously. I've worked on projects where the last 2 months (of an 8 month project) were spent fixing bugs, and that phase would be almost entirely eliminated with TDD.

To me though, the real value is in maintenance. Inheriting a code base with tests makes you less scared to alter it. You feel like you didn't break anything when the tests still pass. Since you aren't scared to make changes you're willing to refactor if something isn't right. Which means the code can be made cleaner, the design can fit better, and, in theory, changes can be applied. Contrast that with voodoo code everyone's scared to touch.