答:
When you see a good move, look for a better one.

    —Emanuel Lasker, 27-year world chess champion

In my experience, the biggest driver of accidental complexity is programmers sticking with the first draft, just because it happens to work.  This is something we can learn from our English composition classes.  They build in time to go through several drafts in their assignments, incorporating teacher feedback.  Programming classes, for some reason, don't.

There are books full of concrete and objective ways to recognize, articulate, and fix suboptimal code:  Clean Code, Working Effectively with Legacy Code, and many others.  Many programmers are familiar with these techniques, but don't always take the time to apply them.  They are perfectly capable of reducing accidental complexity, they just haven't made it a habit to try.

Part of the problem is we don't often see the intermediate complexity of other people's code, unless it has gone through peer review at an early stage.  Clean code looks like it was easy to write, when in fact it usually involves several drafts.  You write the best way that comes into your head at first, notice unnecessary complexities it introduces, then "look for a better move" and refactor to remove those complexities.  Then you keep on "looking for a better move" until you are unable to find one.

However, you don't put the code out for review until after all that churn, so externally it looks like it may as well have been a Feynman-like process.  You have a tendency to think you can't do it all one chunk like that, so you don't bother trying, but the truth is the author of that beautifully simple code you just read usually can't write it all in one chunk like that either, or if they can, it's only because they have experience writing similar code many times before, and can now see the pattern without the intermediate stages.  Either way, you can't avoid the drafts.


