问:
How do you create documentation when there is none?
I have recently inherited a large, legacy system with a complex codebase that has a lack of documentation. I'm the sole internal developer embedded with the core users, taking some responsibility from an external contractor. While modules and functions are documented well enough, there is no documentation around the system itself. What it is, why it exists, how overall modules fit together.

This is a web-application, and an example of this is how it produces a page. This requires executing PHP that makes a call to the database that retrieves some XSLT with custom extensions, that is transformed (this process may happen many times), it may retrieve PHP from the database, however sometimes when retrieving PHP, it will retrieve a PHP stub, which indicates it actually needs to retrieve a PHP file from the file system.

While individual chunks of this process are captured, there is no documentation that takes a systemic or macro view of the world. So I've come in, and have begun writing what I've been able to figure out from emails to the current consultant, what I've been able to figure out from the code, and just raw determination.

Because of the importance of this system, the people I work with have its important that the system can be understood, so they are less reliant on a single person - be it me, the original developer or anyone. To be honest, I am happy with this, I'm secure in my own abilities, and if part of my task is to help mitigate the organisational risk if I was to disappear then thats fair. I also enjoy the task of unravelling a giant legacy system - its a giant puzzle.

However, the challenge is this - I need to produce some solid documentation around how the system works, both for me and whoever follows. While I have started to get a clear understanding, what I would like to know is what are the kinds of things a new developer would need to see to make sence of a legacy system that was new to them?

Similarly, knowing what needs to be written how would you tackle diving in, dissecting and documenting a large legacy codebase?

答:
First, identify the purpose of the system.  This should fit in an 'executive summary', no more than one or two paragraphs.

Second, describe the data sources and consumers.  In short, master data originates from the product catalog, from user registrations, from 'fact files' such as states and zip codes, etc.  Transaction data originates from the on-line users, those who are, for example, buying and paying for products.  Further transaction data is entered by internal staff when making adjustments due to inventory, shipping, or payment problems. And so forth.

Third, describe 'module blocks' - table maintenance, order entry, order fulfillment, shipper selection, etc.  This needs to be flowcharted - how one gets from the initial table population through the transaction entry to the closure of monthly and quarterly accounting cycles.  Each of these should have user roles, some of which are create and edit, some of which are query only, and some of which consume summary reports.

From here one goes into gory details: schema definition, form layouts, print layouts, etc. More than likely the documentation you need to focus on here is what is not 'obvious', such as, for example, pulling PHP fragments from the database.  These unusual practices should be documented early in your efforts.


问:
Specifying options "hard coded", in an interpreted language
In a language like Python or JavaScript (NodeJS), is there anything wrong with defining "the configuration file" as a file which essentially hard-codes the configuration settings? For example:

options.py:

```<code>OUTPUT_DIRECTORY = 'out'
LOGLEVEL = 'debug'
</code>```

options.js:

```<code>outputDirectory = 'out';
logLevel = 'debug';
</code>```

Does this count as "hard-coding" options? When would it be inappropriate to expect a user to configure software this way? Is there any benefit to using a traditional configuration format (eg, ini file) which is parsed at run-time?

答:
I don't see anything wrong with that approach.  It's very convenient in languages like Javascript, PHP, etc., and likely speeds things up by removing the need to parse & load configuration values.

Whether its the way to go is a different question.  In software that is expected to be configured by a programmer - basically software where the 'end user' is a programmer, such as a CMS that gets installed onto a server, it'd work fine.  In software that expects a non-technical end user to make configuration changes... probably not a good idea.  For example, desktop apps written in Python.

ContentLicense: CC BY-SA 3.0


答:
This is exactly how it's done in Django.

One advantage over e.g. INI files is that you leverage all the power and expressiveness of your language in the configuration, allowing settings to be programmatically generated, and tricks like making the configuration dependent on where the application is running.

However, this power comes at a cost. It prevents you from safely offering any method other than the config file for altering settings (for instance via an "Options" dialog), unless:

Your application can decipher the meaning of arbitrary code (which I think is impossible, though I'm not enough of a theorist to be sure about that), or

You have an alternative method of storing configuration options set from within the application (and then you have to decide which of those takes precedence in the event of a conflict).

If you are comfortable offering a config file as the only way of configuring your application, however, that suggests you consider your users competent to edit a file containing a simple list of key/value pairs. It follows that there's no reason they'd be less able to manage that with e.g. Python assignments than with files in INI format, and at the same time you're able to offer expert users much more powerful configuration techniques.

Title: Specifying options "hard coded", in an interpreted language

Body:
In a language like Python or JavaScript (NodeJS), is there anything wrong with defining "the configuration file" as a file which essentially hard-codes the configuration settings? For example:

options.py:

```<code>OUTPUT_DIRECTORY = 'out'
LOGLEVEL = 'debug'
</code>```

options.js:

```<code>outputDirectory = 'out';
logLevel = 'debug';
</code>```

Does this count as "hard-coding" options? When would it be inappropriate to expect a user to configure software this way? Is there any benefit to using a traditional configuration format (eg, ini file) which is parsed at run-time?


问:
How to deal with requirements and use cases in this kind of situation?
Recently I've started to work with object oriented analysis and design and it seemed very interesting to me as a way to get work done better. But I'm still in doubt with one kind of situation. If this is not the correct site to ask about it, sorry for that.

Well, if I have to design a system that allows one user to register customers, sell products and so on, we have someone that will operate the system, in the sense that actor is kind of obvious for some of the use cases - the actor we will consider on the use case "Register New Customer" is simply the responsible for that action in the company of the customer that is purchasing the software.

Now, there are sometimes that this doesn't happen. I'll give an example: I've developed once a system to manage templates for websites in PHP. In that time, I didn't develop it within an object oriented context, but I was thinking on bring this system into object orientation to practice object oriented analysis and design. The point is that the system is very simple: "it takes some configurations written in a xml file, takes a URL and maps it to a file".

The point is that there's no interaction between the users of the websites and the system. The only thing that happens is that the user requests a URL and the system selects one html file that matches this URL in some way, and embed this html into a template specified in the xml. In cases like that, the only functional requirements I can think of are:

The system must allow the user to specify the folders of templates into an xml file;

The system must get the information of directories from the xml file;

The system must load one specific file corresponding to the requested url inside one template file;

The system must allow the replacement of placeholders into the template by values specified on code;

The problem is: for instance, although I thought of them as functional requirements, all of them has to do directly with how the code must be made. Only the third one really fits what I understood of functional requirement. Also the use cases are a little complicated, every action is took by the system itself. The only use case could be "Request Page" with actor being "Site Visitor" and this would imply that the scenario would be just "The user inputs the url into the browser window and the system loads the page."

So, in cases like that, when we are dealing with code will simply be reused into some other code (this is an example, it's just a bunch of code that a developer can use to load pages independent of a template), how should we deal with requirement analysis, use cases and so on?

As I've said, the PHP system I wrote is just an example, I'm really asking in general. Could someone give some hints or reference (some article, tutorial, something like that), that shows how to deal with this?

Thanks very much in advance!

答:
Actors need not be people!

Any system, device, or, external program can be an actor as long as it is recognizably a separate entity which either uses or is used by the system you are developing.

Technical actors usually fall into the "used by" category, as things like "Authentication Server", "Payment Processor" etc.

In you case though would seem to revolve around only two uses cases.
"Requesting System receives rendered output"
and perhaps
"Administrator defines template"


问:
Make PHP code run on .net?
I can write PHP application in linux platform.

However, I getting a request to explore the idea to run PHP application into .NET.

I have zero .NET knowledge.

So wondering, is it possible?

Is it advisable? Implication ? Or maybe I should just install a .NET to playaround first?

In short, zero code changes, except setup the PHP environment in .net.

Also, wondering, will this benefits from .net security?

The reason why I explore this idea is because Singapore government website must run on  .NET (and I intend to save few bucks by not hiring dot net developers). I think the idea of application must run on .NET is absurd (a joke to me), just showing one of the "world-class" standard in Singapore :)

答:
So basically, what you want is to compile PHP to CIL, the bytecode language of .NET. This is in fact possible using Phalanger.

I have no experience using it, but I wouldn't expect existing PHP applications to run on it without problems, especially considering that most PHP apps rely heavily on extensions which are themselves not written in PHP. But that's an obvious problem, maybe the people working on Phalanger have come up with solutions.

Title: Make PHP code run on .net?


问:
Version-control friendly, append-only file format: "binary" or "text"?
I'm designing an append-only ("journaled") file format, and I'd like it to be friendly towards being stored in VCS (git/Mercurial/...).

On one hand, I'd like if after each change, only delta (difference) from previous file state was added into the repository (i.e. some trailing bytes), not the whole contents of the file again. So, for this, I'm considering making the format "pseudo-text", that is no NUL (0x00) byte in the contents (or maybe even some stricter subset of UTF-8), to make it easily diff-able by git/Mercurial.

On the other hand, the "pseudo-text" file format would not be predisposed to merging, it would totally cripple the contents. So to avoid that possibility, I'm inclined to make it "binary", even if only by putting a NUL byte at offset 0 in file. But then, merging even for "text" but structured file formats is not always really possible, even for "typical" cases like sourcecode, so maybe no need to worry here? I'm quite certain there will be totally conflicts all over the place if anyone tries to merge such files, so that could be enough of a warning sign.

Did you have experiences with similar choice in the past? Which choice should I make, and why?

答:
I don't know about mercurial, but git always initially stores the whole content and during the repack operation (part of gc operation; by default ran automatically when there is too many "loose" objects) will find binary deltas. In git these may be against older version than previous, but in your cases the ones from previous will be smallest so git will choose them. Both the initial full copy and the delta are stored deflated.

So the choice between text and binary has negligible effect on the storage size.

Big advantage of text file is that you can debug it with simple text viewer and the diff will show reasonable information. Merging will always cause a conflict, because all changes are always at the end. Whether it is resolveable and makes sense to resolve depends on the actual format and dependencies between entries in it, but you'll always have control over that.

Note however, that you can get diffs work even with binary format, because in git you can specify custom diff program for specific files (via gitattributes).


问:
What is a good strategy for binding view objects to model objects in C++?
Imagine I have a rich data model that is represented by a hierarchy of objects.

I also have a view hierarchy with views that can extract required data from model objects and display the data (and allow the user to manipulate the data).

Actually, there could be multiple view hierarchies that can represent and manipulate the model (e.g. an overview-detail view and a direct manipulation view).

My current approach for this is for the controller layer to store a reference to the underlying model object in the View object. The view object can then get the current data from the model for display, and can send the model object messages to update the data. View objects are effectively observers of the model objects and the model objects broadcast notifications when properties change.

This approach allows all the views to update simultaneously when any view changes the model.

Implemented carefully, this all works. However, it does require a lot of work to ensure that no view or model objects hold any stale references to model objects. The user can delete model objects or sub-hierarchies of the model at any time. Ensuring that all the view objects that hold references to the model objects that have been deleted is time-consuming and difficult.

It feels like the approach I have been taking is not especially clean; while I don't want to have to have explicit code in the controller layer for mediating the communication between the views and the model, it seems like there must be a better (implicit) approach for establishing bindings between the view and the model and between related model objects.

In particular, I am looking for an approach (in C++) that understands two key points:

There is a many to one relationship between view and model objects

If the underlying model object is destroyed, all the dependent view objects must be cleaned up so that no stale references exist

While shared_ptr and weak_ptr can be used to manage the lifetimes of the underlying model objects and allows for weak references from the view to the model, they don't provide for notification of the destruction of the underlying object (they do in the sense that the use of a stale weak_ptr allows for notification), but I need an approach that notifies the dependent objects that their weak reference is going away.

Can anyone suggest a good strategy to manage this?

答:
Well, you can always create your own smart pointer that will notify the referrers. It's not that difficult.

The weak pointers don't have notification because it would require list of weak references that exist and that would in turn require nontrivial synchronization in multi-threaded environment while the implementation without it takes just an extra level of indirection. But especially if you have some constraints from which threads the models can be deleted (GUI frameworks are usually single-threaded anyway), it's possible.


问:
Is Ruby on Rails a suitable framework for a desktop application?
I was wondering if there are obvious advantages and disadvantages to using Ruby on Rails to develop a desktop application.

RoR has great infrastructure for rapid development, proper implementation of specs and automated acceptance tests, an immense number of popular libraries and the promise of being actively developed and maintained in the future.

The downsides I can see are mostly about usability - installation of a Rails app as a local service and launching of a browser when it needs to be active may not come naturally to many users... or be technically easy to implement and support for different platforms.

答:
No, for many reasons:

Sub-par UI. Either you will be limited to traditional web forms based UI, or you will die trying to emulate rich UI interface with lots of JS/HTML5.

No direct access to hardware. If you would like finer control of your print output, access to the scanner or smartcard reader or audio headset, you're doomed.

Difficult deployment. While it's easy to set up your web server, Ruby interpreter and set of gems on a single web server, making a self-installing executable out of it is impossible, or nearly impossible.

Probably a lots of other issues I forgot. And this stands for any web platform, not only for RoR.

ContentLicense: CC BY-SA 2.5


问:
Is there any reason not to include issue numbers in debug logs?
I was going through the answers to this question:

What information must never appear in logs?

And noticed that nobody mentioned this particular attribute. It's something I find useful- whenever any logging is added to the system as a result of tracing a particular issue raised in the bug tracker, or adding a feature, I tend to include the ticket number of the related helpdesk element.

This means that when going through the log, any programmer can cross reference each log message with the associated ticket number. Now I understand that using proper VCS/helpdesk integration means most commits are attached to a ticket number anyway- but over time it makes it easy for us to diagnose problems on inspection whenever a log message comes up.

However it still makes me a bit uneasy leaving this in the logs. The problem is, I can't think of a scenario where this could become a problem. I'm hoping SE can help me out.

By the way- I'm talking about the "verbose" log level. This is never done in a logging level that will appear in production.

答:
I can't think of a scenario where this could become a problem

In my past projects, I've been through 3 or 4 bug tracker migrations that changed (invalidated) all the bug IDs used in prior tracker.

Within bugtrackers themselves, that wasn't a problem since back-references to older issues at prior tracker were easy to discover. But I can easily imagine it making a major headache when posted in a plain text application log, especially when there will be mixes of "old" and "new" tracker IDs.

known issue, details in PRJ-12345

refers to old tracker used before Jun 2012

known issue, details in PRJ-23451

refers to new tracker used after to 2012

It would be quite difficult to figure which of (two) trackers above messages refer to.

I find that it's better to just make sure that log messages are unique, ie guarantee that developer will be able to track the message back to single point in source code (more on that below).

At that single point referred from logs, one can use comments to point reader to exact URL of the respective issue when needed.

```<code>    // known issue, details in http://oldtracker/PRJ-12345
    // known issue, details in http://newtracker/PRJ-23451
</code>```

Side note, a "nice" example of what is bad about not having unique log messages is a Tomcat bug 27988  Unhelpful FileNotFoundException. Its description sounds like a royal road to maintenance nightmare...

org.apache.naming.resources.DirContextURLConnection raises FileNotFoundException
  on lines 311, 344, 382 and 396.  It would be more helpful if these provided a
  message string

...and in my experience, it really was a nightmare.

Guess what happens when your application crashes with braindead file not found and there are (at least) four reasons for that and log doesn't give you a slightest idea what could really go wrong there.

Amount of curses I sent over to Apache developers is hard to count.

Body:
I can't think of a scenario where this could become a problem

In my past projects, I've been through 3 or 4 bug tracker migrations that changed (invalidated) all the bug IDs used in prior tracker.

Within bugtrackers themselves, that wasn't a problem since back-references to older issues at prior tracker were easy to discover. But I can easily imagine it making a major headache when posted in a plain text application log, especially when there will be mixes of "old" and "new" tracker IDs.

known issue, details in PRJ-12345

refers to old tracker used before Jun 2012

known issue, details in PRJ-23451

refers to new tracker used after to 2012

It would be quite difficult to figure which of (two) trackers above messages refer to.

I find that it's better to just make sure that log messages are unique, ie guarantee that developer will be able to track the message back to single point in source code (more on that below).

At that single point referred from logs, one can use comments to point reader to exact URL of the respective issue when needed.

    // known issue, details in http://oldtracker/PRJ-12345
    // known issue, details in http://newtracker/PRJ-23451

Side note, a "nice" example of what is bad about not having unique log messages is a Tomcat bug 27988  Unhelpful FileNotFoundException. Its description sounds like a royal road to maintenance nightmare...

org.apache.naming.resources.DirContextURLConnection raises FileNotFoundException
  on lines 311, 344, 382 and 396.  It would be more helpful if these provided a
  message string

...and in my experience, it really was a nightmare.

Guess what happens when your application crashes with braindead file not found and there are (at least) four reasons for that and log doesn't give you a slightest idea what could really go wrong there.

Amount of curses I sent over to Apache developers is hard to count.


问:
Learning Multiple Languages Simultaneously
When learning new languages, is it better to commit yourself to one language 100% and wait until you've "mastered" it to move on to another, or to work on learning different languages at the same time?

If it matters, I'm currently learning C++ and I'd like to know Java and Python as well.

答:
I found learning multiple languages simultaneously may lead to obviously taking longer to learn one specific language (goes without saying really). However, in my case it has allowed me to decide which languages I prefer and the style of coding I enjoy most.

In my case I started with C# then got into Python and F#. I really liked the functional style of F# which led me to try Scala and Clojure. Now because of learning all these languages I've found Scala to be a good fit for what I do. Plus I am now really confident in OOP and functional styles and can read and write several languages competently. It's a great skill to have.


问:
MVC shared model different required fields on different type
I have a model called Car and depending on what type of Car the user select the view is presented differently. For example the user selects from a grid of different cars and depending if it is a Volvo or a Kia or a Ford the view must allow different fields to be editable. For example with a Volvo the color is editable and is mandatory but with a Kia it is not.

I would like to use the one Car class to bind the view but want the client side validation to pick up the required fields based on what type of car.

I want to go only to one Action method for the Update

what is a good way to approach this problem...? create a base class and inherit from it? will this give me binding problems..?

答:
If you are speaking in terms of asp.net's mvc, then you may want to create a custom attribute and put all the logic inside that class and add the name of the class as an attribute to a property inside your car class.

This link may help you: how to create a custom attribute


答:
It depends on what you mean by "run PHP application into .NET"...

a) You can run PHP sites in the server technology that .Net websites run on, its called IIS.  This is just like running your PHP under Apache so there are no changes to your application.  However, you are not really gaining anything from this as its just running the PHP application the same as Apache and the only reason people would do this is if their hosting solution is already using IIS.