问:
What are my options for using a C++11 library in a C# WPF application?
I am writing a cross-platform (OS X and Windows) desktop application in C++11. I intend to use the same C++11 core on both platforms, utilizing native frameworks for the UI (Cocoa and Objective-C on OS X and WPF and C# on Windows) as I believe the best UX experience is a native one.

Currently the application runs as a console app on both platforms. The application performs some CPU-intensive work and provides callbacks for progress reporting and, when complete, instantiates a collection of Items (std::vector<std::unique_ptr<Item>>) representing the results of the processing.

My goal is for the C++11 library to act as a model for the UI in a manner compatible with the MVC and MVVM patterns.

The UI must:

Allow the user to choose a file to process (open a file dialog and send the file path to the C++ library)

Display progress (handle callbacks from the C++ library to update a progress bar)

Display the results in a WPF form (access the Item class and display information it provides)

I've looked at WinRT and it seems there isn't a lot of information out there for use in desktop applications.  I'm also not fond of the idea of creating the UI itself in C++.  My goal is to get data in and out of the C++ app and use C# to handle the UI as I believe that's a more efficient way of working with WPF.

I'm aware of P/Invoke but my understanding is that it only works with a C interface. Creating such an interface around the C++11 seems cumbersome.

I'm also aware of C++/CLI but I'm not sure if that will meet my needs or if it is compatible with C++11.

I took a look at CppSharp but it seems to be a work-in-progress and I doubt I'd know how to work around any issues that may arise.

I have a lot of experience with C++ and a little with C# but I'm not sure if I'm missing better options or which of the above is a sound approach.

答:
A part of an answer...

Most times in the solution to this problem you will finish up with 3 layers.

A native C/C++ layer, that can call the Windows API or COM or C++ libraries

A managed C/C++ layer, that can access the C# object model and framework

A C# layer, because it's easier to actually use the .NET Framework and WPF in C#.

P/Invoke refers to the calls between native and managed code, but in this kind of structure they kind of happen inside layer (2). Layer (2) used to be Managed C++ but is now replaced by C++/CLI. Each of the layers can talk to the one next to it easily, but (1) does not easily talk to (3) or vice versa.

You may find a product that just does exactly what you want, but I don't know one. More likely you will have to write what you need with this kind of layered structure.

I've done this 3+ times with 3+ different generations of Managed C/C++, and we have a commercial product built this way (legacy C/C++ <=> ASP.NET/remoting). Each generation the managed layer is different but the overall structure has stayed the same. [edit]

I suggest: write some code, but plan to throw it away. Experimentation is in order.

ContentLicense: CC BY-SA 3.0


问:
How to draw a spiral using segments of varying circles?
I have an old plotter that can't handle printing true spirals.  I need help with developing an algorithm to approximate a spiral.

Here's a LISP sub-script that I have written which uses semicircles of varying radii to draw a spiral:

```<code>(setq inner_radius 1e3)  ; The spiral grows from inner radius to outer radius
(setq coil_thickness 35) ; This is the half-pitch of the spiral, pitch is 70
(setq outer_radius (+ 2.4e3 (* 2 coil_thickness)))
(while (< inner_radius outer_radius)
        (setq P1 (list 0 inner_radius))
        (setq P2 (list inner_radius 0))
        (setq P3 (list 0 (* -1 inner_radius)))
        (setq P4 (list (- (- inner_radius) coil_thickness) coil_thickness))
        (setq P5 (list 0 (+ inner_radius (* coil_thickness 2))))
        (command "ARC" P1 P2 P3) ; Draws a 3 point arc through P1, P2 and P3
        (command "ARC" P3 P4 P5) ; Draws a 3 point arc through P3, P4 and P5
        (setq inner_radius (+ inner_radius (* coil_thickness 2)))
)
</code>```

I am using AutoCAD to implement the script. The code here is a cop-out - I can implement a true spiral in AutoCAD but the plotter, which will plot this, is dated and is not able to handle a true spiral. It can handle just circle arcs and line segments. I am seeking a method which can implement a better approximation of the spiral. For instance, I tried thinking about quartcircles (instead of the semicircles I have used in the above sub-script) but couldn't come up with a viable scheme.

答: Currently you are alternating the center between two points, you can improve your approximation by increasing the number of points.  You are currently using two points separated from pitch/2, you can use three points in an equilateral triangle whose edge is pitch/3, four points in a square with edge pitch/4, ... n points in a regular polygon with n sides whose edges are pitch/n.  Your spiral will then be formed of arc of 360/n degrees with a radius increasing by pitch/n by step.</p>


答:
My first choice would be to just use short line segments to approximate the spiral. A spiral in polar coordinates is just:

```<code>R = a + b * Theta
</code>```

Rough pseudo-code for a spiral generation using line segments should be something like:

```<code>LastPoint = (0, 0)
DeltaTheta = 0.01   //Radians, Make smaller for a finer resolution
NumTurns = 4
CONSTANT_A = 0
CONSTANT_B = 1

For Theta = 0 to NumTurns*2*PI STEP DeltaTheta
   ThisR = CONSTANT_A + CONSTANT_B * Theta
   ThisPoint = (ThisR * cos(Theta), ThisR * sin(Theta))
   DrawLine(LastPoint, ThisPoint)
   LastPoint = ThisPoint
Next Theta
</code>```

If you can make the DeltaTheta parameter small enough you should be able to get a relatively decent looking spiral. For a smoother spiral you may want to look at bezier curves, assuming your plotter supports them. Another option would be to use arbitrary arcs that match the slope of the spiral on each end.

Title: How to draw a spiral using segments of varying circles?

Body:
I have an old plotter that can't handle printing true spirals.  I need help with developing an algorithm to approximate a spiral.

Here's a LISP sub-script that I have written which uses semicircles of varying radii to draw a spiral:

```<code>(setq inner_radius 1e3)  ; The spiral grows from inner radius to outer radius
(setq coil_thickness 35) ; This is the half-pitch of the spiral, pitch is 70
(setq outer_radius (+ 2.4e3 (* 2 coil_thickness)))
(while (< inner_radius outer_radius)
        (setq P1 (list 0 inner_radius))
        (setq P2 (list inner_radius 0))
        (setq P3 (list 0 (* -1 inner_radius)))
        (setq P4 (list (- (- inner_radius) coil_thickness) coil_thickness))
        (setq P5 (list 0 (+ inner_radius (* coil_thickness 2))))
        (command "ARC" P1 P2 P3) ; Draws a 3 point arc through P1, P2 and P3
        (command "ARC" P3 P4 P5) ; Draws a 3 point arc through P3, P4 and P5
        (setq inner_radius (+ inner_radius (* coil_thickness 2)))
)
</code>```

I am using AutoCAD to implement the script. The code here is a cop-out - I can implement a true spiral in AutoCAD but the plotter, which will plot this, is dated and is not able to handle a true spiral. It can handle just circle arcs and line segments. I am seeking a method which can implement a better approximation of the spiral. For instance, I tried thinking about quartcircles (instead of the semicircles I have used in the above sub-script) but couldn't come up with a viable scheme.

Body:
My first choice would be to just use short line segments to approximate the spiral. A spiral in polar coordinates is just:

R = a + b * Theta

Rough pseudo-code for a spiral generation using line segments should be something like:

LastPoint = (0, 0)
DeltaTheta = 0.01   //Radians, Make smaller for a finer resolution
NumTurns = 4
CONSTANT_A = 0
CONSTANT_B = 1

For Theta = 0 to NumTurns*2*PI STEP DeltaTheta
   ThisR = CONSTANT_A + CONSTANT_B * Theta
   ThisPoint = (ThisR * cos(Theta), ThisR * sin(Theta))
   DrawLine(LastPoint, ThisPoint)
   LastPoint = ThisPoint
Next Theta

If you can make the DeltaTheta parameter small enough you should be able to get a relatively decent looking spiral. For a smoother spiral you may want to look at bezier curves, assuming your plotter supports them. Another option would be to use arbitrary arcs that match the slope of the spiral on each end.


问:
Are HSQLDB unit tests an anti pattern?
HSQLDB is great. It (also) has an embedded mode (no dedicated server needed), which allows for quick prototyping of stuff like Proof of Concepts, and it can also be great in production-ready applications, as a quick and simple storage of various data.

However, at least 90% of the projects I've worked on in the past years, if they deal in any way with an SQL database, they will unavoidably have unit tests that use an embedded HSQLDB.

Sure-enough, these projects (which use the standard Maven structure most of the times), have a ton of "unit tests" (or, at least, some kind of tests, but which are located in the "unit-test" area of the project (like "src/test/java")) which use one or more embedded instances of HSQLDB in order to do some CRUD operations and check the results.

My question is: is this an anti-pattern? Does the fact that HSQLDB is easy to integrate and the embedded server is very lightweight make it so that it can be overlooked as "mock-up" of an actual database, when it shouldn't be the case? Shouldn't such tests be treated more like integration-tests (since each of them is composed of "something" AND that "something"'s integration with a database server)? Or am I missing something in the "unit test" definition, and we can infact say that using HSQLDB like this simply adheres to the "mock the dependencies, and test only the unit" part of the "unit test" definition?

答:
I consider using something like HSQLDB (or DBUnit) when testing my DAOs as a necessary step to guarantee quality over the code I write when touching a data layer.
As already pointed out, it is not a bullet-proof solution but in combination with its dialects it can cover a reasonable part of your cases.

My only point would be: let's be careful when we talk about unit-tests. When I test a class interacting with an external component that is sort of out of my control (i.e. it can produce non-deterministic behaviour) I consider it automatically as an integration test.

Assuming that you've factored out the logic where you interact directly with your datastore (via JDBC drivers, ORM, etc.) in a concrete class hidden by an interface, a proper unit-test for your DAO would be developed by passing to it a concrete mocked implementation of the interface that returns a set of well-known values against which you will test it.

Title: Are HSQLDB unit tests an anti pattern?


问:
Scrum: requirements clarification vs changing scope
So we estimate the story and put tasks on the board. Then during the Sprint the UX guy comes up with a user experience for the story that is more complicated than what we originally thought. So on one hand we want to implement the right feature for the user, on the other hand if we had known about the complexity of the UX during Sprint planning, we probably wouldn't have committed to the story.

So what to do in cases such as this?

The same question applies to cases where a usability test or user feedback during the Sprint shows us that we should change the feature.

In general, where do you draw the line between clarification of requirements or adaptations and the changing of scope?

答:
I really like the answer from MetaFight, only one addition, if its usual that in every sprint there are histories with huge changes in complexity during the sprint (and perhaps forcing you to stop the sprint!), this is something important to discuss in the retrospective.

Its very important find the root causes, perhaps you need more collaboration of the UX people in the initial history definition?, perhaps you need smaller histories?, i don't know, but probably your team has a better response than stackoverflow.


问:
Why do you need float/double?
I was watching http://www.joelonsoftware.com/items/2011/06/27.html and laughed at Jon Skeet joke about 0.3 not being 0.3. I personally never had problems with floats/decimals/doubles but then I remember I learned 6502 very early and never needed floats in most of my programs. The only time I used it was for graphics and math where inaccurate numbers were ok and the output was for the screen and not to be stored (in a db, file) or dependent on.

My question is, where are places were you typically use floats/decimals/double? So I know to watch out for these gotchas. With money I use longs and store values by the cent, for speed of an object in a game I add ints and divide (or bitshift) the value to know if I need to move a pixel or not. (I made object move in the 6502 days, we had no divide nor floats but had shifts).

So I was mostly curious.

答:
The primary advantage of floating-point types is that from a run-time perspective, two or three formats (I wish more languages supported 80-bit formats) will sufficient for the fast majority of computational purposes.  If programming languages could easily support a family of fixed-point types, the hardware complexity required for a given level of performance would often be lower with fixed-point types than with floating-point.  Unfortunately, providing such support is far from "easy".

For a programming language to satisfy 98% of applications' numerical needs efficiently, it would have to include dozens of types, and provide define operations for what may be hundreds of combinations; further, even if a programming language had wonderful fixed-point support, some applications would still need to maintain roughly-constant relative precision over a sufficiently large range as to require floating-point.  Given that floating-point math is going to be necessary on some occasions in any event, having hardware vendors focus on math performance with two or three floating-point formats, and having code use those formats whenever they work reasonably well, will generally achieve better "bang for the buck" than would trying to optimize the behavior of fixed-point math.

Incidentally, fixed-point math was more advantageous with 8-bit and 16-bit processors than with 32-bit ones.  On an 8-bit processor, in a situation where 32 bits wouldn't quite suffice, a 40-bit type would only cost 25% more space and 25-50% more time than the 32-bit type, and would require 37.5% less space and 37.5-60% less time than a 64-bit type.  On a 32-bit platform, if a 32-bit type won't suffice for something, there's often little reason to use anything less than 64 bits.  If a 48-bit fixed-point type would be adequate, a 64-bit "double" will work just as well as would the fixed-point type.

Title: Why do you need float/double?


问:
Why doesn't VB.NET allow unnamed, one-line objects to be used?
Why isn't this allowed in VB.NET:

```<code>New SqlCommand("some string", someSqlConnection).ExecuteNonQuery()
</code>```

Why would the language have been designed to require that this be used instead:

```<code>Dim com As New SqlCommand("some string", someSqlConnection)
com.ExecuteNonQuery()
</code>```

It doesn't seem to me like it would have taken much time at all to implement.  Am I wrong?  Is there some theoretical advantage this would give a language?

EDIT

Please read:  I thought this language feature was not supported in VB.NET.  I had forgotten that I had used it in the past, and so when lines like the first one above would break, I did not expect there would be a work-around like in the accepted answer.

...Although, looking back at it again, there seems to be trouble doing this when it's off by itself on a line of code, and not used as a function argument or something.  I bet that's probably part of why I originally posted this.  I wonder why this in particular wouldn't be allowed, but I'm asking a question on SO to see if there's a similar work-around for that...

This is not a question about how to use unnamed objects on a single line; this was a question about why a language designer would intentionally choose to forgo such a feature in a language like this.  Was there a lingual advantage to not allowing this feature, or would it just take unexpectedly long to implement?

There was a misunderstanding, but that does not change the conceptual nature of the original question, and it does not change the fact that it was searching for a logical reason to omit such a feature.

The bottom line is this:  This is a site about "conceptual questions about software development".  This almost immediately implies trace amounts of opinion, subjectiveness, etc - as specifically noted in the very same flag this question was put under.  The rule is to not push it too far, and my question did not.  Please remove the flag.  Thank you.

答:
VB does have this functionality, however the syntax is a bit different (obviously) than C#.
Try (New SqlCommand("some string", someSqlConnection)).ExecuteNonQuery().

Basically, adding the parenthesis around the instantiation of the object tells it to first create the object, then call the method. The code in the question, on the other hand, is trying to tell it to create an object whose type is SqlCommand("some string", someSqlConnection)).ExecuteNonQuery() (which obviously isn't an object type).


答:
IMO:

If a test requires DB, it is not the unit test. It is either integration or acceptance test.

To avoid the need of using DB in a test I should follow inversion of control principle by using dependency injection (or service locator).

If I need to test something with DB, I should create a VM with actual database (with fake or real data, depending on the task). Vagrant and Docker are great tools for the job.

Mocking the DB is a bad practice. It is the same as doing it wrong (mocking DB) and then redoing it right (making it work with real DB).

It is OK for proof-of-concept projects, but still it is then followed by redoing (if concept is proved).

It is perfectly fine to use HSQLDB (or whatever) by itself if it is a proper tool for the job.

Title: Are HSQLDB unit tests an anti pattern?

Body:
HSQLDB is great. It (also) has an embedded mode (no dedicated server needed), which allows for quick prototyping of stuff like Proof of Concepts, and it can also be great in production-ready applications, as a quick and simple storage of various data.

However, at least 90% of the projects I've worked on in the past years, if they deal in any way with an SQL database, they will unavoidably have unit tests that use an embedded HSQLDB.

Sure-enough, these projects (which use the standard Maven structure most of the times), have a ton of "unit tests" (or, at least, some kind of tests, but which are located in the "unit-test" area of the project (like "src/test/java")) which use one or more embedded instances of HSQLDB in order to do some CRUD operations and check the results.

My question is: is this an anti-pattern? Does the fact that HSQLDB is easy to integrate and the embedded server is very lightweight make it so that it can be overlooked as "mock-up" of an actual database, when it shouldn't be the case? Shouldn't such tests be treated more like integration-tests (since each of them is composed of "something" AND that "something"'s integration with a database server)? Or am I missing something in the "unit test" definition, and we can infact say that using HSQLDB like this simply adheres to the "mock the dependencies, and test only the unit" part of the "unit test" definition?


答:
For unit testing data access products like MyBatis, tests using embedded HSQLDB are perfectly fine in my opinion (and I know at least at MyBatis they are using HSQLDB exactly for this).

For most other projects I would consider this overkill.  I would make some simple integration tests (these are tests that potentially have side effects on other tests) that access the real database, ensuring that each query/statement is used at least once.  There should be far less integration tests than unit tests in the project.

For the unit tests, I would mock the DAO or whatever accesses the DB (the 'adaptor').

Title: Are HSQLDB unit tests an anti pattern?


问:
Managing Maven dependencies between multiple components with multiple teams making changes
In a situation where there are multiple teams making changes to some Maven projects with dependencies between them (otherwise unrelated projects i.e. no super POM or anything like that), with each team working in a separate working branch on all of these projects and merging them back to trunk only after a story is complete and tested, how should one handle the dependencies between snapshot builds that each team produces?

Note that any of the teams could be making changes in any of the projects: they work on different pieces of functionality of the same system, and the projects are more like different layers.

Before the split into multiple teams, artifacts were deployed to a central Nexus repository.  Of course, it would be possible to set up separate Nexus repositories for each team, and an additional one for trunk, but I'm hoping there would be a better way to deal with this.

答:
TL;DR: Use release dependencies instead of snapshot ones.

Case to consider when choosing between snapshot and release dependencies is when changes in some component (A) break a dependent component (B).

When this happens, you need to fix it, but there are two options, one of which might turn out preferable depending on your project specifics.

One option is when you prefer to fix the issue immediately, even though it may come at cost of distracting developer working on component A. Benefit of this approach is its conceptual simplicity - it relieves developers from the need to memorize, maintain and update dependencies between components, because instead their efforts are focused on simply keeping all the most recent versions of components in sync.

In this case, release dependencies don't offer anything appealing compared to snapshot ones; rather the opposite - these would introduce an extra step / effort to release updated component A to be able to test whether dependent component doesn't break anymore.

By the way, Maven provides support for a simplest form of snapshot dependency preference: multi-module projects, where handling snapshot dependencies between modules is made as easy as it gets (though this comes at the expense of simultaneous releases, which is sometimes undesirable - eg when components / modules tend to change at very different pace).

An opposite option is when you would prefer to postpone integration fixes in the component A, for example when you believe that in your project it is more important for developer to strongly focus on the changes made in it and switch their efforts to integration later. This could be the case when dependencies between components are "loose", small, carefully designed and slowly changing interfaces.

For example, if you already have carefully crafted, thoroughly tested, clean and convenient interface between components A and B, you may prefer to postpone messing in B while you're polishing changes roughly drafted in A, expecting that it will take less effort to integrate after interface at A side gets clean back again.

In cases like this release dependencies allow you to totally isolate dependent component. You don't need to worry about component B at all, until you are done with A and modify dependency in B to refer desired release. Snapshot dependencies can not offer anything like this: if changes made in A break dependent component, you'll have to put an effort into bringing things back to shape.

Now, let's see how above applies in your case,

unrelated projects

each team working in a separate working branch

split into multiple teams

All of the above whispers, says, cries that team is moving in a direction allowing more independent, more isolated work on the components of the system. So that John working on a project A, Paul working on B, George working on C and Ringo working on D have a leeway in planning and implementing changes within these components without permanently having to look at what happens in other components.

Now, let's look from above perspective at "dependencies between snapshot builds that each team produces". The way how Maven works, this would mean a huge step back into what team is supposed to move away from. the very moment John makes an intermittent change in A and builds a snapshot, Maven immediately picks that snapshot and "broadcasts" it into projects of Paul, George and Ringo!

Now, three guys working in other projects have to adapt to changes made by John and, if these changes cause some serious trouble in other projects, most likely John will have to break his flow and urgently adapt their project to... oh by the way to what is he going to adapt? Paul, George and Ringo, they all work like John, their projects are permanently changing, are they supposed to explain to John what exactly he needs to take into account for today, and what he possibly will have to account for tomorrow?

You see, if team is supposed to move to more independent development of different components / projects, using snapshot dependencies essentially totally breaks this movement and returns you back to the days of monolithic approach.

If you want to keep moving to stronger separated components / projects, you better have to define "communication points" at which these projects would "declare" their readiness / obligation to integrate with others. In Maven, releases naturally serve this purpose.

Maven releases provide stable, fixed "checkpoints" allowing project developer to safely communicate with outer world.

Release 2.15.23 is most recent one ready to be integrated; we no longer support / accept bug reports against releases earlier than 2.14.999; releases 2.15.24 and later ones currently suffer from a critical issue and are by no means intended for integration until further notice.

Worth stressing that release dependencies denote stable "checkpoints" between components, not between people. Whether components are maintained by separate developers or not isn't really relevant.

Even if you have, say, John working in both components A and B or maybe John and Paul together working on these two components, it still makes sense to have release dependencies, to allow programmer focus on work in currently chosen component, without being permanently distracted with worries about how this could impact another.

Given above, you also need to decide between teams how exactly are you going to schedule releases to make integration as smooth as possible. Here your options are really broad. A natural "schedule" that comes to mind is that each team decides when they're ready to offer a "checkpoint" of their work for other teams to integrate.

However natural ad-hoc releases sound "from within" a single team, if you look at it from the perspective of other teams, you may find that they would prefer to have a more regular way to get to "integration checkpoints" - from this perspective, you may wish to consider some predictable ways to "promote" component updates for other teams attention - monthly, or weekly, or maybe daily releases.

Now that your system became more complicated, specifics and purpose of snapshot dependencies are worth taking a closer look at. You can find a pretty decent explanation of this in Maven: The Complete Reference at Sonatype (bold font in below quote is mine):

...when you deploy a snapshot, you are not making a release of a software component; you are releasing a snapshot of a component at a specific time.

Why would you use this? SNAPSHOT versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a SNAPSHOT release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build. Similarly, if the next release of your system is going to have a version "1.4", your project would have a version "1.4-SNAPSHOT" until it was formally released...

If a project depends on a SNAPSHOT, it is not stable as the dependencies may change over time... SNAPSHOT versions are for development only...

As you can see, above stresses temporary, intermittent, unstable nature of snapshot dependencies and limits their applicability to times of "active development". In your case, you can think of temporarily switching to snapshot dependency when you need to do series of closely correlated, synchronized, tightly coupled changes in different components. After this "active" phase is over, you can do "checkpoint" releases of involved components and switch back to release dependencies.

Note by the way that if you discover that switching to snapshot dependency happens too often, this might indicate a need to rethink your design. You may think of ways to better isolate components, or of opposite, that is, of "merging" previously separate components back into monolithic, synchronously developed and released module.


答:
I use approaches like that in the past, i'm not sure if this is an "anti-pattern" (some people try to elevate his personal feelings or experiences to universal rules, i'm not), but i prefer another approach:

For unit test, real unit test don't use external things like an in-memory database (not really lightweight if you compare to a hashMap or a stub using some stub library). If you use DI and a simple patterns like Repository or DAO for your data-access this is very easy to achieve. My objective its to have a lot of unit test that execute really quick, and with quick i'm thinking in 3k test in less than a minute.

For integration test, i prefer to use the real data-storage software in this test, the goal of this test its to prove the integration between my software and the real data-storage, use a different data-storage here breaks the intention of this test. I try to write the less integration test as possible to demonstrate this integration, and usually this test are executed outside of the normal build (for example only in nightly builds)

I use HSQLDB sometimes to build simple demos or proof-of concepts, its a great tool, but i don't see anymore what its the place for this tool in my normal development workflow.

Title: Are HSQLDB unit tests an anti pattern?


问:
Sending e-mails without using an e-mail server
JavaMail sends e-mails using an e-mail server, typically through the SMTP interface of an e-mail provider.  Is it necessary to use an e-mail server to send e-mails?

I have a web site that will send e-mails and if possible I'd like to send the e-mails directly from the web site code without using an e-mail server.  The JavaMail FAQ says that an e-mail server is required.

Is there a way to send e-mails without using an e-mail server, either with JavaMail or another API?

答:
You can deliver an email directly to one of the SMTP servers mentioned in the MX record of the address's domain. Usually that is a bad idea,though:

Delivering the mail to a local server is fast - you can almost immediately continue and do something else and let the server handle the delivery.

The actual delivery can take some time, for instance the remote mail server might be slow. Or it might reject the mail first - it is a known strategy against spam to tell a sender to try sending a mail a second time, which some spam bots won't do.

Also the mail server can easily try again a day later or so when the remote server is down, this reduces risk of lost mail.


问:
What kind of a test is a "consistency check"?
Some or all of the tests I write and run are checks for consistency e.g. assert that if I create a new user account, that the account that was created actually has the same name as the name that was submitted in the registration. And now for checking that I implemented a pagination correctly, I suppose I can check that for any given large resultset, getting the "next page", sometimes repeated times and not only once, will eventually lead to the same last page as getting the last page directly (which is done another way than stepping through one page at a time, going directly to the last page in done by using the reversed order and getting the first page from the reversed order.

In our projects we try to follow test-driven development but sometimes I think it is not exact whether a test is a unit test or an integration test when in fact both the integration tests and the unit tests are mostly or only "constistency checks". I didn't see any other type of test than for consistency (both the unit tests and the integration tests do assertions), but it seems that mocking is used more in integration tests than in unit tests and than a unit test is smaller and for a single component or method while an integration test is "larger", but that is still not an exact difference.

So what kind of a test is a consistency check?  Is it a unit test or an integration test?

答:
I don't know if 'consistency check' is the appropriate name for the kind of tests you describe, really what you describe is simply just a test.

Whether or not it is a unit test or an integration test is really a function of the dependencies/state that the method under test has, and how those dependencies/state are managed.

With your example, if your method under test calls into some service and you mock or fake the service that it's using, then you're more likely writing a unit test. If you're using a legitimate implementation of the service then it's an integration test.

Similarly, if there is some kind of global or external state that your method under tests refers to and you mock/fake that, then you are again writing a unit test.

It's easy to think of the differentiation in the context of code coverage. If your test only covers lines in the method under test, and test code, then it's a unit test. If it covers other code, then it's an integration test (or an incorrectly written unit test).


问:
How to define constants with PECL hidef?
I've recently convinced the team that we could upgrade from php5.4 to 5.5 -- but, unfortunately, it seems I overlooked that php-apc is no longer supported in php 5.5 -- which is fine and dandy, but we could use a replacement for apc_define_constants()

Thus, I've heard about the wonders of hidef -- but, I cannot seem to find any documentation for it, anywhere -- I got it installed, after a bit of kajiggering, but I'm not sure what to do next...

How could I go about unwrapping the various functions included in the pecl hidef package ?

Or, at the very least, how can I use it to define constants?

答:
There is a very small piece of documentation in the INSTALL file of the binary distribution here.

For using hidef you first have to define a configuration directory. Default is /etc/php/hidef, but you can (and should, since /etc/php/ probably doesn't exist) define a directory in your ini as so:

```<code>hidef.ini_path=/etc/php5/hidef/
</code>```

Also, don't forget to make sure the extension is enabled in the .ini, also:

```<code>extension=hidef.so
</code>```

On PHP startup it will scan all files in there and read them in. One might do for instance

```<code>$ echo "int ANSWER = 42;" > /etc/php/hidef/sample.ini
</code>```

on command line and then test using

```<code>$ php -r 'echo ANSWER;'
</code>```

If you try this in a web server you might have to restart it after changing the configuration.

Body:
There is a very small piece of documentation in the INSTALL file of the binary distribution here.

For using hidef you first have to define a configuration directory. Default is /etc/php/hidef, but you can (and should, since /etc/php/ probably doesn't exist) define a directory in your ini as so:

hidef.ini_path=/etc/php5/hidef/

Also, don't forget to make sure the extension is enabled in the .ini, also:

extension=hidef.so

On PHP startup it will scan all files in there and read them in. One might do for instance

$ echo "int ANSWER = 42;" > /etc/php/hidef/sample.ini

on command line and then test using

$ php -r 'echo ANSWER;'

If you try this in a web server you might have to restart it after changing the configuration.


答:
It all depends on what you mean by "use" exactly.

If "use" includes only the direct use of an email server, then you might pass the mail to send through some other kind of service indirectly to an email server. For practical use cases, this seems to be a "Good Enough™" solution to me.

If, however, your question means literally "without involving any email server at all", this would be only possible, if your software is able to put the mail into the inbox of the target client by some way of your choice, but except POP3 or IMAP or any other email-relevant protocol used in email context (because, if you would use such an protocol, that particular program would act as the mail server, which is not allowed)

To answer the question: Yes. At least in theory.

Title: Sending e-mails without using an e-mail server

Body:
JavaMail sends e-mails using an e-mail server, typically through the SMTP interface of an e-mail provider.  Is it necessary to use an e-mail server to send e-mails?

I have a web site that will send e-mails and if possible I'd like to send the e-mails directly from the web site code without using an e-mail server.  The JavaMail FAQ says that an e-mail server is required.

Is there a way to send e-mails without using an e-mail server, either with JavaMail or another API?


问:
Our flavor of Scrum
In my organization we almost never finish all the stories in the Sprint, and most of the stories are finished about 80%.

One reason for this, is that many times testers don't have enough time to test all the stories, and developers don't want to test. Another reason is that the teams are usually too optimistic so they commit to more than they can complete, and no one really cares about that, so they continue to do it each Sprint. Usually testing, bug fixes and last polishes remain on the task board after the Sprint is over.

The R&D manager believes that its not that bad to leave some bugs unfixed or to skip some non critical implementation, because then he can have usability test for the new features faster. Nevertheless I think he would be happy if the team could finish all the testing and bug fixes, but if not that's completely okay for him as well, because there are always some stabilization (hardening) sprints at the end in which the smaller stuff will be taken care of.

I'd like to ask you, what do you think about this development method (which is not pure Scrum, but a more flexible/weak version of it).

Thank you.

答:
It's unacceptable to release untested work. There needs to be communication on what needs to be tested, how much time it will take, and how to know when everything works.

You say your team is using a Scrum variant. Are you estimating your stories? Are you testers involved in that estimation? Do you track how many points you actually completed beside how many you committed to?

The reason to use story points is to track velocity. That metric is supposed to be fed into the next sprints, adjusting the amount of work you commit to accordingly. If you don't track completed points or don't adjust future sprints using that evidence, you'll either constantly be wasting time or constantly falling behind (which it sounds like you are).

My suggestions based on the information given are:

Be sure your testers are involved in planning and agree with the story estimations

Define "done". The point of a sprint is to deliver a working, tested artifact. If you can't in the time allotted, cut scope so that what is delivered is of good quality.

Track your previous sprints. You don't need many, just three or four iterations. If you find that you took on too much previously, commit to less this sprint.

Title: Our flavor of Scrum


问:
How do I manage a very large set of rules and magic numbers in my program?
I'm somewhat new to programming (I'm a mechanical engineer by trade), and I'm developing a small program during my downtime that generates a (solidworks) part based on input from various people from around the plant.

Based on only a few inputs (6 to be exact), I need to make hundreds of API calls that can take up to a dozen parameters each; all generated by a set of rules I've gathered after interviewing everyone that handles the part. The rules and parameters section of my code is 250 lines and growing.

So, what is the best way to keep my code readable and manageable? How do I compartmentalize all my magic numbers, all the rules, algorithms, and procedural parts of the code? How do I deal with a very verbose and granular API?

My main goal is to be able to hand someone my source and have them understand what I was doing, without my input.

答:
Based on what you describe, you're probably going to want to explore the wonderful world of databases.  It sounds like many of the magic numbers you describe - particularly if they are part dependent - are really data, not code.  You'll have much better luck, and find it far easier to extend the application in the long run, if you can categorize how the data relates to the parts and define a database structure for it.

Keep in mind, 'databases' don't necessarily mean MySQL or MS-SQL.  How you store the data is going to depend a lot on how the program is used, how you are writing it, etc.  It may mean an SQL type database, or it may simply mean a formatted text file.


答:
Things finished at X% (user histories are done or not done)

Developers that don't want to test

People that don't care about continuos improvement (making better estimations its continuos improvement)

Stabilization sprints

For me this are BIG flaws in your actual process. I see the same or very similar problems a lot of times. One of the main benefits of Scrum its discover this flaws, when scrum make visible this problems there are two possible reactions:

Try to find the root causes of this problems and improve your process, retrospectives and a critical (but constructive) spirit its key here.

"Our world its different, scrum is some ideal thing that cannot be done, we need more flexibility."... and nothing changes...

Title: Our flavor of Scrum

Body:
In my organization we almost never finish all the stories in the Sprint, and most of the stories are finished about 80%.

One reason for this, is that many times testers don't have enough time to test all the stories, and developers don't want to test. Another reason is that the teams are usually too optimistic so they commit to more than they can complete, and no one really cares about that, so they continue to do it each Sprint. Usually testing, bug fixes and last polishes remain on the task board after the Sprint is over.

The R&D manager believes that its not that bad to leave some bugs unfixed or to skip some non critical implementation, because then he can have usability test for the new features faster. Nevertheless I think he would be happy if the team could finish all the testing and bug fixes, but if not that's completely okay for him as well, because there are always some stabilization (hardening) sprints at the end in which the smaller stuff will be taken care of.

I'd like to ask you, what do you think about this development method (which is not pure Scrum, but a more flexible/weak version of it).

Thank you.


问:
What use is a non-zeroing weak reference?
When reading about the various options for working with things like ARC / GC, I often come across explicit wording about which weak references are zeroing (ie, your reference becomes nil/null/0 when the object is collected) and which non-zeroing (you get a dangling pointer). This leads me to ask: What possible use could there be for a non-zeroing weak pointer? You can't use it for anything if you're not sure whether it's any good, can you? And how would you check its validity without risking a core dump / segfault?

Addendum: I understand they're useful in reference-counted environments, and you may want to use them when writing library code that may be used therein, but I can't see a good reason for them with a smart-enough ARC-alike or relocating collector. What good is a reference that can't be relied on?

答:
Weak references are important in the context of a reference-counting memory-management scheme. For example, we might have a tree data structure where each node knows its parent node. The result is a circular data structure. When we give up all known references to the root of the tree, the tree isn't freed because the references from child nodes to the root nodes prevent the refcount from dropping to zero.

This can be avoided with weak references. When each reference from a child to its parent is a weak reference (a reference that does not affect the reference count), then a reference from one of our variables to the root of the tree is the only counting reference. If we remove that reference, the refcount hits zero (or not, if other references were made), and the memory can be reclaimed.

The implication here is that as long as we are interested in nodes of the tree, we will also keep the root of the tree itself around. Therefore, the weak references to a parent node will always stay valid.

An interesting example of a tree with such properties is the Document Object Model for XML or HTML documents. A node in the DOM cannot exist separately from the document (or document fragment) which it belongs to. The DOM contains accessors that allow an implementation to maintain referential integrity even when implemented with weak references or pointers.

There are a few important observations.

Weak references are largely unnecessary with more sophisticated memory management schemes like garbage collection. For example, we could halt the execution of a program and in the graph of all references find all disconnected subgraphs. All of these disconnected subgraphs except the main one can be collected (although implementing the semantics of destruction can be difficult. Also, this makes the RAII-idiom impossible or difficult).

As pointed out in the comments, some notifier implementations can benefit greatly from (zeroing) weak references even in the context of GC'd languages.

Weak references are basically equivalent to ordinary pointers. You have to structure your program in a way to guarantee that it always points to something valid. While sometimes difficult, experience has shown that this isn't exactly impossible (e.g. by keeping the context around).

An implementation that sets weak references to null when the referenced object is freed can be highly inefficient, as we need a reference from the referenced object back to the reference itself, so that it can be reset on freeing.

The other option would be to access each object only through a proxy, where weak references only increase the proxy refcount, and normal references increase both the refcount of the proxy and the actual object. When the inner object's refcount is zero, the proxy has to be notified about the destruction to set it's internal pointer to null. This implies that a weak reference of this design needs deep integration with the runtime's memory management and can't really be added later as a library. This is more memory-efficient, at the expense of adding one additional pointer level to each access.


答:
In Objective-C, non-zeroing weak references exist primarily for compatibility reasons.  When executing ARC code on iOS 4, a runtime called ARC-lite is used which supports the majority of ARC except for zeroing weak references.

If you set your project to target iOS 4, Xcode will refuse to compile code that uses the weak keyword.

Apple also explicitly recommends unsafe_unretained rather than weak when working with certain classes, again for compatibility reasons with older code.

There is also a small performance cost to accessing weak references, although for most purposes this is negligible.

Title: What use is a non-zeroing weak reference?

Body:
When reading about the various options for working with things like ARC / GC, I often come across explicit wording about which weak references are zeroing (ie, your reference becomes nil/null/0 when the object is collected) and which non-zeroing (you get a dangling pointer). This leads me to ask: What possible use could there be for a non-zeroing weak pointer? You can't use it for anything if you're not sure whether it's any good, can you? And how would you check its validity without risking a core dump / segfault?

Addendum: I understand they're useful in reference-counted environments, and you may want to use them when writing library code that may be used therein, but I can't see a good reason for them with a smart-enough ARC-alike or relocating collector. What good is a reference that can't be relied on?


答:
Source code repositories have branches, binary ones don't. So any part of your development plan that relies on branching can't rely on binary repositores for things that are in the scope of branches.

(One exception to the above is ClearCase, which does do both, and is best not spoken of.)

If the teams are to be independant, you really do need to manage the dependencies in terms of released versions. This will be painful; what you are doing is hard. Probably have to get used to planning and discussing changes in advance, abandoning ad-hoc refactoring.

On the other hand, perhaps the teams are really only nominal, e.g. everyone is all working together to a single overall product release/delivery schedule. Then just keep to a single overall version number that gets bumped any time a feature branch is merged back to master. All local dependencies then simply use {project.version}.

Note that this is still not a snapshot, as you never update it without changing the number.

And then within a team share code not binaries. Some extra recompilation, but if that takes more than 15 seconds, get faster PCs. And anyone not using a multi-module IDE like eclipse will have to write a trivial reactor-build POM to cover the set of modules they are currently working on.

See:

http://books.sonatype.com/m2eclipse-book/reference/eclipse.html

http://axelfontaine.com/blog/final-nail.html

http://ahoehma.wordpress.com/2010/12/22/intermodule-dependencies-now-better-working-with-maven-3/

For how to set up an IDE, CI build server and reactor build for this kind of situation.

Or, you could try reimplementing ClearCase with some scripting on top of git+Nexus (don't do this).

Title: Managing Maven dependencies between multiple components with multiple teams making changes

Body:
In a situation where there are multiple teams making changes to some Maven projects with dependencies between them (otherwise unrelated projects i.e. no super POM or anything like that), with each team working in a separate working branch on all of these projects and merging them back to trunk only after a story is complete and tested, how should one handle the dependencies between snapshot builds that each team produces?

Note that any of the teams could be making changes in any of the projects: they work on different pieces of functionality of the same system, and the projects are more like different layers.

Before the split into multiple teams, artifacts were deployed to a central Nexus repository.  Of course, it would be possible to set up separate Nexus repositories for each team, and an additional one for trunk, but I'm hoping there would be a better way to deal with this.


问:
Is there a way to find out what API's to use for developing a third party app
My company uses an application called TotalHRWorks for time keeping and what not. They have an Android and iOS application; however, there is no Windows Phone application. Since there is an Android and iOS app, I figure that I should be able to create a Windows Phone app; but I don't know where to start with trying to discover maybe their web service or whatever APIs that I could use to make it. I don't know whether this can be done or if it's "legal" to do such things - but it would be really handy to have.</p>

答:
If you're lucky they'll be communicating with their server over unencrypted HTTP.

If you're mildly lucky they'll be using HTTPS without cert pinning.

If you're really unlucky they'll be using HTTPS with cert pinning, or something altogether different.

Regular ol' HTTP is easy to snoop using tools like Fiddler.  If HTTPS is involved you can use Fiddler to issue a Root Certificate and get your phone to trust it.  That will allow Fiddler to snoop into HTTPS traffic... unless the app uses cert-pinning.

If they're not using HTTP-based communication you could look into using wireshark (which is a bit lower level) to try and reverse engineer what's going on.

I got lucky once and managed to reverse engineer a game's API and write my own cheat client.

It was lot's of fun!  So much fun that the dev team eventually emailed me asking me to stop :)


问:
Using configuration to determine whether to handle exception or bubble it up
On a side project I'm working on I came up with a way of handling exceptions that's adjustable by configuration. So a try/catch block might look like this:

```<code>try
{
    fileHelper.MoveFile(file, destFolder);
}
catch (IOException ex)
{
    if (exceptionHandler.HandleException(ex))
    {
        return ResultCode.Fail;
    }
    throw;
}
</code>```

The granularity of exception handling is controlled through an enum that's set in the app.config file:

```<code>public enum SystemFailureMode
{
    AlwaysThrow = -1,
    Aggressive = 0,
    Standard = 1,
    Lenient = 2
}
</code>```

This determines whether an exception is "handled" and returned as an error, or if it bubbles up and crashes the system. At first I thought I'd uncovered a new design pattern but now it seems like it's probably an anti-pattern. What do you guys think?

After reviewing the comments and thinking about it myself, I've decided this is definitely an anti-pattern. The fact that this has the potential to turn writing unit tests into a nightmare is enough to turn me off of it.

答:
In my opinion, the nicest way for Exception handling in C# is the same exposed in this article:
http://johannesbrodwall.com/2014/02/07/c-tricks-slimming-down-your-controllers/
(look for "Exception handling")

Please note that the same pattern can be used for Java: http://johannesbrodwall.com/2013/09/25/offensive-programming/

The most important concept is:

"(almost)Never handle exceptions locally"

That's the simplest and the cleanest way to handle exceptions in both Java and C#.
In your case you catch the exception everytime it can happen and then you configure how to handle them, am I right? Now isn't that a hint that you should centralize the exception handling elsewere? Instead of repeating the same pattern try - catch -handleExceptionInAConfigurableWay - throw every time.
I personally don't see any point in configuring a global FailureMode to handle exceptions, if you have an ApplicationFilter like the one in the 1st article, and you want to change how Exception are handled, just change the behaviour of the OnException template method.

Result:

+1: The actual handling of exceptions should be centralized

-10: Not in this way!

Of course it's not possibile to throw always an Exception and handle it in a single "application filter" point.
Sometimes you have some operations to do in case of exceptions (e.g. rollback a transaction), or in every case (e.g. an open file to close in finally block), but in any other situations, if you have to just log the exception stacktrace or pop an error message in some GUI, then just throw the exception and handle it in a single global point.

Using Exceptions as a part of your business logic has never been a good pattern, and the epic failure of Java checked exception is a proof of that.


问:
How to deal with frequent requirements changes?
I'm dealing with pretty stressful (in my opinion) situation in my current work place.

We've started developing new project, get some requirements, implemented it and then show to someone you can call a 'business advisor' (person who knows business requirements but will not use the program). That person is supposed to evaluate application from customers point of view, test it etc.

Here how the 'process' looks:

business advisor talks in the evening with my boss for hour or two on windows messenger

the next day I receive email with copy of that conversation. I am supposed to choose tasks from that, check reported bugs (which often aren't bugs, just poor testing and forgetting about past establishments)

I implement changes, implementation gets accepted and then in a week or two it turns out that isn't want they want (they talked with some potential client that have seen software for 5 minutes and he suggested changes) - I have to do new changes

Don't get me wrong, I understand that sometimes requirements change. What upsets me is how often the change occur in my workplace and how easy for 'management' is two give new requirements or sometimes fundamental changes to existing features.

At the same we working on tight deadlines and I have impression that instead of going forward with our software we're running circles.

I seek advise from you how to deal with this situation? Is this normal situation and I'm just hypersensitive about it?

答:
Requirement changes are not always bad.  The key thing is to remember your customer.  Likely your boss is your customer in this case.  You need to notify your boss that you thing these constant requirement changes are limiting your ability to produce the product which is most useful to him.  It is entirely possible that the business benefits from you constantly reacting to changes.  If so, that is their business model, and you are doing nothing wrong, though I recommend running for the hills in that case!

People who are frustrated with requirement changes are often valued by how well they manage each change.  This metric of "number of changes sufficiently handled" is probably the source of your real trouble.  Consider discussing better metrics with your boss.  When I am facing constantly changing requirements, I strive to write content that lets me adapt to constantly changing requirements.  Instead of running a simulation and analyzing the data every day, I will write tools which make the process of running the simulation and analyzing the data cheaper, and reap the rewards over time.  If that is still too crazy, I might even write a tool to write tools!


答:
It depends on the definition of "exception"

What does it mean to have an exception?  The usual thinking is that something prevented execution from going normal.  Something is "wrong."  If it is not handled, nothing in the future will be "right."

The big question for you is, "what is the state of the system when the exception is thrown?"  What you are talking about is adjustable logic in the recovery after an exception is thrown.  Whether that makes sense or not is TREMENDOUSLY case specific.  It needs to make logical sense to say "let the user decide whether I should stop here, or if I should do my backup plan."  If it makes sense to leave that choice in the hands of the user, by goodness, do it!  If that feels funny, you probably should not give them such power.  In some cases, exception cleanup is a VERY messy business, and letting the user in on that dirty little escapade can lead in very bad directions.

That being said, I have seen the extreme version of your pattern: there was one exception handler for the whole program.  If an exception was thrown, and PRODUCTION_MODE was chosen, the entire program virtually restarted.

Title: Using configuration to determine whether to handle exception or bubble it up

Body:
On a side project I'm working on I came up with a way of handling exceptions that's adjustable by configuration. So a try/catch block might look like this:

```<code>try
{
    fileHelper.MoveFile(file, destFolder);
}
catch (IOException ex)
{
    if (exceptionHandler.HandleException(ex))
    {
        return ResultCode.Fail;
    }
    throw;
}
</code>```

The granularity of exception handling is controlled through an enum that's set in the app.config file:

```<code>public enum SystemFailureMode
{
    AlwaysThrow = -1,
    Aggressive = 0,
    Standard = 1,
    Lenient = 2
}
</code>```

This determines whether an exception is "handled" and returned as an error, or if it bubbles up and crashes the system. At first I thought I'd uncovered a new design pattern but now it seems like it's probably an anti-pattern. What do you guys think?

After reviewing the comments and thinking about it myself, I've decided this is definitely an anti-pattern. The fact that this has the potential to turn writing unit tests into a nightmare is enough to turn me off of it.


问:
Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.

答:
The only thing I would use PHP for is web programming. But it is the only thing I would use for web programming.

I don't really like OOP so python and ruby really have no appeal for me. I learned a lot from my 2 years of professional full-time Rails and it changed the way I write PHP. I suspect most PHP programmers would my PHP code. And the aspect I like best about Django (just from ready the introduction in '08) is the template engine and we have Smarty, so…

So… yes I went back to PHP. And I like it! I still cringe a little when I have to type out array( instead of [ but on the other hand I love that arrays are always ordered-maps. That is just plain handy, at least for web type programming.

(I love javascript bestest of all, could you imagine if there was some baller server-side run-time?!)

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Matt


问:
How to manage accidental complexity in software projects
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:

Write down the problem.

Think real hard.

Write down the solution.

Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.

So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?

答:
Accidental Complexity

The original question (paraphrased) was:

How do architects manage accidental complexity in software projects?

Accidental complexity arises when those with direction over a project choose to append technologies that are one off, and that the overall strategy of the project's original architects did not intend to bring into the project. For this reason it is important to record the reasoning behind the choice in strategy.

Accidental complexity can be staved off by leadership that sticks to their original strategy until such time as a deliberate departure from that strategy becomes apparently necessary.

Avoiding Unnecessary Complexity

Based on the body of the question, I would rephrase it like this:

How do architects manage complexity in software projects?

This rephrasing is more apropos to the body of the question, where the Feynman algorithm was then brought in, providing context that proposes that for the best architects, when faced with a problem, have a gestalt from which they then skilfully construct a solution, and that the rest of us can not hope to learn this. Having a gestalt of understanding depends on the intelligence of the subject, and their willingness to learn the features of the architectural options that could be within their scope.

The process of planning for the project would use the learning of the organization to make a list of the requirements of the project, and then attempt to construct a list of all possible options, and then reconcile the options with the requirements. The expert's gestalt allows him to do this quickly, and perhaps with little evident work, making it appear to come easily to him.

I submit to you that it comes to him because of his preparation. To have the expert's gestalt requires familiarity with all of your options, and the foresight to provide a straightforward solution that allows for the foreseen future needs that it is determined the project should provide for, as well as the flexibility to adapt to the changing needs of the project. Feynman's preparation was that he had a deep understanding of various approaches in both theoretical and applied mathematics and physics. He was innately curious, and bright enough to make sense of the things he discovered about the natural world around him.

The expert technology architect will have a similar curiosity, drawing on a deep understanding of fundamentals as well as a broad exposure to a great diversity of technologies. He (or she) will have the wisdom to draw upon the strategies that have been successful across domains (such as Principles of Unix Programming) and those that apply to specific domains (such as design patterns and style guides). He may not be intimately knowledgeable of every resource, but he will know where to find the resource.

Building the Solution

This level of knowledge, understanding, and wisdom, can be drawn from experience and education, but requires intelligence and mental activity to put together a gestalt strategic solution that works together in a way that avoids accidental and unnecessary complexity. It requires the expert to put these fundamentals together; these were the knowledge workers that Drucker foresaw when first coined the term.

Back to the specific final questions:

Specific methods to tame accidental complexity can be found in the following sorts of sources.

Principles of Unix Programming

Design Patterns

and Style Guides (e.g. Python's PEP 8)

Following the Principles of Unix Programming will have you creating simple modular programs that work well and are robust with common interfaces. Following Design Patterns will help you construct complex algorithms that are no more complex than necessary. Following Style Guides will ensure your code is readable, maintainable, and optimal for the language in which your code is written. Experts will have internalized many of the principles found in these resources, and will be able to put them together in a cohesive seamless fashion.


答:
Unless you anticipate extending this to multiple parts I'd be reluctant to add a database just yet. Having a database means a big pile of stuff to learn for you, and more stuff to install to get it to work for other people. Adding an embedded database keeps the final executable portable, but someone with your source code now has one more thing to get working.

I think a list of clearly named constants and rule-implementing functions will help a lot. If you give everything natural names and focus on  literate programming techniques you should be able to make a readable program.

Ideally you'll end up with code that says:

```<code>LeftBearingHoleDepth = BearingWidth + HoleDepthTolerance;
if (not CheckPartWidth(LeftBearingHoleDepth, {other parameters})
    {whatever you need to adjust}
</code>```

Depending on how local the constants are I'd be tempted to declare them in the functions they're used in where possible. It's quite useful to turn:

```<code>SomeAPICall(10,324.5, 1, 0.02, 6857);
</code>```

into

```<code>const NumberOfOilDrainHoles = 10
const OilDrainHoleSpacing = 324.5
{etc}
SomeAPICall(NumberOfOilDrainHoles, OilDrainHoleSpacing, {etc}
</code>```

That gives you largely self-documenting code and also encourages anyone who modifies the code to give similarly meaningful names to what they add. Starting local also makes it easier to deal with the total number of constants you'll accumulate. It gets a bit annoying if you have to keep scrolling through a long list of constants to make sure the value is the one you want.

One tip for names: put the most important word on the left. It may not read quite as well, but it makes finding things easier. Most of the time you're looking at a sump and wondering about the bolt, not looking at a bolt and wondering where it does, so call it SumpBoltThreadPitch not BoltThreadPitchSump. Then sort the list of constants. Later, to extract all the thread pitches you can get the list in a text editor and either use the find function, or use a tool like grep to return only the lines that contain "ThreadPitch".

Title: How do I manage a very large set of rules and magic numbers in my program?

Body:
I'm somewhat new to programming (I'm a mechanical engineer by trade), and I'm developing a small program during my downtime that generates a (solidworks) part based on input from various people from around the plant.

Based on only a few inputs (6 to be exact), I need to make hundreds of API calls that can take up to a dozen parameters each; all generated by a set of rules I've gathered after interviewing everyone that handles the part. The rules and parameters section of my code is 250 lines and growing.

So, what is the best way to keep my code readable and manageable? How do I compartmentalize all my magic numbers, all the rules, algorithms, and procedural parts of the code? How do I deal with a very verbose and granular API?

My main goal is to be able to hand someone my source and have them understand what I was doing, without my input.

Body:
Unless you anticipate extending this to multiple parts I'd be reluctant to add a database just yet. Having a database means a big pile of stuff to learn for you, and more stuff to install to get it to work for other people. Adding an embedded database keeps the final executable portable, but someone with your source code now has one more thing to get working.

I think a list of clearly named constants and rule-implementing functions will help a lot. If you give everything natural names and focus on  literate programming techniques you should be able to make a readable program.

Ideally you'll end up with code that says:

LeftBearingHoleDepth = BearingWidth + HoleDepthTolerance;
if (not CheckPartWidth(LeftBearingHoleDepth, {other parameters})
    {whatever you need to adjust}

Depending on how local the constants are I'd be tempted to declare them in the functions they're used in where possible. It's quite useful to turn:

SomeAPICall(10,324.5, 1, 0.02, 6857);

into

const NumberOfOilDrainHoles = 10
const OilDrainHoleSpacing = 324.5
{etc}
SomeAPICall(NumberOfOilDrainHoles, OilDrainHoleSpacing, {etc}

That gives you largely self-documenting code and also encourages anyone who modifies the code to give similarly meaningful names to what they add. Starting local also makes it easier to deal with the total number of constants you'll accumulate. It gets a bit annoying if you have to keep scrolling through a long list of constants to make sure the value is the one you want.

One tip for names: put the most important word on the left. It may not read quite as well, but it makes finding things easier. Most of the time you're looking at a sump and wondering about the bolt, not looking at a bolt and wondering where it does, so call it SumpBoltThreadPitch not BoltThreadPitchSump. Then sort the list of constants. Later, to extract all the thread pitches you can get the list in a text editor and either use the find function, or use a tool like grep to return only the lines that contain "ThreadPitch".


问:
Why most "well-known" imperative/OO languages allow unchecked access to types that can represent a 'nothing' value?
I have been reading about the (un)convenience of having null instead of (for example) Maybe. After reading this article, I am convinced that it would be much better to use Maybe (or something similar). However, I am surprised to see that all the "well-known" imperative or object oriented programming languages still use null (which allows unchecked access to types that can represent a 'nothing' value), and that Maybe is mostly used in functional programming languages.

As an example, look at the following C# code:

```<code>void doSomething(string username)
{
    // Check that username is not null
    // Do something
}
</code>```

Something smells bad here... Why should we be checking if the argument is null? Shouldn't we assume that every variable contains a reference to an object? As you can see, the problem is that by definition almost all variables can contain a null reference. What if we could decide which variables are "nullable" and which not? That would save us a lot of effort while debugging and looking for a "NullReferenceException". Imagine that, by default, no types could contain a null reference. Instead of that, you would state explicitly that a variable can contain a null reference, only if you really need it. That is the idea behind Maybe. If you have a function that in some cases fails (for example division by zero), you could return a Maybe<int>, stating explicitly that the result may be an int, but also nothing! This is one reason to prefer Maybe instead of null. If you are interested in more examples, then I suggest to read this article.

The facts are that, despite the disadvantages of making most types nullable by default, most of the OO programming languages actually do it. That is why I wonder about:

What kind of arguments would you have to implement null in your programming language instead of Maybe? Are there reasons at all or is it just "historical baggage"?

Please ensure you understand the difference between null and Maybe before answering this question.

答:
"Maybe," as written, is a higher level construct than null.  Using more words to define it, Maybe is, "a pointer to either a thing, or a pointer to nothing, but the compiler has not yet been given enough information to determine which one."  This forces you to explicitly check each value constantly, unless you build a compiler specification that is smart enough to keep up with the code you write.

You can make an implementation of Maybe with a language that has nulls easily.  C++ has one in the form of boost::optional<T>.  Making the equivalent of null with Maybe is very difficult.  In particular, if I have a Maybe<Just<T>>, I cannot assign it to null (because such a concept does not exist), while a T** in a language with null is very easy to assign to null.  This forces one to use Maybe<Maybe<T>>, which is totally valid, but will force you to do many more checks to use that object.

Some functional languages use Maybe because null requires either undefined behavior or exception handling, neither of which is an easy concept to map into functional language syntaxes.  Maybe fills the role much better in such functional situations, but in procedural languages, null is king.  It's not a matter of right and wrong, just a matter of what makes it easier to tell the computer to do what you want it to do.


问:
Studies on how well can a programmer understand code in unfamiliar languages?
Are there any serious studies on how well an experienced programmer who knows language X can understand code written by a competent programmer using language Y, for a good range of widely used languages as X and Y?

Of course the real world isn't so simple as a programmers knows just one language.  What we'd like to know is: if we do our project in, say, C#, and someday some old physicists who know only Fortran and Algol look at it, to what extent would it make sense to them?  Mathematical parts of it might read fine to them, if they ignore what to them are some random-ish punctuation marks.  Or, would a Python expert be able to find flaws in my clever Ruby script?

There could be issues from the level of superficial syntax to the level of grand concepts such as objects, template metaprogramming, functional and so on.  I'm not expecting the one programmer to fully understand every syntax detail of code in a "foreign language" or to follow the religion of some grand concept, but wondering to what extent they'd get the main flow of control, find the spot where something is drawn on the screen and what determines its color or size, verify that a robot programmed to drive a car will turn off the engine when it's done, those sorts of things.

A good quality study would include published academic research, an official report from some industry group or major software company, though I'll take systematic unbiased observations by experienced leaders of workshops and classes or other sources.  Not interested in short blogs, single-case examples, or anecdotes.  (Well, maybe a few anecdotes if they make for a good read.)

答:
It depends tremendously on the individual programmer, and how they internalize languages.  I have absolutely no trouble working in a dozen languages, while I have a friend that only knows C++.  He is no worse at programming than me, he just learned a different way.

Personally, I find a related question more interesting: when there is a bug in the code (i.e. programmer X thought he wrote someFunction(x, y) but he really wrote something else), how hard is it for the second developer to identify the bug.  A good programmer X would make it exceedingly obvious what he WANTED the computer to do, and that would be easy to read.  However, if he made a mistake, it can be a big deal.  Things like the following C++ bug:

```<code>int x = getCorrectValueForX();
if (x = 2)
   doSomethingWhenXIsTwo();
</code>```

Can be NOTORIOUSLY difficult to detect unless you know the language.

Body:
It depends tremendously on the individual programmer, and how they internalize languages.  I have absolutely no trouble working in a dozen languages, while I have a friend that only knows C++.  He is no worse at programming than me, he just learned a different way.

Personally, I find a related question more interesting: when there is a bug in the code (i.e. programmer X thought he wrote someFunction(x, y) but he really wrote something else), how hard is it for the second developer to identify the bug.  A good programmer X would make it exceedingly obvious what he WANTED the computer to do, and that would be easy to read.  However, if he made a mistake, it can be a big deal.  Things like the following C++ bug:

int x = getCorrectValueForX();
if (x = 2)
   doSomethingWhenXIsTwo();

Can be NOTORIOUSLY difficult to detect unless you know the language.


答:
It not only depends on the programmer as other people have said, but also on the similarities between languages, both in syntax, philosophy and implementation.

Many different languages use a C derivative syntax, and so following the control flow will be easier if you're familiar with that type of syntax.  The same goes for strongly typed and loosely typed languages, languages with higher order function support, level of abstraction and programmatic philosophies.  It not only depends on you being able to read the syntax but also be familiar with the languages concepts and philosophies.

If you learned C for example, I think it would be reasonable to expect you to be able to derive the control flow from C#, Java, or C++ etc. It would be a little harder to decipher VB because of the difference in syntax, or JavaScript because of closures, weak typing and higher-order functions (I know you can do this in C but it's a little wonky). I would not expect you, however, to be able to debug Lisp, F#, R or, god forbid, assembly because these use a completely different programming paradigm.

TL;DR It's not only important to be able to recognize the syntax, most the time you can decipher a declaration or method call but being able to comprehend the reason behind why a program is written a certain way is the crux of understanding and reading code.

Title: Studies on how well can a programmer understand code in unfamiliar languages?

Body:
Are there any serious studies on how well an experienced programmer who knows language X can understand code written by a competent programmer using language Y, for a good range of widely used languages as X and Y?

Of course the real world isn't so simple as a programmers knows just one language.  What we'd like to know is: if we do our project in, say, C#, and someday some old physicists who know only Fortran and Algol look at it, to what extent would it make sense to them?  Mathematical parts of it might read fine to them, if they ignore what to them are some random-ish punctuation marks.  Or, would a Python expert be able to find flaws in my clever Ruby script?

There could be issues from the level of superficial syntax to the level of grand concepts such as objects, template metaprogramming, functional and so on.  I'm not expecting the one programmer to fully understand every syntax detail of code in a "foreign language" or to follow the religion of some grand concept, but wondering to what extent they'd get the main flow of control, find the spot where something is drawn on the screen and what determines its color or size, verify that a robot programmed to drive a car will turn off the engine when it's done, those sorts of things.

A good quality study would include published academic research, an official report from some industry group or major software company, though I'll take systematic unbiased observations by experienced leaders of workshops and classes or other sources.  Not interested in short blogs, single-case examples, or anecdotes.  (Well, maybe a few anecdotes if they make for a good read.)


问:
Dynamic method creation in python
I have a class that will have a number of external methods that will all call the same smaller set of internal methods.  So something like:

obj.method_one(a, c) and
obj.method_two(a, c)

where obj.method_one calls obj._internal_method(a, c, y) and obj.method_two calls obj._internal_method(a, c, z).

They're nearly identical but they have one argument at the end that differs on the internal call (which is a constant).

I could just copy and paste a few times but I was wondering if theres any way to dynamically create these external methods.

答:
There are ways, but unless you have at least half a dozen, I'd suggest:

```<code>class myclass(object):
   def _internal_method(self,a,c,y):
       pass # add code here

   def method_one(self,a,c): self._internal_method(a,c,"method one")
   def method_two(self,a,c): self._internal_method(a,c,"another method")
</code>```

The other option is to actually really create it dynamically. This can be confusing, because if the object is inspected, the methods aren't there. It looks like this:

```<code>class test(object):
    def __getattr__(self,attrname):
        def _internal_method(a,c):
            print "You called %s  with %s and %s" % (attrname,a,c)
        if attrname in ["method_one","method_two"]:
            return _internal_method
        else:
            raise NameError

a=test()
a.method_one("first","second")
</code>```

This makes use of the fact that a getting a property (like a method) that does not exist, the object's __getattr__ is called, and the result is passed back. Note that we are passing back the FUNCTION _internal_method as a.method_one, not calling it at this stage; that is done after the call to getattr has returned. Think of the last line as being:

```<code>tmp=a.method
tmp("first","second")
</code>```

The first of these calls __getattr__ which returns _internal_method (but does not call it), the latter calls _internal_method.

Since _internal_method is declared within __getattr__, it has the same scope as the call that created it, so self and attrname are accessible. Also, _internal_method is TRULY private, not just "private by convention".

I will reiterate that this is confusing for the next person to maintain your code. For example, if you ask for help(a.method_one), you will get the help for _internal_method instead!

The length of this explanation, and your probable confusing is a very good reason not to use this unless you have to.

Title: Dynamic method creation in python

Body:
There are ways, but unless you have at least half a dozen, I'd suggest:

class myclass(object):
   def _internal_method(self,a,c,y):
       pass # add code here

   def method_one(self,a,c): self._internal_method(a,c,"method one")
   def method_two(self,a,c): self._internal_method(a,c,"another method")

The other option is to actually really create it dynamically. This can be confusing, because if the object is inspected, the methods aren't there. It looks like this:

class test(object):
    def __getattr__(self,attrname):
        def _internal_method(a,c):
            print "You called %s  with %s and %s" % (attrname,a,c)
        if attrname in ["method_one","method_two"]:
            return _internal_method
        else:
            raise NameError

a=test()
a.method_one("first","second")

This makes use of the fact that a getting a property (like a method) that does not exist, the object's __getattr__ is called, and the result is passed back. Note that we are passing back the FUNCTION _internal_method as a.method_one, not calling it at this stage; that is done after the call to getattr has returned. Think of the last line as being:

tmp=a.method
tmp("first","second")

The first of these calls __getattr__ which returns _internal_method (but does not call it), the latter calls _internal_method.

Since _internal_method is declared within __getattr__, it has the same scope as the call that created it, so self and attrname are accessible. Also, _internal_method is TRULY private, not just "private by convention".

I will reiterate that this is confusing for the next person to maintain your code. For example, if you ask for help(a.method_one), you will get the help for _internal_method instead!

The length of this explanation, and your probable confusing is a very good reason not to use this unless you have to.


答:
You have implemented a "resumable exception". Many people consider resumable exceptions to be an anti-pattern, partly because it is almost never necessary, partly because it is a pattern that can be abused.

Having implemented a "resumable exception", you then add a signal to control how the exception is handled. This is normal, and is not the anti-pattern. Common status values include "force ignore exception type", "handle exceptions as programmed", and "throw directly to top level".

In my opinion, resumable exceptions are a Good Thing when dealing with un-attended, parallel, synchronous/asynchronous processes with shared resources. You don't want an exception on your process control to kill the whole server process. You don't want an exception to bubble up to the 'top', because there is nothing and nobody at the 'top'. Most exceptions you don't want to treat as exceptions at all.

The best known example of resumable exceptions is BASICs "on error resume next", equivilant to your "return ResultCode.Fail". "Error" is an archaic term for "Exception": "resume next" is the exception-handler control signal. This pattern was commonly used to wrap serial communications, where "file errors" are not "exceptional"

Your "return ResultCode.Fail" handles minimal cases like that, where you can isolate the part of the program where you want to turn off exception handling.

On the other hand, when you find yourself wrapping every single line into a seperate try-catch block, it's time to find a different language, not time to build it yourself.


答:
You don’t spell it out, but “accidental complexity” is defined as complexity that is not inherent to the problem, as compared to “essential” complexity. The techniques requireed for "Taming" will depend on where you start from. The following refers mostly to systems that have already acquired unnecessary complexity.

I have experience in a number of large multi-year projects were the “accidental” component significantly outweighed the “essential” aspect, and also those where it did not.

Actually, the Feynman algorithm applies to some extent, but that does not mean that “think real hard” means only magic that cannot be codified.

I find there are two approaches that need to be taken. Take them both – they are not alternatives. One is to address it piecemeal and the other is to do a major rework.
So certainly, “write down the problem”. This might take the form of an audit of the system – the code modules, their state (smell, level of automated testing, how many staff claim to understand it), the overall architecture (there is one, even if it “has issues”), state of requirements, etc. etc.

It’s the nature of “accidental” complexity that there is no one problem that just needs addressed. So you need to triage. Where does it hurt – in terms of ability to maintain the system and progress its development? Maybe some code is really smelly, but is not top priority and fixing can be made to wait. On the other hand, there may be some code that will rapidly return time spent refactoring.

Define a plan for what a better architecture will be and try to make sure new work conforms to that plan – this is the incremental approach.

Also, articulate the cost of the problems and use that to build a business case to justify a refactor. The key thing here is that a well architected system may be much more robust and testable resulting in a much shorter time (cost and schedule) to implement change – this has real value.

A major rework does come in the “think real hard” category – you need to get it right. This is where having a "Feynman" (well, a small fraction of one would be fine) does pay off hugely. A major rework that does not result in a better architecture can be a disaster. Full system rewrites are notorious for this.

Implicit in any approach is knowing how to distinguish “accidental” from “essential” – which is to say you need to have a great architect (or team of architects) who really understands the system and its purpose.

Having said all that, the key thing for me is automated testing. If you have enough of it, your system is under control. If you don't . . .

Title: How to manage accidental complexity in software projects

Body:
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:

Write down the problem.

Think real hard.

Write down the solution.

Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.

So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?


答:
The concept of null can easily be traced back to C but that's not where the problem lies.

My everyday language of choice is C# and I would keep null with one difference. C# has two kinds of types, values and references. Values can never be null, but there are times I'd like to be able to express that no value is perfectly fine. To do this C# uses Nullable types so int would be the value and int? the nullable value. This is how I think reference types should work as well.

Also see:
Null reference may not be a mistake:

Null references are helpful and sometimes indispensable (consider how much trouble if you may or may not return a string in C++). The mistake really is not in the existence of the null pointers, but in how the type system handles them. Unfortunately most languages (C++, Java, C#) don’t handle them correctly.

Title: Why most "well-known" imperative/OO languages allow unchecked access to types that can represent a 'nothing' value?

Body:
I have been reading about the (un)convenience of having null instead of (for example) Maybe. After reading this article, I am convinced that it would be much better to use Maybe (or something similar). However, I am surprised to see that all the "well-known" imperative or object oriented programming languages still use null (which allows unchecked access to types that can represent a 'nothing' value), and that Maybe is mostly used in functional programming languages.

As an example, look at the following C# code:

```<code>void doSomething(string username)
{
    // Check that username is not null
    // Do something
}
</code>```

Something smells bad here... Why should we be checking if the argument is null? Shouldn't we assume that every variable contains a reference to an object? As you can see, the problem is that by definition almost all variables can contain a null reference. What if we could decide which variables are "nullable" and which not? That would save us a lot of effort while debugging and looking for a "NullReferenceException". Imagine that, by default, no types could contain a null reference. Instead of that, you would state explicitly that a variable can contain a null reference, only if you really need it. That is the idea behind Maybe. If you have a function that in some cases fails (for example division by zero), you could return a Maybe<int>, stating explicitly that the result may be an int, but also nothing! This is one reason to prefer Maybe instead of null. If you are interested in more examples, then I suggest to read this article.

The facts are that, despite the disadvantages of making most types nullable by default, most of the OO programming languages actually do it. That is why I wonder about:

What kind of arguments would you have to implement null in your programming language instead of Maybe? Are there reasons at all or is it just "historical baggage"?

Please ensure you understand the difference between null and Maybe before answering this question.


问:
What's the appropriate procedure for subversion merges?
We have a project with a few release branches and a trunk. Lately we've been adding bugfixes and new features to the release branch, while doing simultaneous infrastructure development on the trunk. This has caused us some problems.

Today I was told to merge changes from branch to trunk, using HEAD as starting/end revisions. It generated a dozen conflicts, which I resolved mostly by accepting the working copy of the trunk. After this was done, I found some scrambled code and some variables that didn't belong in functions.

In addition to giving me a headache, this makes me re-think the way I approached merging. Is it a better practice to merge from a RECENT starting revision, as opposed to the origin of the branch? I actually did it this way first, and it didn't result in any scrambled code or misplaced variables.

答:
It generated a dozen conflicts, which I resolved mostly by accepting the working copy of the trunk.

Well, this seemed to be one cause of the problem. Check merge conflicts very carefully and make sure you resolve them by manual editing, not by (perhaps blindly?) accepting them.

Especially with SVN (but I guess even with DVCS) when doing structural changes on one branch (with cross-cutting nature, like renaming functions or classes, changes file or library structure etc.), it is better not to hold these changes back from other branches for a long period. Better merge these changes to the other branches as soon as possible.

When I understood you correctly, you could not do this here so easily because you did not want to risk the structural changes in the trunk to destabilize the relase branch. In this case it would have probably been better to merge every bug fix or new feature from the release branch immediately to the trunk once the bug fix or new feature was done. This at least lets you handle the merge conflicts one-by-one, and its easier to anticipate how a bug fix from the release branch maps to the structural changed code of the trunk when this is done immediately.