b) If you mean you want to convert your PHP to a .Net application, I would suggest that you learn how ASP.Net works and port it across manually rather than using an automated tool.  PHP and ASP.Net are very different beasts so they work in different ways.  Besides, if you are expected to maintain the application in .Net then you will need to know how it works.

Title: Make PHP code run on .net?

Body:
I can write PHP application in linux platform.

However, I getting a request to explore the idea to run PHP application into .NET.

I have zero .NET knowledge.

So wondering, is it possible?

Is it advisable? Implication ? Or maybe I should just install a .NET to playaround first?

In short, zero code changes, except setup the PHP environment in .net.

Also, wondering, will this benefits from .net security?

The reason why I explore this idea is because Singapore government website must run on  .NET (and I intend to save few bucks by not hiring dot net developers). I think the idea of application must run on .NET is absurd (a joke to me), just showing one of the "world-class" standard in Singapore :)


问:
How to structure a class in python
I have come to python from C++ (I also know a little Java).  I am writing code to exercise a server so I basically use http methods to send a load of requests to the server.  As part of my code I created a class and called it testdata.  This contains basically test input data (to send in requests) and output data to check against.

With my C++ hat on I created a load of getter and setter methods which were one lines.  I even had an __init__ method to set eg self.<some_attribute_name> = "" or some safe default.

I realise now that you can freely add attributes to a python object and there is no need to pre-initialise simple variables in init.

So I have some questions.

For my testdata class, should I even be using a class?

I just add data items like this:

```<code>import testing

td = testing.testdata()
td.sessionid = "123"
</code>```

But what about access eg to td.sessionid before I have previously assigned a value.  I know I can use hasattr but that is an extra burden.  Do I have to make sure I always assign first?  What if I do td.sessionid before it is even assigned anything?  I will get an AttributeError at runtime.  How to handle this?

Due to problem 3. above.  Should I always use __init__ to initialise member data to safe default values? eg "" for strings.

What are recommended approaches in Python?

答:
Generally, you use class attributes to provide defaults:

```<code>class TestData(object):
    sessionid = None
</code>```

You only need to define a __init__ if you need to provide a new instance with attributes that have to be uniquely set for that new instance.

However, don't define a class just to hold state. Use classes when you are going to provide both state and behaviour. Python's standard types and library is otherwise more than rich enough to cover the just-data needs.

Title: How to structure a class in python

Body:
Generally, you use class attributes to provide defaults:

class TestData(object):
    sessionid = None

You only need to define a __init__ if you need to provide a new instance with attributes that have to be uniquely set for that new instance.

However, don't define a class just to hold state. Use classes when you are going to provide both state and behaviour. Python's standard types and library is otherwise more than rich enough to cover the just-data needs.


问:
Separation of construction and initialization
I'm confused by this post by Mark Seeman.

And his comment on IInitializable below:

The problem with an Initialize method is the same as with Property
  Injection (A.K.A. Setter Injection): it creates a temporal coupling
  between the Initialize method and all other members of the class.
  Unless you truly can invoke any other member of the class without
  first invoking the Initialize method, such API design is deceitful and
  will lead to run-time exceptions. It also becomes much harder to
  ensure that the object is always in a consistent state.

The same time he writes:

This issue is similar to the issue of invoking virtual members from
  the constructor. Conceptually, an injected dependency is equivalent to
  a virtual member.

I thinks this statement is true only if admit that constructed != initialized.

What we get now:

Dependencies are injected in constructor but it is not recommended to use them.

Initialize phase brings complexity and should be avoided.

Isn't it contradictory?

Imagine class needs to set its state using the provided dependencies. Loading saved setting for example.

Init is bad, constructor is bad, so where to perform this operation?

And another point:

Are not methods like Connection.Open() just another name for Initialize?

Question:

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

答:
dedicated Initialise method is bad - if you use this you must construct an object and then not use it at all until you've successfully called Init, and always destroy it if the Init call fails. Its a mess of initialisation that is much better handled in the constructor.

If you only return a successfully constructed object that contains everything it needs to start working, then you have a much easier time as a programmer using that class.

Similarly, there shouldn't be a problem if the injected dependancy is resolved during construction.

However that means setting the DI object during construction - 'constructor injection', and I assume he's talking about 'property injection' where the config is passed in as a set of property calls after the object is constructed.  This is the same problem where you had an Init method, but you now have a SetConfigX method. Names are different, obviously, but the principle is the same - you end up with a half-constructed object that you then fill out with the rest of its state before it can be used.


问:
Communication between programmers and system engineers. Tool for planning builds and maintenance jobs
We have Development department and the department of System Engineers that works on a big project (development of J2EE application).

We are using Build management system, Bug tracking system and a Wiki engine in our work.

Sometimes we have a situation when some developer initiate a server restart or an application build that breaks the debug process for other developers (in some cases developers using the same remote Developer server).

At the present moment we are using the chat application for approving the process of restart\rebuild server (application).

Can anyone share the experience of solving collision like I described above?

My vision is to use application which was able to do the following things:

create request for server restart (or application rebuild\redeploy);

subcribing for notification on "new request created" event;

manual approving the request (by several members) and automatic approving of request (in case nobody declined the request during the some period of a time);

subcribing for notification on "the request is approved" event;

the request solving;

subcribing for notification on "the request is solved (done)" event.

It looks like the request has its own lifecycle or workflow.

I think that some Bug tracking system (for example, by Atlassian Jira) can help to create the request and can start the workflow on it. But this solution does not look perfect (even good) for me - its too "heavy and bulky".

答:
Simple. Stop sharing the same development server. Give each developer his own environment in which to develop. This can be on their own box, or a VM each on the server.

Then the existing 'dev' server gets renamed to 'integration server' and it is used as a quality check after development code is merged from a developer's branch to a mainline branch/trunk.

Never bother with a "workflow" solution to a problem like this, you'll introduce a lot of process that will just serve to slow your developers down so they are less productive. Your solution in particular requires co-operation for all the other developers, who may well not bother to look at the requests, or worse will just say "no, my work is too important to be interrupted" which immediately blocks the dev who wants to update the system.


答:
I thinks this statement is true only if admit that constructed != initialized.

You are missing the point it seems. Calling virtual methods from the constructor implicitly means that the object is not yet fully constructed (and initialized). The concepts are the same. You can't call virtual methods until all of the constructors have run (the object is fully initialized). Likewise, you can't call methods that use injected dependencies until they're populated (the object is fully initialized).

Dependecnies are injected in constructor but it is not recommended to use them.

That's not what the article is saying at all. It's saying that the constructor should be limited to accepting dependencies, not looking them up or configuring them, or really anything else. It also says that constructor injection is insufficient for some needs (circular dependencies), and awkward in others (where the constructor definition forces big inheritence hierarchies).

I don't want to put words into the article writer's mouth, but I would recommend using constructor injection until you find a good reason not to. It's the easiest to implement. It's the easiest to debug. It's the easiest to read.

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

Personally, I like factories that spin up an object (or set of objects) with all of their dependencies populated. This limits the places where care needs to be taken to the constructors of your components and the factories themselves. If the dependencies aren't found, you get an error immediately. If you get the object(s) back, you know they're in a good state.

It's not something that can be applied (well) to all problems, but in my experience, can be applied to most problems well and isolates a bit of complexity.

Title: Separation of construction and initialization

Body:
I'm confused by this post by Mark Seeman.

And his comment on IInitializable below:

The problem with an Initialize method is the same as with Property
  Injection (A.K.A. Setter Injection): it creates a temporal coupling
  between the Initialize method and all other members of the class.
  Unless you truly can invoke any other member of the class without
  first invoking the Initialize method, such API design is deceitful and
  will lead to run-time exceptions. It also becomes much harder to
  ensure that the object is always in a consistent state.

The same time he writes:

This issue is similar to the issue of invoking virtual members from
  the constructor. Conceptually, an injected dependency is equivalent to
  a virtual member.

I thinks this statement is true only if admit that constructed != initialized.

What we get now:

Dependencies are injected in constructor but it is not recommended to use them.

Initialize phase brings complexity and should be avoided.

Isn't it contradictory?

Imagine class needs to set its state using the provided dependencies. Loading saved setting for example.

Init is bad, constructor is bad, so where to perform this operation?

And another point:

Are not methods like Connection.Open() just another name for Initialize?

Question:

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?


问:
random unique pair numbers from two range
I want to write a function that return random unique pair numbers every time call it from a range until resetting it.
Something like this:

```<code>function randomUniquePairs($ranges, $reset = false){
   if ($reset === false){
      // some code for reseting
   }
   /*
     some code for creating random unique pair numbers
   */
   return $result;
}

randomUniquePairs(range(1,10), range(1,20));
/*
  this function returns for example:
   array(2,9)
*/
randomUniquePairs(range(1,10), range(1,20));
/*
  this function returns for example:
   array(5,19)
*/

randomUniquePairs(range(1,10), range(1,20));
/*
  this function returns for example:
   array(5,9)
*/
 //this function returns random unique pairs until we pass reset paramer true
</code>```

I tried two approaches:

Approach 1

My first attempt was to make an array of all of possible pairs then select from them randomly, but it is very inefficient, because if ranges are so wide, it consumes a lot of memory.
the code:

```<code>  class a {
    private $asqar;

    function __construct() ($range) {

        // cycle for ranges
        foreach ($range[0] as  $v1) {
            foreach ($range[1] as $v2) {
                $asqar[] =  array(
                    $v1,
                    $v2,
                );
            }
        }
    }

    function randomUniquePairs($reset = false){

        if ($reset === true){
           $this->asgar = array();
        }

        $rndKey = array_rand($this->asgar);
        $result = $this->asqar[$rndkey];
        unset($this->asqar[$rndkey]);
        return $result;
    }
}

$c = new a(range(1,10), range(1,20));
$c->randomUniquePairs();
</code>```

Approach 2

My second attempt was to write a function that produce a pair from these ranges, then store it in a variable, every time that function calls after producing a pair , it checks if this pair produced before call function recursively, it continues until it produce a unique pair.
Here's the code:

```<code>class a{

    private $__uniqueVariables = array();

    public function randomUniquePairs($range, $reset = false) {

        if ($reset === true){
       $this->__uniqueVariables = array();
    }

    // cycle for each value
    foreach ($range as $value) {

        // shuffle
        shuffle($value);

        // selected id
        $selectedId[] = $value[0];
    }

    // check for selected variable
    if (in_array($rndUnqNum, $this->__uniqueVariables)) {

        // return for try again
        return $this->uniqueVariable($range);
    }

    // added to current unique variables
    $this->__uniqueVariables[] = $rndUnqNum;

    // return
    return $rndUnqNum;
}

}
</code>```

but this second approach has an issue that sometimes throw Fatal error: Maximum function nesting level of '100' reached.

I'm looking for a better approach to my algorithm.

答:
This is based on @MichaelT comments and code. I started with this before he posted it but i have been peeking after he posted his code so it's not entirely original work.

I reserve where the numbers in both ranges are the same and i add the offset so that it's more aligned with the original spec.

```<code><?php
class Gen
{
    private $mask;            // bitmask all combinations
    private $firstOffset;     // what first range starts from
    private $secondOffset;    // what second range starts from
    private $firstWidth;      // the width of first range
    private $secondWidth;     // the width of second range
    private $permutations;    // number of permutations
    private $used = 0;        // number of permutations used

    public function __construct(array $range1, array $range2)
    {
        if( ! count($range1) || ! count($range2) )
            throw new Exception("Both ranges must contain at least one element");

        // I support both array(1, 2, 3, 4) and array(1, 4) as a range
        $this->firstOffset = $range1[0];
        $this->secondOffset = $range2[0];
        $firstEnd = array_pop($range1);
        $secondEnd = array_pop($range2);

        if( $firstEnd < $this->firstOffset ||
            $secondEnd < $this->secondOffset )
            throw new Exception('End lower than start in at least one range.' .
                        "Given [{$this->firstOffset}, $firstEnd] " .
                        "and [{this->secondOffset}, $secondEnd]");

        $this->firstWidth = 1 + $firstEnd - $this->firstOffset;
        $this->secondWidth = 1 + $secondEnd - $this->secondOffset;
        $this->permutations = $this->firstWidth*$this->secondWidth; // with no overlap
        $this->reset();
    }

    public function next()
    {
        if( $this->used != $this->permutations ) {
            $random_permutation = rand(0,$this->permutations);
            if( ($found = gmp_scan0($this->mask, $random_permutation)) == $this->permutations )
                $found = gmp_scan0($this->mask, 0);
            $this->used++;
            gmp_setbit($this->mask, $found);
            $first = $found % $this->firstWidth + $this->firstOffset;
            $second = floor($found / $this->firstWidth) + $this->secondOffset;
            return array( $first, $second);
        }
        throw new Exception("No more pairs available");
    }

    public function reset()
    {
        $this->mask = gmp_init(0);
        $this->used = 0;

        // Make simple variables of
        // so that the original ranges
        // are [$s1, $e1] and [$s2, $e2]
        $s1 = $this->firstOffset;
        $s2 = $this->secondOffset;
        $e1 = $s1 + $this->firstWidth - 1;
        $e2 = $s2 + $this->secondWidth - 1;

        if( $s1 <= $e2 && $s2 <= $e1 ) {        // if the rhe ranges overlap
            $is = max($s1, $s2);                // get the start of intersect
            $ie = min($e1, $e2);                // get the end of intersect
            $this->used +=    1 + $ie - $is;    // the count of emelemts in common
            $i1end = $ie - $s1 + 1;             // calculate the end element for first range
            for( $i1 = $is - $s1,               // initialize range1 by reducing by s1
                 $i2 = $is - $s2;               // initialize range2 by reducing by s2
                 $i1 < $i1end;                  // as long as $i1 is lower than the calculates stop
                 $i1++, $i2++) {                // increment both indexes by one for next iteration

                // body of for loop sets bitmask where both
                // would get the same value when offset is added
                gmp_setbit( $this->mask, $i1 + $i2 * $this->firstWidth );
            }
        }
    }
}

//$g = new Gen(range(1,6), range(1,10));
//$g = new Gen(array(3,4), array(5));
$g = new Gen(array(1,6), array(3291,83901));
try {
    while(1) {
        print implode(", ", $g->next()) . "\n";
    }
} catch ( Exception $e ) {
    print "Done!\n";
}
</code>```

Body:
This is based on @MichaelT comments and code. I started with this before he posted it but i have been peeking after he posted his code so it's not entirely original work.

I reserve where the numbers in both ranges are the same and i add the offset so that it's more aligned with the original spec.

<?php
class Gen
{
    private $mask;            // bitmask all combinations
    private $firstOffset;     // what first range starts from
    private $secondOffset;    // what second range starts from
    private $firstWidth;      // the width of first range
    private $secondWidth;     // the width of second range
    private $permutations;    // number of permutations
    private $used = 0;        // number of permutations used

    public function __construct(array $range1, array $range2)
    {
        if( ! count($range1) || ! count($range2) )
            throw new Exception("Both ranges must contain at least one element");

        // I support both array(1, 2, 3, 4) and array(1, 4) as a range
        $this->firstOffset = $range1[0];
        $this->secondOffset = $range2[0];
        $firstEnd = array_pop($range1);
        $secondEnd = array_pop($range2);

        if( $firstEnd < $this->firstOffset ||
            $secondEnd < $this->secondOffset )
            throw new Exception('End lower than start in at least one range.' .
                        "Given [{$this->firstOffset}, $firstEnd] " .
                        "and [{this->secondOffset}, $secondEnd]");

        $this->firstWidth = 1 + $firstEnd - $this->firstOffset;
        $this->secondWidth = 1 + $secondEnd - $this->secondOffset;
        $this->permutations = $this->firstWidth*$this->secondWidth; // with no overlap
        $this->reset();
    }

    public function next()
    {
        if( $this->used != $this->permutations ) {
            $random_permutation = rand(0,$this->permutations);
            if( ($found = gmp_scan0($this->mask, $random_permutation)) == $this->permutations )
                $found = gmp_scan0($this->mask, 0);
            $this->used++;
            gmp_setbit($this->mask, $found);
            $first = $found % $this->firstWidth + $this->firstOffset;
            $second = floor($found / $this->firstWidth) + $this->secondOffset;
            return array( $first, $second);
        }
        throw new Exception("No more pairs available");
    }

    public function reset()
    {
        $this->mask = gmp_init(0);
        $this->used = 0;

        // Make simple variables of
        // so that the original ranges
        // are [$s1, $e1] and [$s2, $e2]
        $s1 = $this->firstOffset;
        $s2 = $this->secondOffset;
        $e1 = $s1 + $this->firstWidth - 1;
        $e2 = $s2 + $this->secondWidth - 1;

        if( $s1 <= $e2 && $s2 <= $e1 ) {        // if the rhe ranges overlap
            $is = max($s1, $s2);                // get the start of intersect
            $ie = min($e1, $e2);                // get the end of intersect
            $this->used +=    1 + $ie - $is;    // the count of emelemts in common
            $i1end = $ie - $s1 + 1;             // calculate the end element for first range
            for( $i1 = $is - $s1,               // initialize range1 by reducing by s1
                 $i2 = $is - $s2;               // initialize range2 by reducing by s2
                 $i1 < $i1end;                  // as long as $i1 is lower than the calculates stop
                 $i1++, $i2++) {                // increment both indexes by one for next iteration

                // body of for loop sets bitmask where both
                // would get the same value when offset is added
                gmp_setbit( $this->mask, $i1 + $i2 * $this->firstWidth );
            }
        }
    }
}

//$g = new Gen(range(1,6), range(1,10));
//$g = new Gen(array(3,4), array(5));
$g = new Gen(array(1,6), array(3291,83901));
try {
    while(1) {
        print implode(", ", $g->next()) . "\n";
    }
} catch ( Exception $e ) {
    print "Done!\n";
}


问:
Should validation rules be tested?
If I have a method taking input and giving output, it's a no-brainer that tests should be written. But what about things like validation rules?

For example, I add a validation rule that a certain property must be at least 5 characters long. Should I then write a UI test to check for an error message when the form field is empty? Assume that the validation library itself works fine, the only thing I do is add a one-liner to specify this rule.

I'm leaning towards no, because I'd only be duplicating the validation rules, and if the rules itself are set up incorrectly, the test will probably also be incorrect. However, I'd very much like to hear people's opinion and experience on this.

答:
Absolutely, including if the underlying library (business layer) works fine.

The reason is that there may be a lot of things going wrong between the business layer and the UI when it comes to validation. In the first case, you can simply throw an exception. In the second case, you have to process the exception, react to it (for example by cancelling the processing or doing or not doing a redirection, displaying a localized message, etc.)

Imagine the validation of an e-mail address. The business layer detected that "someone.somewhere.com" is not a valid e-mail address. The expected behavior is to:

Stop processing,

Stop redirection,

Show a message to the user,

Highlight the e-mail field in red.

What if:

The processing is not stopped?

The invalid e-mail is simply replaced by a null string?

The redirection is still done?

The message is not shown?

The message is wrong?

Another error message for an other field is shown together with the expected message?

The message is correct is some cultures,  but not in others?

The message is too long in some cultures for the area?

The e-mail field is not highlighted?

Another field is highlighted together with the e-mail field?

The e-mail field is empty, i.e. the previous input is discarded?

All previous input of the form is discarded?

Title: Should validation rules be tested?


答:
If you don't write a test to verify that the validation rule is actually functioning how to do know that it worked?

There are customer requirements / user stories that state for the input to be valid it must by 5 characters or longer, have no double letters and no more than 2 numbers. If the user doesn't meet these standard you warn them, reject the answer, or quit the program; depending on the requirements. So of course you should test these conditions.

Title: Should validation rules be tested?

Body:
If I have a method taking input and giving output, it's a no-brainer that tests should be written. But what about things like validation rules?

For example, I add a validation rule that a certain property must be at least 5 characters long. Should I then write a UI test to check for an error message when the form field is empty? Assume that the validation library itself works fine, the only thing I do is add a one-liner to specify this rule.

I'm leaning towards no, because I'd only be duplicating the validation rules, and if the rules itself are set up incorrectly, the test will probably also be incorrect. However, I'd very much like to hear people's opinion and experience on this.


答:
YES you absolutely should test your validation.  Then you should test that your UI responds to it correctly as a separate test.

Also if you use regular expressions then a great tool to help you catch unexpected validation errors (or false positives) is Rex as this is quite good at exercising all the paths.

Title: Should validation rules be tested?


问:
What would be the best approach to make revisions of user content?
I have searched and could not find any information about it. What is the best approach to storing revisions?

I have a website where the user can write a document which can be fairly long (200-300 lines). How do you determine when to make a revision?

Is it not a scalable solution to make a new one whenever the save, because that would be useless to the user when the want to look back, and it would require quite a lot of space.

You could use time and say for every 15 minute they are working on it there would be a revision, but that would sometimes be nothing or the whole document have completely changed.

I could make a diff from the previous revision, and compare by line and look at how many percent of the lines have been changed.

What are other doing revisions?

答:
I suggest that modern devices may actually have the space to store the full versions.   Space may have been an issue with 5MB Drives but with 256GB drives aplenty that may no longer apply.

So I would do the math, e.g. 5000 users * 100 edits a day * 300 characters = 150000000.... less than one fifth of 1 GB.


答:
Dependencies are injected in constructor but it is not recommended to use them.

I think the author is saying the opposite of that with a focus on loose coupling. He's quoted as saying:

"The Constructor Injection design pattern is a extremely useful way to implement loose coupling"

Loose coupling is the core of good software design. It makes classes reusable, extendable and testable.

Initialize phase brings complexity and should be avoided.

Yes it does, but that doesn't mean it can always be avoided. Constructors do not have a return value, and not all languages support throwing of exceptions. Some books argue that a constructor should always be successful, and I agree with this rule.

Here is some source code examples of both styles. Both approaches work, but which one is better?

```<code>try
{
    FileReader f = new FileReader("something.txt");
    String str = f.read();
}
catch(FileNotFound e) {...}
</code>```

or

```<code>FileReader f = new FileReader("something.txt");
if(f.exists())
{
    String str = f.read();
}
</code>```

The first example has the FileReader object dependant upon an external resource. If it can not access it, then it fails during the constructor. This creates dependency beyond the controller of the programmer, and also unit testing.

In the second example there is no dependency. The object is allowed to be created even if the resource doesn't exist. The dependency is now up to the programmer to enforce.

So how does this relate to initializing an object. It's very simple. Who should be responsible? The object or the programmer. That's up to the author of the object. He/she might have good reasons to give up control of constructing the object to the programmer using it.

If initializing an object is a complex task, then you localize that code into a factory class so you have one place to go to make changes.

Are not methods like Connection.Open() just another name for Initialize?

The method Connection.Open() is an initializer only if Connection.Read() fails if Open() was not called.

Here is the problem the author is talking about.

```<code>Connection con = new Connection();
con->Read(); // this will fail, Open() was not called
</code>```

To fix the above code. You have to write this, and this is a bad design.

```<code>Connection con = new Connection();
con->Open("192.168.1.1");  // bug fix, forgot to call Open()
con->Read();
</code>```

I've read many comments in source code by programmers who write "bug fix, forgot to call X(...)". The argument is that the bug was avoidable in the first place. Had the author of the Connection class not used an initializer.

Here is the solution to the problem.

```<code>Connection con = new Connection("192.168.1.1");
con->Read();
</code>```

Now, how you handle a failed connection is answered higher up in my answer. Either the constructor throws an exception, or the programmer has to call isOpen() before read().

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

It might be hard to understand, but the answer is in the Single Responsibility Principle.

For my example with the Connection object. It broke the SRP rule. The Connection object opens and reads from the resource. That's two different responsibilities. We can fix this by fracturing the object into multiple pieces each with their own responsibilities.

Here is an example;

```<code>try
{
    SocketAddress addr = new SocketAddress("192.168.1.1");
    try
    {
        Socket s = new Socket(addr);
        try
        {
            SocketReader r = new SocketReader(s);
            if(r != null)
            {
                String str = r->Read();
            }
        } catch(ReadFailure e) {..}
    } catch(ConnectionFailure e) {..}
} catch(BadAddress e) {..}
</code>```

Each object is responsible only for one thing.

SocketAddress will only construct successfully if the address is valid.

Socket will only construct if it can make a connection to the address.

SocketReader only work if it can read.

As you can see. You have to write a lot more source code, and this is why we often see dependency injection avoided. It's extra work on the part of the programmer.

Body:
Dependencies are injected in constructor but it is not recommended to use them.

I think the author is saying the opposite of that with a focus on loose coupling. He's quoted as saying:

"The Constructor Injection design pattern is a extremely useful way to implement loose coupling"

Loose coupling is the core of good software design. It makes classes reusable, extendable and testable.

Initialize phase brings complexity and should be avoided.

Yes it does, but that doesn't mean it can always be avoided. Constructors do not have a return value, and not all languages support throwing of exceptions. Some books argue that a constructor should always be successful, and I agree with this rule.

Here is some source code examples of both styles. Both approaches work, but which one is better?

try
{
    FileReader f = new FileReader("something.txt");
    String str = f.read();
}
catch(FileNotFound e) {...}

or

FileReader f = new FileReader("something.txt");
if(f.exists())
{
    String str = f.read();
}

The first example has the FileReader object dependant upon an external resource. If it can not access it, then it fails during the constructor. This creates dependency beyond the controller of the programmer, and also unit testing.

In the second example there is no dependency. The object is allowed to be created even if the resource doesn't exist. The dependency is now up to the programmer to enforce.

So how does this relate to initializing an object. It's very simple. Who should be responsible? The object or the programmer. That's up to the author of the object. He/she might have good reasons to give up control of constructing the object to the programmer using it.

If initializing an object is a complex task, then you localize that code into a factory class so you have one place to go to make changes.

Are not methods like Connection.Open() just another name for Initialize?

The method Connection.Open() is an initializer only if Connection.Read() fails if Open() was not called.

Here is the problem the author is talking about.

Connection con = new Connection();
con->Read(); // this will fail, Open() was not called

To fix the above code. You have to write this, and this is a bad design.

Connection con = new Connection();
con->Open("192.168.1.1");  // bug fix, forgot to call Open()
con->Read();

I've read many comments in source code by programmers who write "bug fix, forgot to call X(...)". The argument is that the bug was avoidable in the first place. Had the author of the Connection class not used an initializer.

Here is the solution to the problem.

Connection con = new Connection("192.168.1.1");
con->Read();

Now, how you handle a failed connection is answered higher up in my answer. Either the constructor throws an exception, or the programmer has to call isOpen() before read().

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

It might be hard to understand, but the answer is in the Single Responsibility Principle.

For my example with the Connection object. It broke the SRP rule. The Connection object opens and reads from the resource. That's two different responsibilities. We can fix this by fracturing the object into multiple pieces each with their own responsibilities.

Here is an example;

try
{
    SocketAddress addr = new SocketAddress("192.168.1.1");
    try
    {
        Socket s = new Socket(addr);
        try
        {
            SocketReader r = new SocketReader(s);
            if(r != null)
            {
                String str = r->Read();
            }
        } catch(ReadFailure e) {..}
    } catch(ConnectionFailure e) {..}
} catch(BadAddress e) {..}

Each object is responsible only for one thing.

SocketAddress will only construct successfully if the address is valid.

Socket will only construct if it can make a connection to the address.

SocketReader only work if it can read.

As you can see. You have to write a lot more source code, and this is why we often see dependency injection avoided. It's extra work on the part of the programmer.


问:
How to practice ATDD if design is not yet emerged from TDD?
Despite being very stakeholders friendly, ATDD aimed to provide a "stop" line when a feature has just been done. This avoids wasting time to add non-focused (and sometimes useless) code.

That's why some teams start by establishing a walking skeleton of the application, and directly specifying with an acceptance test the first required feature.

Let's suppose this first acceptance test (not representing a relevant first acceptance test, just being an example):

Given Michael has just been created in the application,
his status should be left to non-activated.

I want to write my acceptances tests focusing on business logic directly (use-cases), not dealing with GUI for business rules.

Thus my question would be...how to write it? since I don't even already know what is a "User", what is a status etc...
Indeed, shouldn't it be the role of TDD to emerge the design and therefore these components?

But if I firstly practice TDD in order to emerge them, the benefit of ATDD (as a stop line) would disappear.

I imagine that it would be more consistent to write some acceptance tests (before entering TDD cycle) when the project has well progressed, since all main components would already be designed.

To sum up, should I always write my acceptances test BEFORE my TDD cycle?

答:
Acceptance tests access the application through a special purpose API.

You presented this use case:

Given Michael has just been created in the application, his status should be left to non-activated.

The API implied from this use case is something like:

```
CreateUser(String name);
enum UserStatus {non-activated};
UserStatus GetUserStatus(String name);
```

So far this has nothing to do with TDD.  It's just a simple API that your acceptance tests can use to access the application.

Now, to make this acceptance test pass, you'll have to implement this API.  That's when you start doing TDD.  The decisions you make while test-driving the solution will help you determine the design of the application.

Note that the design of the application has nothing to do with the design of the API that's used by your acceptance tests.  That API is an adapter layer between those tests and your application.  That layer allows your application to assume any design you so desire.

Regarding TDD and design.  It is true that design emerges from TDD.  But TDD is not the sole process by which you design your application.  You also think through the design in many other ways.  You might draw some UML diagrams.  You might use CRC cards.  You might have a design session with your co-workers.  Indeed, you should likely do ALL of these things.

And you should also allow designs to emerge with TDD.  TDD doesn't replace previous design tools, it adds a new tool to the kit.

Some folks will likely complain that this sounds like BDUF, and doesn't sound very "Agile".  The problem with that is the letter 'B'.  It's entirely true that we don't want to do BIG design up front.  But it's not true at all that we don't want to do some design up front.  We do!  A few hours, or even days of design up front is not bad.  Months and months of it is.

Body:
Acceptance tests access the application through a special purpose API.

You presented this use case:

Given Michael has just been created in the application, his status should be left to non-activated.

The API implied from this use case is something like:

CreateUser(String name);
enum UserStatus {non-activated};
UserStatus GetUserStatus(String name);

So far this has nothing to do with TDD.  It's just a simple API that your acceptance tests can use to access the application.

Now, to make this acceptance test pass, you'll have to implement this API.  That's when you start doing TDD.  The decisions you make while test-driving the solution will help you determine the design of the application.

Note that the design of the application has nothing to do with the design of the API that's used by your acceptance tests.  That API is an adapter layer between those tests and your application.  That layer allows your application to assume any design you so desire.

Regarding TDD and design.  It is true that design emerges from TDD.  But TDD is not the sole process by which you design your application.  You also think through the design in many other ways.  You might draw some UML diagrams.  You might use CRC cards.  You might have a design session with your co-workers.  Indeed, you should likely do ALL of these things.

And you should also allow designs to emerge with TDD.  TDD doesn't replace previous design tools, it adds a new tool to the kit.

Some folks will likely complain that this sounds like BDUF, and doesn't sound very "Agile".  The problem with that is the letter 'B'.  It's entirely true that we don't want to do BIG design up front.  But it's not true at all that we don't want to do some design up front.  We do!  A few hours, or even days of design up front is not bad.  Months and months of it is.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答: I once worked on a project where the contractor had tyepdef'ed every standard datatype from int to string including pointers to obscure names. His approach made understanding the code really difficult. Another style that warns me is premature flexibility; a product I once worked upon had the complete code in DLLs that were loaded in no predictable order. All this to accommodate future evolution. A few DLLs used thread wrappers for portability. It was a a nightmare to debug the program or predict the flow by reading the source code. Definitions were scattered across header files. It was no surprise that the code did not survive beyond second version.</p>


答:
Wikis and similar generally create new revision whenever the user saves and many of them (including stack exchange) merge the revisions if the previous was less than 5 minutes ago.

Any decent backend will only store the changes and having them spread over more revisions usually does not add much actual data. Besides users can only write so fast and text does not take that much space (see Michael's answer). So the scalability is unlikely an issue.

A standard widely used revision control system is probably best backend. All of them do the delta compression.

Title: What would be the best approach to make revisions of user content?

Body:
I have searched and could not find any information about it. What is the best approach to storing revisions?

I have a website where the user can write a document which can be fairly long (200-300 lines). How do you determine when to make a revision?

Is it not a scalable solution to make a new one whenever the save, because that would be useless to the user when the want to look back, and it would require quite a lot of space.

You could use time and say for every 15 minute they are working on it there would be a revision, but that would sometimes be nothing or the whole document have completely changed.

I could make a diff from the previous revision, and compare by line and look at how many percent of the lines have been changed.

What are other doing revisions?


问:
How do you create documentation when there is none?
I have recently inherited a large, legacy system with a complex codebase that has a lack of documentation. I'm the sole internal developer embedded with the core users, taking some responsibility from an external contractor. While modules and functions are documented well enough, there is no documentation around the system itself. What it is, why it exists, how overall modules fit together.

This is a web-application, and an example of this is how it produces a page. This requires executing PHP that makes a call to the database that retrieves some XSLT with custom extensions, that is transformed (this process may happen many times), it may retrieve PHP from the database, however sometimes when retrieving PHP, it will retrieve a PHP stub, which indicates it actually needs to retrieve a PHP file from the file system.

While individual chunks of this process are captured, there is no documentation that takes a systemic or macro view of the world. So I've come in, and have begun writing what I've been able to figure out from emails to the current consultant, what I've been able to figure out from the code, and just raw determination.

Because of the importance of this system, the people I work with have its important that the system can be understood, so they are less reliant on a single person - be it me, the original developer or anyone. To be honest, I am happy with this, I'm secure in my own abilities, and if part of my task is to help mitigate the organisational risk if I was to disappear then thats fair. I also enjoy the task of unravelling a giant legacy system - its a giant puzzle.

However, the challenge is this - I need to produce some solid documentation around how the system works, both for me and whoever follows. While I have started to get a clear understanding, what I would like to know is what are the kinds of things a new developer would need to see to make sence of a legacy system that was new to them?

Similarly, knowing what needs to be written how would you tackle diving in, dissecting and documenting a large legacy codebase?

答:
This is a bottom-up approach where you need a top-down approach, but it should help if you combine it with other answers:

When you look at a part of the system for the first time, you're as big a newb as anybody.  You don't know what you're looking at, but you know what questions you have (WTF if nothing else) and where you would like to see some answers.  When you think you've got an answer, document it as you would have wanted it documented before.  Actually, you might want to start documenting immediately by putting in the questions before you have answers.  And, as you go along, you're apt to mix your answers with questions.  ("This code seems to ..., but is anything actually using it?")

This works for any kind of documenting (including your own code that was not documented because, as you wrote it, the code seemed self-explanatory).  Try to remember what it was like when you understood nothing so the next person (or you, after you've forgotten it all) can glance at your documentation and understand as quickly as possible.

And when you encounter code you documented earlier, and find either that it makes no sense to you now or doesn't answer one or two key questions, fix it up as soon as you can figure it out again or find the answers.


问:
How best do you represent a bi-directional sync in a REST api?
Assuming a system where there's a Web Application with a resource, and a reference to a remote application with another similar resource, how do you represent a bi-directional sync action which synchronizes the 'local' resource with the 'remote' resource?

Example:

I have an API that represents a todo list.

GET/POST/PUT/DELETE /todos/, etc.

That API can reference remote TODO services.

GET/POST/PUT/DELETE /todo_services/, etc.

I can manipulate todos from the remote service through my API as a proxy via

GET/POST/PUT/DELETE /todo_services/abc123/, etc.

I want the ability to do a bi-directional sync between a local set of todos and the remote set of TODOS.

In a rpc sort of way, one could do

POST /todo_services/abc123/sync/

But, in the "verbs are bad" idea, is there a better way to represent this action?

答:
Apache CouchDB is a database which is based on REST, HTTP, and JSON. Developers perform basic CRUD operations over HTTP. It also provides a replication mechanism which is peer-to-peer using only HTTP methods.

To provide this replication, CouchDB needs to have some CouchDB-specific conventions. None of these are opposed to REST. It provides each document (that is a REST resource within a database) with a revision number. This is part of the JSON representation of that document, but is also in the ETag HTTP header. Each database also has a sequence number which allows for tracking changes to the database as a whole.

For conflict resolution, they simply note that a document is conflicted and retain the conflicted versions, leaving it to the developers using the database to provide a conflict resolution algorithm.

You can either use CouchDB as your REST API, which will give you synchronization out of the box, or take a look at how it provides replication to provide a starting point for making your own algorithm.


问:
Flowgraph Aptitude question
I recently looked a Flow-Graph question.

Consider 8 boxes with following values

```<code>Box 1 = 2
Box 2 = 7
Box 3 = 2
Box 4 = 1
Box 5 = 5
Box 6 = 7
Box 7 = 1
Box 8 = 4
</code>```

Now follow the instructions:

Put the number from Box 7 into Box 1

Add the numbers from Box 1 and Box 2 , and put the result in Box 1

Change Instruction 2, Increase the number in Box 2 by 1

If the second box number mentioned in instruction 2 is greater than the number in box 8, stop. If not, go to step 2.

What number is in Box 1 now?

Note: When you are told to put a number into a box, it is understood that whatever number was previously in that box has just been erased.

When I tried to solve:

b[1] = 1

b[1] = 1+7 = 8

b[b[2]] = b[7]+1 =b[7]=2

b[2] > b[8]
7 > 4 : true

result: 8

But the solution is 11! how? I got stuck.Am I misinterpreting something?

答:
This how I interpret it:

Put the number from Box 7 into Box 1 - fairly straightforward.  The number in box 7 gets set as the number in box 1.

Add the numbers from Box 1 and Box 2 , and put the result in Box 1 - also fairly straightforward.  The sum of boxes 1 and 2 gets assigned to box 1.

Change Instruction 2, Increase the number in Box 2 by 1 - I think quotation marks here would make this clearer -- Increase the number in "Box 2" by 1.  This is to say, instruction 2 now reads "Add the numbers from Box 1 and Box 3 , and put the result in Box 1"

If the second box number mentioned in instruction 2 is greater than the number in box 8, stop. If not, go to step 2. - The reason for the strange wording is for the simple fact that the box number mentioned in the 2nd instruction is subject to changes.  We will loop this algorithm for 4 times, where Box 5 will end the loop (since Box 8 holds value 4).

That said, after applying it to this set, you get the following steps:

```<code>2 7 2 1 5 7 1 4
1 7 2 1 5 7 1 4
8 7 2 1 5 7 1 4
10 7 2 1 5 7 1 4
11 7 2 1 5 7 1 4
</code>```

And if box 1 contains the solution, then it is 11.

The algorithm seems to put the sum of the numbers in each box in the first box. It is certainly a strange way to go about doing an algorithm.  It isn't exactly clear what happens to numbers that are "taken out" of another box if they are swapped, if 0 is placed in its stead, or if the number is copied.  I assumed in this example that the number is simply copied, but the answer to this problem depends on this and it isn't mentioned.

Title: Flowgraph Aptitude question

Body:
This how I interpret it:

Put the number from Box 7 into Box 1 - fairly straightforward.  The number in box 7 gets set as the number in box 1.

Add the numbers from Box 1 and Box 2 , and put the result in Box 1 - also fairly straightforward.  The sum of boxes 1 and 2 gets assigned to box 1.

Change Instruction 2, Increase the number in Box 2 by 1 - I think quotation marks here would make this clearer -- Increase the number in "Box 2" by 1.  This is to say, instruction 2 now reads "Add the numbers from Box 1 and Box 3 , and put the result in Box 1"

If the second box number mentioned in instruction 2 is greater than the number in box 8, stop. If not, go to step 2. - The reason for the strange wording is for the simple fact that the box number mentioned in the 2nd instruction is subject to changes.  We will loop this algorithm for 4 times, where Box 5 will end the loop (since Box 8 holds value 4).

That said, after applying it to this set, you get the following steps:

2 7 2 1 5 7 1 4
1 7 2 1 5 7 1 4
8 7 2 1 5 7 1 4
10 7 2 1 5 7 1 4
11 7 2 1 5 7 1 4

And if box 1 contains the solution, then it is 11.

The algorithm seems to put the sum of the numbers in each box in the first box. It is certainly a strange way to go about doing an algorithm.  It isn't exactly clear what happens to numbers that are "taken out" of another box if they are swapped, if 0 is placed in its stead, or if the number is copied.  I assumed in this example that the number is simply copied, but the answer to this problem depends on this and it isn't mentioned.


问:
When being a technical genius is not enough to be a successful developer?
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.

答:
Although it is a quality that may be more applicable to team than to individual developers, I think that there is a lot behind the saying, "Great engineers ship."

It's something that would be hard to demonstrate in an interview for most folks, but if I was interviewing a candidate who, for example, had authored and shipped a substantial open-source application, library or framework and could talk eloquently about the extra something that it takes to actually finish a non-trivial project, I would have to give that person a leg up over his or her competition.

Contrariwise, if a potential candidate pointed me towards his Github account and I saw that it was full of half-completed, buggy, neglected or poorly-documented projects, I would have a good reason to disregard his candidacy.

"Coffee is for closers," as a man said in a movie once.


问:
Sharing dlls in a software deployment
We are moving our software project from the practically auto-creating Visual Studio Installer in Visual Studio 2010 to a WiX installer.  I'd like to use this change to make sure things are right.

The application is a subsidiary to our company's main app that will already be installed in its own folder.  The main app has a lot of dlls, some of which the subsidiary app needs to load to work.

With the previous installer, the required dlls are pulled into the project and included in the subsidiary app's installation folder.  However, this seems to create possible problems:

Multiple versions of the same dll creates confusion, especially if we
produce another app in the future.

If the version of the main app
changes, the updates are missed by the subsidiary app.

I'm not comfortable with adding our app to the same folder, because they are developed and maintained by different groups.

Instead of this, perhaps I could add the path of the main app to the PATH environment variable.  Would this work, and are there concerns with doing this?

Is there some other way to approach this issue?

答:
You are probably better off having the DLL's in their own respective directories.  This way if one group changes one of them in a way that conflicts with an application from another group, it wont impact that application.  I wouldnt worry about having duplicate DLL's - in the scheme of things its probably not much disk space.

Another approach to consider may be to have a shared 'common' directory thats used by all the groups in your company.  A path such as "c:\program files\common files\CompanyName".  (if you look, you'll likely see you have a 'common files' path in your 'program files' directory already, as many larger vendors do this).  Of course, if you do that, you need to commit to testing every DLL change against all apps that might use that DLL.

Title: Sharing dlls in a software deployment


问:
What logic is used to control Lock and Update actions in P2P networks? (similar to Bitcoin)
Bitcoin relies on Proof of Work (hashing) to control the writing to a central repository (the blockchain).  It also relies on a set of rules for these updates, and defines what happens if a conflict is found (longest chain wins)

Using that as an example for my question:

What are some architectural examples of different distributed lock and/or update mechanisms suitable for P2P networks?  (I'm looking for descriptions of software design suitable to this project, not software products)

What key logic or rules are fundamental to that decentralized "database"?

答:
Bitcoin, Bittorrent, TOR, and a lot of Amazon's infrastructure (the decentralized bits) all run using something called Distributed Hash Tables.

Honestly, I don't understand it well enough to explain it well enough. Steve Gibson did a pretty good summary of it a while back if you have 30 minutes to listen.

Link.


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
I could said that industry standard is wrong from the first place

Industry standard of coordinate actually came from desk coordinate, when people draw everything on desk, which is horizontal plane. X is left/right and Y is front/back, so it just make Z be upward and that was born Right-Handed Coordinate System

But
You know
We now using with monitor screen
It is Vertical plane. X is still left/right but Y is the up and down instead

So what Right-Handed Coordinate System would cause?
It make +Z be backward and -Z be forward
What the hell is this?
Up is + and Down is -
Right is + and Left is -
BUT Forward is - and Backward is + ???
It so stupid if we making game that character running in 3D world but we need to minus z to go forward. That's why game programmer most appreciate DirectX

To grab a standard that came from desk and use it on monitor is so wrong in many level from the first place. And now we should admit it that they, OpenGL and Industry, is wrong. They just use what they think it would make them comfortable but they are wrong and Right-Handed Coordinate System is just a junk legacy that should be thrown away as fast as possible


问:
How does a non-technical manager add value to team of self-motivated software developers?
I am seeing a lot of programmers turning away from management and administration roles. They want to build stuff. And as a result, a lot of these positions are filled by non-technical people. I fail to see how they add value. Is scheduling meetings, booking offsites and other administrative work enough to justify their role?</p>

答:
As it applies specifically to software development, there are two sorts of value-adding roles for managers: project management and team leading.

A project manager interfaces with clients and middle management, which is a time saver for the developers.  Often there are clarifications or scope changes that come up in projects, and it is helpful to clients and middle manager to have a single point of contact.  Trying to field questions from every member of a development team leads to unrecorded project decisions and undocumented commitments, the bane of scope management.

On the other side, a team leader is involved with career/skills development, making sure the workload is appropriately distributed among team members, and providing resources and rewards commensurate with the individual contributions and needs.

Neither of these roles requires a heads-down programmer, in fact somewhat the opposite.  A programmer will often jump to a code-writing task as the first response to a question or crisis, and it's helpful to have someone whose job is to ask whether that task really needs to be done.


答:
I fail to see how they currently add value and is scheduling meetings, booking offsites and other administration works enough for their role?

Don't underestimate the amount of interaction your manager does with other departments. They handle budgets, training plans, HR paperwork. They protect the developers from getting sucked into meetings with other departments and provide a unified front for your group.

In short, their job is to protect self-motivated developers from all of the other demotivating things that exist in business.

Title: How does a non-technical manager add value to team of self-motivated software developers?

Body: I am seeing a lot of programmers turning away from management and administration roles. They want to build stuff. And as a result, a lot of these positions are filled by non-technical people. I fail to see how they add value. Is scheduling meetings, booking offsites and other administrative work enough to justify their role?</p>


问:
Can I use aac in an commercial app for free?
I was wondering if I can use the aac codec in my commercial app for free (through lgpl ffmpeg). It says on the wiki:

No licenses or payments are required to be able to stream or distribute content in AAC format.[36] This reason alone makes AAC a much more attractive format to distribute content than MP3, particularly for streaming content (such as Internet radio).
  However, a patent license is required for all manufacturers or developers of AAC codecs.> For this reason free and open source software implementations such as FFmpeg and FAAC may be distributed in source form only, in order to avoid patent infringement. (See below under Products that support AAC, Software.)

But the xSplit program had to cancel the AAC for free members because they have to pay royalties per person. Is this true (that you have to pay per each person that uses aac)? If you do have to pay, which company do you pay to and how does one apply?

答:
Android apps like TuneIn radio use the FFMPEG decoder and I cannot believe that such a popular app is paying a per download licence fee for that.
I note the the BBCs rather nifty iPlayer Radio app uses HLS to deliver the audio directly to the media player. This is how it should be done.</p>


答:
Along with the other benefits mentioned, the non-technical manager may do a better job of making final decisions when there is an impasse amongst the experts. I know this sounds counter-intuitive, but the good non-technical managers understand the strengths and weaknesses of their people.

Example: Two programmers debate over which server to use for an application. In some sort of make-believe democracy, they both get their one vote, so no decision is made. This war could go on forever (and with some technical people it will). Someone has to step in and arbitrate this disagreement and get the project going. A good judge will lean to the opinion of the one with the most expertise in this area.

Just because someone lacks talent, skill or knowledge in an area doesn't mean they can't identify those who do. Recognizing talent is a talent.


答:
The best managers are magicians. They make the rest of the company disappear for their developers. I can't remember the exact quote from Joel but it was something to the effect that it's management's job to make sure there's a fat Internet Pipe, a beast of a machine, and lots of caffeine so all the developers have to worry about is what they do best.

A good manager is the voice of your group to the rest of the company.


问:
How to structure a class in python
I have come to python from C++ (I also know a little Java).  I am writing code to exercise a server so I basically use http methods to send a load of requests to the server.  As part of my code I created a class and called it testdata.  This contains basically test input data (to send in requests) and output data to check against.

With my C++ hat on I created a load of getter and setter methods which were one lines.  I even had an __init__ method to set eg self.<some_attribute_name> = "" or some safe default.

I realise now that you can freely add attributes to a python object and there is no need to pre-initialise simple variables in init.

So I have some questions.

For my testdata class, should I even be using a class?

I just add data items like this:

```<code>import testing

td = testing.testdata()
td.sessionid = "123"
</code>```

But what about access eg to td.sessionid before I have previously assigned a value.  I know I can use hasattr but that is an extra burden.  Do I have to make sure I always assign first?  What if I do td.sessionid before it is even assigned anything?  I will get an AttributeError at runtime.  How to handle this?

Due to problem 3. above.  Should I always use __init__ to initialise member data to safe default values? eg "" for strings.

What are recommended approaches in Python?

答:
In answer to your questions:

1.
In my experience a collection of related config data has always been contained in a dictionary (http://docs.python.org/2/tutorial/datastructures.html#dictionaries). This allows easy manipulation of the data without the worries of instantiation required by classes. Behind the scenes a dictionary is just a hash table.

2.
I don't see the question here but for a dictionary you have a number of options, see the link above but as an example:

```<code>data = {
    "foo": "123"
}
data["bar"] = 42
</code>```

This example shows both creating a dictionary with a known key value pair but also how to add a new one.

3.
Firstly I don't see why you would want to access it without it being assigned, what would be the point? However you could simply use the get function to get around this issue. So following on from the previous example:

```<code>data.get("foo")
</code>```

would give you "123" while:

```<code>data.get("woops")
</code>```

would give you None. Also you can pass in a second argument as the default e.g.

```<code>data.get("woops", "backup")
</code>```

would give you backup

Just for completeness if you were to use the standard [] access notation attempting to access a key that does not exist would throw (called raise in python) a KeyError but you could deal with this using standard try/catch mechanisms (called try/except in python)

4.
This point is kind of moot if you were to go down the dictionary root but put quite simply yes. Realistically this is what the constructor is for to 'construct' the instance of the object. Just because python lets you dynamically allocate new instance variables doesn't mean its the right thing to do. If you were to pass a lint checker over that code it would certainly moan

Title: How to structure a class in python

Body:
In answer to your questions:

1.
In my experience a collection of related config data has always been contained in a dictionary (http://docs.python.org/2/tutorial/datastructures.html#dictionaries). This allows easy manipulation of the data without the worries of instantiation required by classes. Behind the scenes a dictionary is just a hash table.

2.
I don't see the question here but for a dictionary you have a number of options, see the link above but as an example:

data = {
    "foo": "123"
}
data["bar"] = 42

This example shows both creating a dictionary with a known key value pair but also how to add a new one.

3.
Firstly I don't see why you would want to access it without it being assigned, what would be the point? However you could simply use the get function to get around this issue. So following on from the previous example:

data.get("foo")

would give you "123" while:

data.get("woops")

would give you None. Also you can pass in a second argument as the default e.g.

data.get("woops", "backup")

would give you backup

Just for completeness if you were to use the standard [] access notation attempting to access a key that does not exist would throw (called raise in python) a KeyError but you could deal with this using standard try/catch mechanisms (called try/except in python)

4.
This point is kind of moot if you were to go down the dictionary root but put quite simply yes. Realistically this is what the constructor is for to 'construct' the instance of the object. Just because python lets you dynamically allocate new instance variables doesn't mean its the right thing to do. If you were to pass a lint checker over that code it would certainly moan


问:
Is it appropriate to have positive comments in code reviews, or is it exclusively for constructive criticism?
I have been doing a lot of code review lately, and I am unsure of the positive and negative effects and professionalism of putting positive and/or funny comments in code reviews.

We use Github as our code review platform on my team, so the comments are viewable by anyone.  I generally try to use this platform so the entire process from start to finish is visible and historical.

答:
I'd say keep the comments clean and to the point, exactly because of culture.

You cannot avoid that some people will take things the wrong way.

In order to mitigate that, a personal one to one talk will smooth things along, if face to face is not possible, chat or email or skype.


答:
It's important to highlight positives as well as negatives. I know if I were reviewing the refactor of a particular hellish subsystem into something neat and clean, I'd probably buy the programmer a pizza for his efforts.

If you're using reviews as training, it's doubly important - highlighting a good piece of code will be helpful for the junior programmers also reviewing that code. They will have a chance to ask questions about why a particular approach or technique is better than another.

Title: Is it appropriate to have positive comments in code reviews, or is it exclusively for constructive criticism?

Body:
I have been doing a lot of code review lately, and I am unsure of the positive and negative effects and professionalism of putting positive and/or funny comments in code reviews.

We use Github as our code review platform on my team, so the comments are viewable by anyone.  I generally try to use this platform so the entire process from start to finish is visible and historical.


问:
Licensing code "not for reuse"
I have a client-side Javascript framework that is publicly available and BSD licensed.  Each file says it is copyright me, the date, all rights reserved, and the BSD license text.

I am making a project which uses - and adapts and makes code changes to - my BSD licensed framework.  Although obviously browsers will download and execute this code, I don't want to BSD license my derived project.  I don't object to people seeing my code, but I don't want them to cut-n-paste and make derivatives of my project.

What boilerplate text do I put at the top of each file?

I would like to include a link to my BSD-licensed framework too.  How should I phrase that?

答:
"All rights reserved"

Advertisements can come in the flavor of "if you enjoyed this work or want BSD-licensed version, go see LINK".

And remember, you can't strip the BSD license unless you own all of it. If you took BSD code, made changes to it, then you don't have the right to dual license it. You'd need to get the permission from every author who contributed to it.

Title: Licensing code "not for reuse"