问:
Help with database design with a strict and structured subset of clinical data
I'm developing an application to keep some of the data in chronic patients, the data came from a very strict subset of data, vital signs, exams, ecc.

On a first glance I thought to create a Patient model with has_many encounters, and put every info in a different field like (age, height, weight, ecc), but it will result in a big model. So I wondered about embedding to make it easier to maintain and scale if in a couple of months I need to register a new exam, right now I have been thinking in something like this:

Patient

```<code>name: string,
address: string,
phone: integer,
diagnose: string,
etc...
</code>```

Encounters

```<code>patient_id: ObjectID,
age: Integer,
vital_signs: [ { height, weight, bmi, systolic_pressure, diastolic_pressure } ],
exams: [ { creatinine, total cholesterol... } ],
next_encounter: Date
</code>```

I'm going to still need to access to bmi for example if I want to get how many people in the community is obese (hint: an awful lot), so embedding maybe it's not a very good idea. In any case, all the "analysis" will only be done only monthly (or less).

I picked mongodb, because I'm afraid the requisites for this database will be changing from time to time, so flexibility it's important.

Maybe in this case since data is structured, every document will have the same types of fields, a relational database could be better? I don't think it makes sense using a nosql database in a sql way, right?

PS.- I read this article from mongodb blog, and I'm more confused about if this really it's the best approach.

答:
Thoughts -

Definitely better in an RDBMS.

Check for existing standard schemas for medical data. (HL7)

Comments on the suggested table structure:-

Patient

```<code>name: string,
address: string,
phone: integer,
diagnose: string,
DOB Date (Date of Birth)
etc...
</code>```

Encounters

```<code>patient_id: ObjectID,
Date_of_Examination: Date,
</code>```

(With Patient DOB, patient age can be calculated for the Encounter)

```<code>vital_signs: [ { height, weight, bmi, systolic_pressure, diastolic_pressure } ],
</code>```

(possibly better to break this out into two tables: Vital Sign Types, Encounter-Vital Signs in case a new Observation type is added)

```<code>exams: [ { creatinine, total cholesterol... } ],
</code>```

(DEFINITELY break this out into Examination Types, Encounter-Examinations)

```<code>next_encounter: Date
</code>```

Body:
Thoughts -

Definitely better in an RDBMS.

Check for existing standard schemas for medical data. (HL7)

Comments on the suggested table structure:-

Patient

name: string,
address: string,
phone: integer,
diagnose: string,
DOB Date (Date of Birth)
etc...

Encounters

patient_id: ObjectID,
Date_of_Examination: Date,

(With Patient DOB, patient age can be calculated for the Encounter)

vital_signs: [ { height, weight, bmi, systolic_pressure, diastolic_pressure } ],

(possibly better to break this out into two tables: Vital Sign Types, Encounter-Vital Signs in case a new Observation type is added)

exams: [ { creatinine, total cholesterol... } ],

(DEFINITELY break this out into Examination Types, Encounter-Examinations)

next_encounter: Date


问:
Good way to count unique anonymous visitors of articles
I'm building a website with articles, and I'd like to count unique-per-day visits for each article.

The idea to use cookies suggests itself, but I simply can't set a cookie for each and every article visited - ofc the user typically won't go through everything, but better to be safe. If I put all into one cookie, I'll run out of per-cookie space soon, too.

What'd be the best (most practical and lightweight) solution to this?

I have an sqlite database, so maybe some kind of persistent "session" data? That'll put extra load on the server and db, though. Ideas?

答:
This is how you are tracked without cookies via the browser fingerprint.

https://panopticlick.eff.org/index.php?action=log&js=yes

Idea: Each browser has a unique fingerprint if you get enough features

ip address

installed fonts

javascript yes/no

adblock yes/no

accepted headers

is some stuff cached?

java

screen size

If you get 20 bits out of the browser you can distinct approximately 1,000,000 users. If you only have 100 users and some features change then they are still identifiable with a high probability.

Also you can add knowledge about the

interests of people viewing a site

how long they visit

how many links they click (make links traceable)

to add more information.

ContentLicense: CC BY-SA 3.0


问:
Assembly vs. algorithmic languages (like C, Algol, etc)
Usually, computer science papers describe algorithms in Algol-like pseudolanguage, similar to Pascal or even C/C++.

But Donald Knuth uses his own assembly language (MMIX).

Are there any good known algorithms inexpressible in Algol-like language but expressible in unstructured assembly code? Like coroutines, maybe?

答:
I believe that Knuth himself gives an answer in "The Art of Computer Programming".

He says:

High level languages are inadequate for discussing important low-level
  details such as coroutine linkage, random number generation,
  multi-precision arithmetic, and many problems involving the efficient
  usage of memory.

But the decision to use a machine-oriented language is probably due to the fact that:

New algebraic languages go in and out of fashion every five years or
  so, while I am trying to emphasize concepts that are timeless.

(Preface to TAOCP vol. 1)

Moreover, if I did use a high-level language, what language should it be? In
  the 1960s I would probably have chosen Algol W; in the 1970s, I would then
  have had to rewrite my books using Pascal; in the 1980s, I would surely have
  changed everything to C; in the 1990s, I would have had to switch to C++ and
  then probably to Java. In the 2000s, yet another language will no doubt be
  de rigueur. I cannot afford the time to rewrite my books as languages go in
  and out of fashion; languages aren't the point of my books, the point is
  rather what you can do in your favorite language. My books focus on timeless
  truths.

  Expressing basic methods like algorithms for sorting and searching in machine
  language makes it possible to carry out meaningful studies of the effects of
  cache and RAM size and other hardware characteristics (memory speed,
  pipelining, multiple issue, lookaside buffers, the size of cache blocks,
  etc.) when comparing different schemes.

Indeed since '60 there were suitable notation for coroutines in ALGOL-like languages:

...coroutine linkage had already been noted briefly as a "programming tip" in
  an early UNIVAC publication [...] A suitable notation for coroutines in
  ALGOL-like languages was introduced in Dahl and Nygaard's SIMULA I [...] and
  several excellent examples of coroutines (including replicated coroutines)
  appear in the book Structured Programming [by Dahl, Dijkstra, and Hoare].

(TAOCP vol. 1, pp 229-230)

Not to mention high-precision / multiple precision routine in FORTRAN / ALGOL:

Extended precision subroutines for use in FORTRAN programs were described by
  B.I. Blum (1965) [...] and for use in ALGOL by M. Tienari and V.Suokonautio
  [...]
  Arithmetic on integers with unlimited precision, making use of linked memory allocation techniques, was elegantly introduced by G.E. Collins [...]

(TAOCP vol. 2, pg 279)

Same about random number generation: there are examples in C (TAOCP vol. 2, pp 185-188) and exercises in other high level languages (e.g. [EX10] pg 193).


问:
Is it imaginable to teach a machine how to program itself to a defined specification?
A friend of mine without programming knowledge asked me this question and I found it interesting.

I think it is not possible because it would require a really advanced artificial intelligence capable of analyzing the text of a problem, think about a solution and program it. Just thinking about a machine being able to program a simple calculator seems pretty advanced to me.

But maybe I'm wrong and I would like to know what do you think about it and if you are aware of any articles/researches on the subject, or if it already exists or if the possibility exists of selecting a specification, and getting the machine to self-program to this "spec?"

2023 EDIT: GPT-4 ;-)

答:
This is hard to answer because, just like with artificial intelligence, once we have accomplished this it will be because we will have written a program that does it. And critics will say, "well, this machine isn't really programming itself! it just follows exactly the program you gave it!"

Well yes. Whatever we will ever accomplish with computers, we will do by giving it some program and it will execute it. If that's an argument against, then we can't accomplish anything. And yet, at some point, people thought a chess playing computer would be obviously intelligent. Now they can, and we know exactly how, and we don't think that's intelligent. Submarines still can't swim.

So -- consider a few examples.

Since decades, we have had parser generators. You give them a description of a language, it is processed and the result is code for a parser for that language. We know exactly how it's done, but isn't that a computer programming itself?

Second -- editors that tell you you've made a mistake (syntax error, non existing variable, etc). It doesn't program anything itself, but it can tell you that you did something wrong. It's very much on the surface only.

Languages in which you can just click and drag UI controls, and the code that will actually make them work is generated automatically.

JIT compilers. Software that can recognize hotspots in the currently running software and replace some of that by highly optimized compiled code, effectively optimizing itself while it runs. I think this is an example of what can seem to be a machine programming itself, until you know exactly how it happens, and then it turns out to be just doing what the programmer told it to, as always.

General game playing. This is an interesting field of research, in which researchers write programs that can read descriptions of the rules of games, that the programs then play against each other. So instead of a tic-tac-toe program or a chess program, these are programs that read the rules of tic-tac-toe or chess or some new game made up on the spot, and can then play them. The program isn't programming itself, but it does play chess without the rules of chess having been hardcoded. There was a time when this would clearly be considered the computer teaching itself something.

We've taken lots of small steps in the general direction.

But I can't think of any programs that rewrite themselves based on the results of earlier runs, or that can recognize obsolete or inefficient routines in their own code. I think that one day we will have that, and we'll consider it nothing special at all, as it'll be just some feature of the latest compiler...

ContentLicense: CC BY-SA 4.0


问:
In an MVC, should models use libraries, or should libraries use models?
When I build a RESTful API, I use an MVC pattern. And in order to make controllers skinny and code reusable outside of the API (e.g. in Cron tasks), I put much of my code into services (commonly known as libraries).

My routers delegate to controllers which then delegate to services, which use models.

I am wondering: Does it make sense for services to use models? So

```<code>router > controller > services > models
</code>```

Or, should models use services? So

```<code>router > controller > models > services
</code>```

答:
In the MVC pattern, eberything that is not part of the Controller or View is considered to be part of the Model side of the triad. This means that from an MVC perspective, your question is moot, because both your services and models are part of the MVC Model side of the triad.

As most MVC frameworks provide data access services as part of their Model component, which you may want to use as well when accessing your code from outside the API, it makes most sense to place your services layer between the controller and models.


答:
Not currently and not in the foreseeable future because you need all the awesome complexity of the human brain to create a program. And even then those brains need to be highly trained in order to do so properly, and even then not all of them are capable of doing the task though one could argue that with sufficient time you could train anybody to program.

I took it from the way you phrased your question that you are not talking about simple emulated tasks.

You asked for articles and this Science Blogs article on Developing Intelligence answers that question in many ways.

Title: Is it imaginable to teach a machine how to program itself to a defined specification?

Body:
A friend of mine without programming knowledge asked me this question and I found it interesting.

I think it is not possible because it would require a really advanced artificial intelligence capable of analyzing the text of a problem, think about a solution and program it. Just thinking about a machine being able to program a simple calculator seems pretty advanced to me.

But maybe I'm wrong and I would like to know what do you think about it and if you are aware of any articles/researches on the subject, or if it already exists or if the possibility exists of selecting a specification, and getting the machine to self-program to this "spec?"

2023 EDIT: GPT-4 ;-)


问:
Event sourcing - performance penalty?
I am trying to convince people in my company that we should switch to event sourcing. Our software is a product that consist of many modules - like a module for wiki, blogs, documents, etc. I would like to use event sourcing also to allow easy collaboration on artifacts (like blogs), to have a history of changes, to minimize concurrent modification issues and so on.

There is also a feature of staging - where modules can be staged offline, so people can work on them; and then applied to online once when changes are finished.

The one of the reasons why no one wants to go this direction is the amount of events needed to be persisted. The events needed to be very granular, since of variety of actions users can do. But, there is no other operation on events then: 1) adding them 2) reading them from one point in time to the other. More over, we can have the concept of 'applied' events; some modules do not need to keep track of the full history, just the most recent ones.

So I wonder if there is any experience in how persisting events may influence the performance of the system?

答:
I may be able to provide a bit of (biased) insight (that you shouldn't take at face value) since I recently had the pleasure to do a proof of concept in implementing eventsourcing for one of my companies products. Before this POC we had a "classic" system with a RDBMS in the bottom that did not save any events, the proof of concept was to replace the entire service layer with a CQRS architecture that used GetEventStore for eventsourcing and Raven as the read model.

In the end, there was no big performance change that our users could spot (sometimes faster, sometimes slower) compared to the classic RDBMS implementation. Why? Mainly because on the read side you are saving everything denormalized "ready for use" which makes querying really really fast and simple. Writing was also pretty fast even though we did the naive "read all events from a stream and apply them"-approach. But since we had done our due diligence in domain design we just had to read a single stream - and often enough a stream for a single aggregate did not have that many events so compared to the joining and grouping and stuff we did in the classic RDBMS way this turned out to not be much of a difference. And if we would have gotten enough events in a stream we could have used snapshots in order to not have to re-read every single event from a stream. But generally it's not necessary to perform such optimizations in advance - you'd be surprised how fast reading and applying events can be.

In the end though, this was slower (WAIT! Didn't I just say that it was about as fast earlier? Damn, you spotted my lies! :D) since we also went to a CQRS architecture where we had several servers communicating via messaging and thus also BASE consistency. Semantically compared to the classic RDBMS version this was slower since in order to have full consistency you'd have to wait until the event has gone through all the way to the read layer. However the users could rarely notice this added slowdown - and even when they did it was totally acceptable. And in many cases we realized that the users had no use for a full consistency model and we didn't need to wait for the event to go through the entire system. The users could just keep working anyway. This was kind of a "hard" realization that took a lot of time for our business people to accept, but it's the truth - consistency in a distributed system is a myth anyway, as soon as you show someone data on the screen it's most likely already old and out-of-date anyway.

In my experience, the main performance hit you take from eventsourcing is not from saving your data as a stream of events, that's pretty fast and if you get gigantic streams - start taking snapshots. The main performance hit you take is the one you choose yourself when you need to wait for events passing through the entire system.

Generally, I wouldn't say that "performance" is a good reason to not use eventsourcing.
Sadly, in the end, we did not choose to go in the eventsourcing direction at my company. Though this was not because of performance or any such reason - that was purely because we had too many people who got way too scared of throwing out the RDBMS. :(

Title: Event sourcing - performance penalty?


问:
Where should an object in CQRS+ES be fully initialized: in the constructor, or when applying the first event?
There appears to be widespread agreement in the OOP community that the class constructor should not leave an object partly or even fully uninitialized.

What do I mean by "initialization"? Roughly speaking, the atomic process that brings a newly created object into a state where all of its class invariants hold. It should be the first thing that happens to an object, (it should only run once per object,) and nothing should be permitted to get hold of an un-initialized object. (Thus the frequent advice to perform object initialization right in the class constructor. For the same reason, Initialize methods are often frowned upon, as these break apart the atomicity and make it possible to get hold of, and use, an object that is not yet in a well-defined state.)

Problem: When CQRS is combined with event sourcing (CQRS+ES), where all state changes of an object are caught in an ordered series of events (event stream), I am left wondering when an object actually reaches a fully-initialized state: At the end of the class constructor, or after the very first event has been applied to the object?

Note: I'm refraining from using the term "aggregate root". If you prefer, substitute it whenever you read "object".

Example for discussion: Assume that each object is uniquely identified by some opaque Id value (think GUID). An event stream representing that object's state changes can be identified in the event store by the same Id value: (Let's not worry about correct event order.)

interface IEventStore
{
    IEnumerable<IEvent> GetEventsOfObject(Id objectId);
}
```

<p>Assume further that there are two object types <code>Customer</code> and <code>ShoppingCart</code>. Let's focus on <code>ShoppingCart</code>: When created, shopping carts are empty and must be associated with exactly one customer. That last bit is a class invariant: A <code>ShoppingCart</code> object that is not associated to a <code>Customer</code> is in an invalid state.</p>

<p>In traditional OOP, one might model this in the constructor:</p>

<pre class="lang-cs prettyprint-override"><code>partial class ShoppingCart
{
    public Id Id { get; private set; }
    public Customer Customer { get; private set; }

    public ShoppingCart(Id id, Customer customer)
    {
        this.Id = id;
        this.Customer = customer;
    }
}
</code>```

I am however at a loss how to model this in CQRS+ES without ending up with deferred initialization. Since this simple bit of initialization is effectively a state change, wouldn't it have to be modelled as an event?:

partial class CreatedEmptyShoppingCart
{
    public ShoppingCartId { get; private set; }
    public CustomerId { get; private set; }
}
// Note: `ShoppingCartId` is not actually required, since that Id must be
// known in advance in order to fetch the event stream from the event store.
```

This would obviously have to be the very first event in any ShoppingCart object's event stream, and that object would only be initialized once the event were applied to it.

So if initialization becomes part of the event stream "playback" (which is a very generic process that would likely work the same, whether for a Customer object or a ShoppingCart object or any other object type for that matter)…

Should the constructor be parameter-less and do nothing, leaving all work to some void Apply(CreatedEmptyShoppingCart) method (which is much the same as the frowned-upon Initialize())?

Or should the constructor receive an event stream and play it back (which makes initialization atomic again, but means that each class' constructor contains the same generic "play back & apply" logic, i.e. unwanted code duplication)?

Or should there be both a traditional OOP constructor (as shown above) that properly initializes the object, and then all events but the first are void Apply(…)-ied to it?

I do not expect of answer to provide a fully working demo implementation; I'd already be very happy if someone could explain where my reasoning is flawed, or whether object initialization really is a "pain point" in most CQRS+ES implementations.

答:
When doing CQRS+ES I prefer not having public constructors at all. Creating my aggregate roots should be done via a factory (for simple enough constructions such as this) or a builder (for more complicated aggregate roots).

How to then actually initialize the object is an implementation detail. The OOP "Don't use initialize"-advice is imho about public interfaces. You should not expect that anyone that uses your code knows that they must call SecretInitializeMethod42(bool,int,string) - that's bad public API design. However if your class does not provide any public constructor but instead there is a ShoppingCartFactory with the method CreateNewShoppingCart(string) then the implementation of that factory may very well hide any kind of initialization/constructor magic which your user then don't need to know about (thus providing a nice public API, but allowing you to do more advanced object creation behind the scenes).

Factories get a bad rep from people thinking there's too many of them, but used correctly they can hide away a lot of complexity behind a nice easy-to-understand public API. Don't be afraid to use them, they're a powerful tool which can help you make complex object construction much easier - as long as you can live with some more lines of code.

It's not a race to see who can solve the problem with the least lines of code - it is however an ongoing competition as to who can make the nicest public API's! ;)

Edit: Adding some examples on how applying these patterns could look

If you just have an "easy" aggregate constructor that has a couple of required parameters you can go with just a very basic factory implementation, something along these lines

```<code>public class FooAggregate {
     internal FooAggregate() { }

     public int A { get; private set; }
     public int B { get; private set; }

     internal Handle(FooCreatedEvent evt) {
         this.A = a;
         this.B = b;
     }
}

public class FooFactory {
    public FooAggregate Create(int a, int b) {
        var evt = new FooCreatedEvent(a, b);
        var result = new FooAggregate();
        result.Handle(evt);
        DomainEvents.Register(result, evt);
        return result;
    }
}
</code>```

Of course, exactly how you divide creating the FooCreatedEvent is in this case up to you. One could also make a case for having a FooAggregate(FooCreatedEvent) constructor, or having a FooAggregate(int, int) constructor that creates the event. Exactly how you choose to divide the responsibility here is up to what you think is the cleanest and how you have implemented your domain event registration. I often choose to have the factory create the event - but it's up to you since event creation is now an internal implementation detail that you can change and refactor at any time without changing your external interface. An important detail here is that the aggregate does not have a public constructor and that all the setters are private. You don't want anyone to use them externally.

This pattern works fine when you're just more or less replacing constructors, but if you have more advanced object construction this may become way too complex to use. In this case I usually forego the factory pattern and turn to a builder pattern instead - often with a more fluent syntax.

This example is a bit forced since the class it builds isn't very complex, but you can hopefully grasp the idea and see how it would ease more complex construction tasks

```<code>public class FooBuilder {
    private int a;
    private int b;

    public FooBuilder WithA(int a) {
         this.a = a;
         return this;
    }

    public FooBuilder WithB(int b) {
         this.b = b;
         return this;
    }

    public FooAggregate Build() {
         if(!someChecksThatWeHaveAllState()) {
              throw new OmgException();
         }

         // Some hairy logic on how to create a FooAggregate and the creation events from our state
         var foo = new FooAggregate(....);
         foo.PlentyOfHairyInitialization(...);
         DomainEvents.Register(....);

         return foo;
    }
}
</code>```

And then you use it like

```<code>var foo = new FooBuilder().WithA(1).Build();
</code>```

And of course, generally when I turn to the builder pattern it's not just two ints, it may contain lists of some value objects or dictionaries of some kind of maybe some other more hairy things. It is however also quite useful if you have many combinations of optional parameters.

The important takeaways for going this way is:

Your main objective is being able to abstract object construction so that the external user doesn't have to know about your event system.

It's not that important where or who registers the creation event, the important part is that it gets registered and that you can guarantee that - apart from that, it's an internal implementation detail. Do what fits your code the best, don't follow my example as some sort of "this is the right way"-thing.

If you want to, by going this way you could have your factories/repositories return interfaces instead of concrete classes - making them easier to mock for unit tests!

This is a lot of extra code sometimes, which makes many people shy away from it. But it's often quite easy code compared to the alternatives and it does provide value when you do sooner or later need to change stuff. There's a reason that Eric Evans talks about factories/repositories in his DDD-book as important parts of DDD - they are necessary abstractions to not leak certain implementation details to the user. And leaky abstractions are bad.

Hope that helps a bit more, just ask for clarifications in comments otherwise :)

Body:
When doing CQRS+ES I prefer not having public constructors at all. Creating my aggregate roots should be done via a factory (for simple enough constructions such as this) or a builder (for more complicated aggregate roots).

How to then actually initialize the object is an implementation detail. The OOP "Don't use initialize"-advice is imho about public interfaces. You should not expect that anyone that uses your code knows that they must call SecretInitializeMethod42(bool,int,string) - that's bad public API design. However if your class does not provide any public constructor but instead there is a ShoppingCartFactory with the method CreateNewShoppingCart(string) then the implementation of that factory may very well hide any kind of initialization/constructor magic which your user then don't need to know about (thus providing a nice public API, but allowing you to do more advanced object creation behind the scenes).

Factories get a bad rep from people thinking there's too many of them, but used correctly they can hide away a lot of complexity behind a nice easy-to-understand public API. Don't be afraid to use them, they're a powerful tool which can help you make complex object construction much easier - as long as you can live with some more lines of code.

It's not a race to see who can solve the problem with the least lines of code - it is however an ongoing competition as to who can make the nicest public API's! ;)

Edit: Adding some examples on how applying these patterns could look

If you just have an "easy" aggregate constructor that has a couple of required parameters you can go with just a very basic factory implementation, something along these lines

public class FooAggregate {
     internal FooAggregate() { }

     public int A { get; private set; }
     public int B { get; private set; }

     internal Handle(FooCreatedEvent evt) {
         this.A = a;
         this.B = b;
     }
}

public class FooFactory {
    public FooAggregate Create(int a, int b) {
        var evt = new FooCreatedEvent(a, b);
        var result = new FooAggregate();
        result.Handle(evt);
        DomainEvents.Register(result, evt);
        return result;
    }
}

Of course, exactly how you divide creating the FooCreatedEvent is in this case up to you. One could also make a case for having a FooAggregate(FooCreatedEvent) constructor, or having a FooAggregate(int, int) constructor that creates the event. Exactly how you choose to divide the responsibility here is up to what you think is the cleanest and how you have implemented your domain event registration. I often choose to have the factory create the event - but it's up to you since event creation is now an internal implementation detail that you can change and refactor at any time without changing your external interface. An important detail here is that the aggregate does not have a public constructor and that all the setters are private. You don't want anyone to use them externally.

This pattern works fine when you're just more or less replacing constructors, but if you have more advanced object construction this may become way too complex to use. In this case I usually forego the factory pattern and turn to a builder pattern instead - often with a more fluent syntax.

This example is a bit forced since the class it builds isn't very complex, but you can hopefully grasp the idea and see how it would ease more complex construction tasks

public class FooBuilder {
    private int a;
    private int b;

    public FooBuilder WithA(int a) {
         this.a = a;
         return this;
    }

    public FooBuilder WithB(int b) {
         this.b = b;
         return this;
    }

    public FooAggregate Build() {
         if(!someChecksThatWeHaveAllState()) {
              throw new OmgException();
         }

         // Some hairy logic on how to create a FooAggregate and the creation events from our state
         var foo = new FooAggregate(....);
         foo.PlentyOfHairyInitialization(...);
         DomainEvents.Register(....);

         return foo;
    }
}

And then you use it like

var foo = new FooBuilder().WithA(1).Build();

And of course, generally when I turn to the builder pattern it's not just two ints, it may contain lists of some value objects or dictionaries of some kind of maybe some other more hairy things. It is however also quite useful if you have many combinations of optional parameters.

The important takeaways for going this way is:

Your main objective is being able to abstract object construction so that the external user doesn't have to know about your event system.

It's not that important where or who registers the creation event, the important part is that it gets registered and that you can guarantee that - apart from that, it's an internal implementation detail. Do what fits your code the best, don't follow my example as some sort of "this is the right way"-thing.

If you want to, by going this way you could have your factories/repositories return interfaces instead of concrete classes - making them easier to mock for unit tests!

This is a lot of extra code sometimes, which makes many people shy away from it. But it's often quite easy code compared to the alternatives and it does provide value when you do sooner or later need to change stuff. There's a reason that Eric Evans talks about factories/repositories in his DDD-book as important parts of DDD - they are necessary abstractions to not leak certain implementation details to the user. And leaky abstractions are bad.

Hope that helps a bit more, just ask for clarifications in comments otherwise :)


问:
Creating a custom GUI. App/DE/WM?
I am starting with this project of mine of writing a custom UI for linux. What would happen is:

The computer would boot into this UI which would not be the typical taskbar/icons/startbutton kind of thing. Think more like a dedicated UI instead of a general purpose one.

It would provide access to wifi, ethernet, bluetooth etc. Basically have access to most system resources.

Up until this point, I don't planning on having a file manager for the user. The app would take care of this. Sort of the way apps on mobile phones work.

My first instinct was to work (fork an existing one) on a custom DE like Gnome/KDE. So I read up a lot about window managers and desktop environments and while window managers seem to be the best option for what I am trying to do, another idea occurred to me which would be much less complicated. I could simply (I know!) write an app which the native OS boots into, without any splash screen etc. So, take a distro like Arch Linux, strip it down to the basics and then build an app on top of that.

I would like to get some advice on what the best way to go forward with this would be. Do you guys concur that an app is better to go with? Please excuse me if the question seems naive. Any suggestions/ideas welcome.

答:
I would like to get some advice on what the best way to go forward with this would be. Do you guys concur that an app is better to go with?

Step 1: decide what you want: you describe something that is a boot loader (very low level); then, you describe something that is a WM or a DE.

Normally:

you should try to optimize for a user-level application;

if that doesn't fit, you should consider a DE or WM;

if that doesn't fit either, you should consider something custom (i.e. something that is between a DE, WM or user application - eventually not running X server at all)

if that doesn't fit either, you should consider something at operating system level (i.e. similar to a boot loader).

These steps are sorted in order of ease of implementation (determined by availability of libraries, documentation at each level, amount of specific domain knowledge and so on).

Step 2: decide what is feasible from what you want: a desktop application can take (depending on requirements and available resources) anywhere between half a day of development and a decade; a DE replacement on the other hand, would probably take longer (depending on complexity).

From here on, it gets complicated (you need analysis, design and the entire project lifecycle party).

Title: Creating a custom GUI. App/DE/WM?


问:
How to implement simple secure client side encryption
I know these sorts of questions come up, but I couldn't find a simple answer, most of the answers are "don't do that"

For play, I built myself a webapp, it uses sjcl to encrypt and decrypt notes on the client, whilst sending the encrypted form back to the server.

I am storing the key in local storage.

From my research, I am at risk from:

Cross site scripting attacks (my application uses AJAX to send and receive the data from the server, I'm not sure if that is an attack vector).

Local machine being hacked. At the moment the app can only be used on machines I have full control over, the moment I log in from a machine I do not control and type my key, that machine essentially has my key.

Any type of flaw in local storage that lets a site from a different domain read the storage of other websites stored in the browser.

I am sure I have missed countless other attack vectors.

At first glance, I feel like it's impossible to design a client side encrypted note taking application that never sends the key to the server. With programming, there is almost always a way.

Is there a way I can make the app actually usable?

答:
In basic terms you assume, that if you encrypt data on client side (creating a token) and send token to server over HTTP, it will be secure - this is not true.

Hacker can get the token via network monitoring software (he does not need password) - that's it. Estimated time to bypass this is like less then 15 min.


问:
Why was the first compiler written before the first interpreter?
The first compiler was written by Grace Hopper in 1952 while the Lisp interpreter was written in 1958 by John McCarthy's student Steve Russell. Writing a compiler seems like a much harder problem than an interpreter. If that is so, why was the first compiler written six-years before the first interpreter?</p>

答:
I disagree with the premise of the question.

Adm. Hopper's first compiler (the A-0) was more like a linker or a macro language. She stored subroutines on a tape (each one assigned a number) and her programs would be written as a list of subroutines and arguments. The compiler would copy the requested subroutines from tape and re-order them into a complete program.

She used the word "compile" in the same sense that one compiles an anthology of poems: collecting various items together into one volume.

That first compiler did not have a lexer or parser, as far as I can tell, which makes it a distant ancestor of a modern compiler. She later created another compiler (the B-0, a.k.a. FLOW-MATIC) with the goal of a more English-like syntax, but it wasn't completed until 1958 or 1959 -- around the same time as the Lisp interpreter.

Therefore, I think the question itself is a bit mistaken. It seems that compilers and interpreters co-evolved almost exactly at the same time, no doubt due to the sharing of ideas that would have had many scientists thinking along the same lines in those days.

A better answer with citations here: https://stackoverflow.com/a/7719098/122763.


答:
Basically, if the key is safe, the data is safe too (provided that its a good encryption algorithm and the key long enough, which I take as granted).

If I understood right, you only send encrypted data over the wire, not the key itself. If it's not the case, please discard this whole answer.

Assuming the key is never sent over the wire, the only way to compromise the data is to discover the key. This could happen if:

How the key is generated is predictible

Somebody having access to the file

A virus on the PC

DNS spoofing attacks (claiming to be your host/domain) -> Use TLS and certificates (see http://dev.w3.org/html5/webstorage/#privacy)

Exploiting a bug in some exotic browser/version (dunno if this already happenned, and if there are some vulnerability alerts or such)

...is there anything else?

...perfect security is hard to achieve. But in your case, it seems an attacker must go to great length in order to hack it, or the user have a compromised machine from the start. Usually, the bottleneck is the user itself. ;)

Title: How to implement simple secure client side encryption

Body:
I know these sorts of questions come up, but I couldn't find a simple answer, most of the answers are "don't do that"

For play, I built myself a webapp, it uses sjcl to encrypt and decrypt notes on the client, whilst sending the encrypted form back to the server.

I am storing the key in local storage.

From my research, I am at risk from:

Cross site scripting attacks (my application uses AJAX to send and receive the data from the server, I'm not sure if that is an attack vector).

Local machine being hacked. At the moment the app can only be used on machines I have full control over, the moment I log in from a machine I do not control and type my key, that machine essentially has my key.

Any type of flaw in local storage that lets a site from a different domain read the storage of other websites stored in the browser.

I am sure I have missed countless other attack vectors.

At first glance, I feel like it's impossible to design a client side encrypted note taking application that never sends the key to the server. With programming, there is almost always a way.

Is there a way I can make the app actually usable?


答:
First, from what I understand, you don't show to user any data from other users, so you don't really have to worry about XSS. If you would show it, then you would have to make some countermeasures, such as character escaping (that actually should be used anyway). Hacked machine and browser security flaws are things you rather can't predict.

Second, the encryption thing you created doesn't really work. Sorry. Unless you are a genious with years of experience in security, but then you wouldn't need to ask this question. Among things that should be considered when designing encryption are:

Man in the Middle - can someone catch user's data by decrypting data from server on own machine and reencrypt them when sending to client? Attacker may simply ask real server for token, and when pretending to client that he is the server, he has the luxury to generate own set of keys/tokens, which will look as legit as original.

Network monitoring - are you sure you are not susceptible for instance to replay attack? Assume you order some items in some shop. If attacker records it and replays to the server, the same, encrypted data, will server detect it, or commit transaction again?

Key generation - are the keys you use completely random, or just predictably random? If attacker can generate the same set of keys your server stores, he doesn't even need to directly attack you, he can just sit back and other implications are pretty obvious. And believe me, standard random with time seed is very predictable.

Lots and lots more...

There are libraries like SSL that make this for you, made by people with years of experience and, as you probably realize, even they happen to mistakes, but nobody seems to be particularly eager to implement any alternative for some reason.

In case of security, the best option is to use checked and popular solutions, as they are probably also the most safe ones. As there is quite a few open-source and  free libraries available, that should not be a problem. Ready encryption supported by browser will probably take care of more problems than you will ever probably imagine there is.

Unless of course I misunderstood you and you were not playing with webapps for webapp part of it, but for security thing. Then keep trying, and remember you will also learn a lot by attacking the app you created.


问:
Can objects constructed from the same class have unique method definitions?
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?

答:
Methods in most (class-based) OOP languages are fixed by type.

JavaScript is prototype-based, not class based and so you can override methods on a per-instances base because there is no hard distinction between "class" and object; in reality, a "class" in JavaScript is an object which is like a template for how the instances should work.

Any language which allows first-class functions, Scala, Java 8, C# (via delegates) etc, can act like you have per-instance method overrides; you would have to define a field with a function type and then override it in each instance.

Scala has another posibility; In Scala, you can create object singletons (using the object keyword instead of the class keyword), so you can extend your class and override the methods, resulting in a new instance of that base class with overrides.

Why would someone do this? There could be dozens of reasons. It might be that the behavior needs to me more tightly defined than using various field combinations would allow. It could also keep the code decoupled and organized better. In general however, I think these cases a rarer and there often is a more straightforward solution using field values.


问:
Which of these is the better way to structure functions in JavaScript?
I am new to programming (self teaching Javascript so I am missing some of the basics). I'm not sure if this falls under a style or best-practice question.

When writing a function that will be used often, and that has many slightly varied output expectations, should an internal if-statement be run to determine the output, or should the function be broken down into specific functions.

eg. What is better (try to ignore the contents!)

1:

```<code>function changeColour(colour){
  this.removeColour();
  switch(colour){
    case "red":
      this.colour('red');
    break;
    case "blue":
     this.colour('blue');
   break;
 }
}
</code>```

or

2.

```<code>function makeRed()
function makeBlue().. etc
</code>```

答:
Although, to some degree, the choice of how granular to make the function definitions is to do with how you feel about readability, it also to do with maintainability. If you end up with a codebase that has a lot of functions that all do a very similar thing (in your example, the latter level of granularity) then if you have to make a change to the way the repeated functionality works you'll have to go into every one of the similar functions to make the same change and you might just miss one.

If you can put this similar functionality into one readable, short function, then I would be tempted to do so. Just make sure it is short and (as an arbitrary example) fit within 50 lines os so and encodes only one main idea.


答:
You asked for any language that provide per-instance methods.
There is already an answer for Javascript, so let's see how it is done in Common Lisp, where you can use EQL-specializers:

;; define a class
(defclass some-class () ())

;; declare a generic method
(defgeneric some-method (x))

;; specialize the method for SOME-CLASS
(defmethod some-method ((x some-class)) 'default-result)

;; create an instance named *MY-OBJECT* of SOME-CLASS
(defparameter *my-object* (make-instance 'some-class))

;; specialize SOME-METHOD for that specific instance
(defmethod some-method ((x (eql *my-object*))) 'specific-result)

;; Call the method on that instance
(some-method *my-object*)
=> SPECIFIC-RESULT

;; Call the method on a new instance
(some-method (make-instance 'some-class))
=> DEFAULT-RESULT
```

Why?

EQL-specializers is useful when the argument subject to dispatching is supposed to has a type for which eql makes sense: a number, a symbol, etc. Generally speaking, you don't need it, and you simply have to define as many subclasses as needed by your problem. But sometimes, you only need to dispatch according to a parameter which is, for example, a symbol: a case expression would be limited to the known cases in the dispatching function, whereas methods can be added and removed any time.

Also, specialization on instances is useful for debugging purposes, when you want to temporarily inspect what happens with a specific object in your running application.

Title: Can objects constructed from the same class have unique method definitions?

Body:
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?

Body:
You asked for any language that provide per-instance methods.
There is already an answer for Javascript, so let's see how it is done in Common Lisp, where you can use EQL-specializers:

;; define a class
(defclass some-class () ())

;; declare a generic method
(defgeneric some-method (x))

;; specialize the method for SOME-CLASS
(defmethod some-method ((x some-class)) 'default-result)

;; create an instance named *MY-OBJECT* of SOME-CLASS
(defparameter *my-object* (make-instance 'some-class))

;; specialize SOME-METHOD for that specific instance
(defmethod some-method ((x (eql *my-object*))) 'specific-result)

;; Call the method on that instance
(some-method *my-object*)
=> SPECIFIC-RESULT

;; Call the method on a new instance
(some-method (make-instance 'some-class))
=> DEFAULT-RESULT

Why?

EQL-specializers is useful when the argument subject to dispatching is supposed to has a type for which eql makes sense: a number, a symbol, etc. Generally speaking, you don't need it, and you simply have to define as many subclasses as needed by your problem. But sometimes, you only need to dispatch according to a parameter which is, for example, a symbol: a case expression would be limited to the known cases in the dispatching function, whereas methods can be added and removed any time.

Also, specialization on instances is useful for debugging purposes, when you want to temporarily inspect what happens with a specific object in your running application.


问:
Reference counting & GC in LISP
What is the main method for reclaiming the memory in LISP? Does LISP really need garbage collection? Would not reference counts suffice?

I just wanted to know whether reference counts are enough or not for
  memory management in LISP, since I am not much familiar with LISP
  language and other functional languages either.

Thanks.

答: Environment fragments in Lisp have an undetermined lifetime, most of the LISP implementations need garbage collection to reclaim free run-time store.</p>

Title: Reference counting & GC in LISP


答:
You can also do this in Ruby using singleton objects:

```<code>class A
  def do_something
    puts "Hello!"
  end
end

obj = A.new
obj.do_something

def obj.do_something
  puts "Hello world!"
end

obj.do_something
</code>```

Produces:

```<code>Hello!
Hello world!
</code>```

As for uses, this is actually how Ruby does class and module methods. For example:

```<code>def SomeClass
  def self.hello
    puts "Hello!"
  end
end
</code>```

Is actually defining a singleton method hello on the Class object SomeClass.

Body:
You can also do this in Ruby using singleton objects:

class A
  def do_something
    puts "Hello!"
  end
end

obj = A.new
obj.do_something

def obj.do_something
  puts "Hello world!"
end

obj.do_something

Produces:

Hello!
Hello world!

As for uses, this is actually how Ruby does class and module methods. For example:

def SomeClass
  def self.hello
    puts "Hello!"
  end
end

Is actually defining a singleton method hello on the Class object SomeClass.


答:
Reference counting is basically never sufficient for managing memory due to cycles. If a language has mutation we can essentially create a structure like

```<code>  -------------------
  |        |        |
  |  Head  |  Tail  |
  |        |        |
  -------------------
     |  |       |
     |  +-------+
     |
  1 <+
</code>```

I put way too much effort into this lousy diagram

Now that the head is pointed at the tail the counter for the object will never dip to 0, meaning it'll lie around forever. This is a persistant issue for Perl and is the reason for the contortions with weak_prt in C++.

Also frankly a good GC is orders of magnitude faster than reference counting. Bumping those counters constantly (particularly when you need to ensure thread safety) is actually not free. Clever things with generational/parallel garbage collection can give essentially pause free high performance code!

It's a natural question to wonder why we couldn't just start with malloc and free in Lisp and see where that takes us. In a language with closures, however, using manual memory management is a constant perilous battle. You are constantly in grave danger of closing over something with a slightly different lifetime and having things slowly pear-shaped. This complexity is noticeable in C++ with the fine grained notions of capturing and moving in and out of closures, even this destroys the time honored series of tricks in Lisp for simulating objects and other useful creatures.

TLDR: Garbage collection is actually pretty fast and reference counting is just too naive.

Title: Reference counting & GC in LISP

Body:
What is the main method for reclaiming the memory in LISP? Does LISP really need garbage collection? Would not reference counts suffice?

I just wanted to know whether reference counts are enough or not for
  memory management in LISP, since I am not much familiar with LISP
  language and other functional languages either.

Thanks.

Body:
Reference counting is basically never sufficient for managing memory due to cycles. If a language has mutation we can essentially create a structure like

  -------------------
  |        |        |
  |  Head  |  Tail  |
  |        |        |
  -------------------
     |  |       |
     |  +-------+
     |
  1 <+

I put way too much effort into this lousy diagram

Now that the head is pointed at the tail the counter for the object will never dip to 0, meaning it'll lie around forever. This is a persistant issue for Perl and is the reason for the contortions with weak_prt in C++.

Also frankly a good GC is orders of magnitude faster than reference counting. Bumping those counters constantly (particularly when you need to ensure thread safety) is actually not free. Clever things with generational/parallel garbage collection can give essentially pause free high performance code!

It's a natural question to wonder why we couldn't just start with malloc and free in Lisp and see where that takes us. In a language with closures, however, using manual memory management is a constant perilous battle. You are constantly in grave danger of closing over something with a slightly different lifetime and having things slowly pear-shaped. This complexity is noticeable in C++ with the fine grained notions of capturing and moving in and out of closures, even this destroys the time honored series of tricks in Lisp for simulating objects and other useful creatures.

TLDR: Garbage collection is actually pretty fast and reference counting is just too naive.


答:
You can think of per-instance methods as allowing you to assemble your own class at runtime.  This can eliminate a lot of glue code, that code which has no other purpose than to put two classes together to talk to each other.  Mixins are a somewhat more structured solution to the same sorts of problems.

You're suffering a little from the blub paradox, essentially that it's difficult to see the value of a language feature until you've used that feature in a real program.  So look for opportunities where you think it might work, try it out, and see what happens.

Look in your code for groups of classes that differ only by one method.  Look for classes whose sole purpose is combining two other classes in different combinations.  Look for methods that do nothing else but pass a call through to another object.  Look for classes that are instantiated using complex creational patterns.  Those are all potential candidates to be replaced by per-instance methods.


答:
Naive reference counting cannot deal with cyclic data structures, since parts of the data structure will cause other parts to have a reference count higher than zero.

On the trivial end, Lisp (in general and Common Lisp in particular) allows you to create read-time cyclic "lists": #1#=(red green blue . #1#) is a never-ending list. They're even useful, in their right place.

Less obvious, if you have a family tree with each person represented as a node with references to parents and children, you suddenly have a graph that cannot be cleaned up using only reference counting. Is it useful? To some extent, yes. It makes looking up both children and parents from a single node effectively O(1) instead of having one of them being effectively O(1) and the other being effectively O(population) (or, admittedly, you can use weak references).

Even less obvious, updating the reference count must by necessity happen at every time a reference is made or unmade and either requires a Read-Copy-Update or a lock acquisition and release. With a periodic GC policy, this is amortised across the whole interval.

Title: Reference counting & GC in LISP


答:
It's hard to guess the motivation for your question, and so some possible answers might or might not address your real interest.

Even in some non-prototype languages it is possible to approximate this effect.

In Java, for example, an anonymous inner class is pretty close to what you're describing - you can create and instantiate a subclass of the original, overriding just the method or methods you want to.  The resulting class will be an instanceof the original class, but will not be the same class.

As to why you'd want to do this?  With Java 8 lambda expressions, I think that many of the best use cases go away.  With earlier versions of Java, at least, this can avoid a proliferation of trivial, narrow-use classes.  That is, when you have a large number of related use-cases, differing in only a tiny functional way, you can create them almost on-the-fly (almost), with the behavioral difference injected at the time you need it.

That said, even pre-J8, this can often be refactored to shift the difference into a field or three, and inject them in the constructor.  With J8, of course, the the method itself can be injected into the class, though there may be a temptation to do so when another refactoring may be cleaner (if not as cool).


答:
You can do something like this in C# and most other similar languages.</p>

```<code>public class MyClass{
    public Func<A,B> MyABFunc {get;set;}
    public Action<B> MyBAction {get;set;}
    public MyClass(){
        //todo assign MyAFunc and MyBAction
    }
}
</code>```

Body:
You can do something like this in C# and most other similar languages.

public class MyClass{
    public Func<A,B> MyABFunc {get;set;}
    public Action<B> MyBAction {get;set;}
    public MyClass(){
        //todo assign MyAFunc and MyBAction
    }
}


问:
Should I pass in filenames to be opened, or open files?
Suppose I have a function that does things with a text file - for example reads from it and removes the word 'a'.  I could either pass it a filename and handle the opening/closing in the function, or I could pass it the opened file and expect that whoever calls it would deal with closing it.

The first way seems like a better way to guarantee no files are left open, but prevents me from using things like StringIO objects

The second way could be a little dangerous - no way of knowing if the file will be closed or not, but I would be able to use file-like objects

```<code>def ver_1(filename):
    with open(filename, 'r') as f:
        return do_stuff(f)

def ver_2(open_file):
    return do_stuff(open_file)

print ver_1('my_file.txt')

with open('my_file.txt', 'r') as f:
    print ver_2(f)
</code>```

Is one of these generally preferred?  Is it generally expected that a function will behave in one of these two ways?  Or should it just be well documented such that the programmer can use the function as appropriate?

答:
Convenient interfaces are nice, and sometimes the way to go. However, most of the time good composability is more important than convenience, as a composable abstraction allows us to to implement other functionality (incl. convenience wrappers) on top of it.

The most general way for your function to use files is to take an open file handle as parameter, as this allows it to also use file handles that are not part of the filesystem (e.g. pipes, sockets, …):

```<code>def your_function(open_file):
    return do_stuff(open_file)
</code>```

If spelling out with open(filename, 'r') as f: result = your_function(f) is too much to ask of your users, you could choose one of the following solutions:

your_function takes an open file or a file name as parameter. If it is a filename, the file is opened and closed, and exceptions propagated. There is a bit of an issue with ambiguity here which could be worked around using named arguments.

Offer a simple wrapper that takes care of opening the file, e.g.

```<code>def your_function_filename(file):
    with open(file, 'r') as f:
        return your_function(f)
</code>```

I generally perceive such functions as API bloat, but if they provide commonly used functionality, the gained convenience is a sufficiently strong argument.

Wrap the with open functionality in another composable function:

```<code>def with_file(filename, callback):
    with open(filename, 'r') as f:
        return callback(f)
</code>```

used as with_file(name, your_function) or in more complicated cases with_file(name, lambda f: some_function(1, 2, f, named=4))

Body:
Convenient interfaces are nice, and sometimes the way to go. However, most of the time good composability is more important than convenience, as a composable abstraction allows us to to implement other functionality (incl. convenience wrappers) on top of it.

The most general way for your function to use files is to take an open file handle as parameter, as this allows it to also use file handles that are not part of the filesystem (e.g. pipes, sockets, …):

def your_function(open_file):
    return do_stuff(open_file)

If spelling out with open(filename, 'r') as f: result = your_function(f) is too much to ask of your users, you could choose one of the following solutions:

your_function takes an open file or a file name as parameter. If it is a filename, the file is opened and closed, and exceptions propagated. There is a bit of an issue with ambiguity here which could be worked around using named arguments.

Offer a simple wrapper that takes care of opening the file, e.g.

def your_function_filename(file):
    with open(file, 'r') as f:
        return your_function(f)

I generally perceive such functions as API bloat, but if they provide commonly used functionality, the gained convenience is a sufficiently strong argument.

Wrap the with open functionality in another composable function:

def with_file(filename, callback):
    with open(filename, 'r') as f:
        return callback(f)

used as with_file(name, your_function) or in more complicated cases with_file(name, lambda f: some_function(1, 2, f, named=4))


问:
Is there any mechanism to make programming language more stable(compatible) for changes?
There are a big number of programming languages. Some of them grow up and become very popular. People use such languages more and more often. The founder of such language (or founding organisation/community) may try to implement changes to make the language better. But sometimes it's hard to make some changes because of backward compatibility and such ugly things have already existed in the language for years, and are used by many users.

Are there any architectural principles or steps, during the language design phase, which can help to make it more stable so the language designers won't be as afraid to break backward compatibility?

答:
Language stability is not a technical decision. It is a contract between the language author and the users.

The author advertise a given version as more or less stable. The less stable a language is, the more changes the author can make. Each user interested by the language can decide if he wants to invest time in it to learn new features or develop applications that might be broken by next month's update.

Using an unstable language can be interesting because you are interested by a new concept, or you want to help by giving your feedback. If you are a business, you might prefer to wait for a technology to be more stable before investing your time in it.You care more about stuff like time to market, and user experience.

So this is a communication & trust issue. Look at the rust language development. They are crystal clear about what they are changing and what they are keeping. When they want to delay a decision about a given feature, they use what they call a feature gate. On the other side, the angular team faced a lot of anger over their 2.0 announcement because the changes were larger than expected.

Even libraries author have to communicate about the stability of their apis. Pretty much any technology used by other people have to strike a balance between stability and perfection. A car maker cannot change the position of the pedals, and a laptop designer won't invent a new keyboard layout for the same reason: you are not helping your users if you cannot make a decision about the way they will use your product.


答:
The real question is one of completeness. Is your file processing function the complete processing of the file, or is it just one piece in a chain of processing steps? If it is complete in and of its own, then feel free to encapsulate all file access within a function.

```<code>def ver(filepath):
    with open(filepath, "r") as f:
        # do processing steps on f
        return result
</code>```

This has the very nice property of finalizing the resource (closing the file) at the end of the with statement.

If however there is possibly a need for processing an already-open file, then the distinction of your ver_1 and ver_2 makes more sense. For example:

```<code>def _ver_file(f):
    # do processing steps on f
    return result

def ver(fileobj):
    if isinstance(fileobj, str):
        with open(fileobj, 'r') as f:
            return _ver_file(f)
    else:
        return _ver_file(fileobj)
</code>```

This kind of explicit type testing is often frowned upon, especially in languages like Java, Julia, and Go where type- or   interface-based dispatching is directly supported. In Python, however, there is no language support for type-based dispatching. You may occasionally see criticism of direct type-testing in Python, but in practice it's both extremely common and quite effective. It enables a function to have a high degree of generality, handling whatever datatypes are likely to come its way, aka "duck typing." Note the leading underscore on _ver_file; that is a conventional way of designating a "private" function (or method). While it can technically be called directly, it suggests that function is not intended for direct external consumption.

2019 update: Given recent updates in Python 3, for example that paths are now potentially stored as pathlib.Path objects not just str or bytes (3.4+), and that type hinting has gone from esoteric to mainstream (circa 3.6+, though still actively evolving), here's updated code that takes these advances into account:

```<code>from pathlib import Path
from typing import IO, Any, AnyStr, Union

Pathish = Union[AnyStr, Path]  # in lieu of yet-unimplemented PEP 519
FileSpec = Union[IO, Pathish]

def _ver_file(f: IO) -> Any:
    "Process file f"
    ...
    return result

def ver(fileobj: FileSpec) -> Any:
    "Process file (or file path) f"
    if isinstance(fileobj, (str, bytes, Path)):
        with open(fileobj, 'r') as f:
            return _ver_file(f)
    else:
        return _ver_file(fileobj)
</code>```

Title: Should I pass in filenames to be opened, or open files?

Body:
Suppose I have a function that does things with a text file - for example reads from it and removes the word 'a'.  I could either pass it a filename and handle the opening/closing in the function, or I could pass it the opened file and expect that whoever calls it would deal with closing it.

The first way seems like a better way to guarantee no files are left open, but prevents me from using things like StringIO objects

The second way could be a little dangerous - no way of knowing if the file will be closed or not, but I would be able to use file-like objects

```<code>def ver_1(filename):
    with open(filename, 'r') as f:
        return do_stuff(f)

def ver_2(open_file):
    return do_stuff(open_file)

print ver_1('my_file.txt')

with open('my_file.txt', 'r') as f:
    print ver_2(f)
</code>```

Is one of these generally preferred?  Is it generally expected that a function will behave in one of these two ways?  Or should it just be well documented such that the programmer can use the function as appropriate?

Body:
The real question is one of completeness. Is your file processing function the complete processing of the file, or is it just one piece in a chain of processing steps? If it is complete in and of its own, then feel free to encapsulate all file access within a function.

def ver(filepath):
    with open(filepath, "r") as f:
        # do processing steps on f
        return result

This has the very nice property of finalizing the resource (closing the file) at the end of the with statement.

If however there is possibly a need for processing an already-open file, then the distinction of your ver_1 and ver_2 makes more sense. For example:

def _ver_file(f):
    # do processing steps on f
    return result

def ver(fileobj):
    if isinstance(fileobj, str):
        with open(fileobj, 'r') as f:
            return _ver_file(f)
    else:
        return _ver_file(fileobj)

This kind of explicit type testing is often frowned upon, especially in languages like Java, Julia, and Go where type- or   interface-based dispatching is directly supported. In Python, however, there is no language support for type-based dispatching. You may occasionally see criticism of direct type-testing in Python, but in practice it's both extremely common and quite effective. It enables a function to have a high degree of generality, handling whatever datatypes are likely to come its way, aka "duck typing." Note the leading underscore on _ver_file; that is a conventional way of designating a "private" function (or method). While it can technically be called directly, it suggests that function is not intended for direct external consumption.

2019 update: Given recent updates in Python 3, for example that paths are now potentially stored as pathlib.Path objects not just str or bytes (3.4+), and that type hinting has gone from esoteric to mainstream (circa 3.6+, though still actively evolving), here's updated code that takes these advances into account:

from pathlib import Path
from typing import IO, Any, AnyStr, Union

Pathish = Union[AnyStr, Path]  # in lieu of yet-unimplemented PEP 519
FileSpec = Union[IO, Pathish]

def _ver_file(f: IO) -> Any:
    "Process file f"
    ...
    return result

def ver(fileobj: FileSpec) -> Any:
    "Process file (or file path) f"
    if isinstance(fileobj, (str, bytes, Path)):
        with open(fileobj, 'r') as f:
            return _ver_file(f)
    else:
        return _ver_file(fileobj)


答:
Conceptually, even though in a language like Java all instances of a class must have the same methods, it is possible to make it appear as though they don't by adding an extra layer of indirection, possibly in combination with nested classes.

For example, if a class Foo may define a static abstract nested class QuackerBase which contains a method quack(Foo), as well as several other static nested classes deriving from QuackerBase, each with its own definition of quack(Foo), then if the outer class has a field quacker of type QuackerBase, then it may set that field to identify a (possibly singleton) instance of any one of its nested classes.  After it has done so, invoking quacker.quack(this) will execute the quack method of the class whose instance has been assigned to that field.

Because this is a fairly common pattern, Java includes mechanisms to automatically declare the appropriate types.  Such mechanisms are not really doing anything that couldn't be done by simply using virtual methods and optionally-nested static classes, but they greatly reduce the amount of boilerplate necessary to produce a class whose sole purpose is to run a single method on behalf of another class.


问:
Why does TDD work?
Test-driven development (TDD) is big these days. I often see it recommended as a solution for a wide range of problems here in Programmers SE and other venues. I wonder why it works.

From an engineering point of view, it puzzles me for two reasons:

The "write test + refactor till pass" approach looks incredibly anti-engineering. If civil engineers used that approach for bridge construction, or car designers for their cars, for example, they would be reshaping their bridges or cars at very high cost, and the result would be a patched-up mess with no well thought-out architecture. The "refactor till pass" guideline is often taken as a mandate to forget architectural design and do whatever is necessary to comply with the test; in other words, the test, rather than the user, sets the requirement. In this situation, how can we guarantee good "ilities" in the outcomes, i.e. a final result that is not only correct but also extensible, robust, easy to use, reliable, safe, secure, etc.? This is what architecture usually does.

Testing cannot guarantee that a system works; it can only show that it doesn't. In other words, testing may show you that a system contains defects if it fails a test, but a system that passes all tests is not safer than a system that fails them. Test coverage, test quality and other factors are crucial here. The false safe feelings that an "all green" outcomes produces to many people has been reported in civil and aerospace industries as extremely dangerous, because it may be interepreted as "the system is fine", when it really means "the system is as good as our testing strategy". Often, the testing strategy is not checked. Or, who tests the tests?

In summary, I am more concerned about the "driven" bit in TDD than about the "test" bit. Testing is perfectly OK; what I don't get is driving the design by doing it.

I would like to see answers containing reasons why TDD in software engineering is a good practice, and why the issues that I have explained above are not relevant (or not relevant enough) in the case of software. Thank you.

答:
Why does TDD work?

It doesn't.

Clarification: automated tests are better than no tests. However I personally think that most of unit tests are waste because they usually tautological (i.e. says things obvious from actual code under test) and it can't be easily proven that they consistent, not redundant and cover all border cases (where errors usually occur).

And most important: Good software design doesn't magically falls out from tests as it's advertised by many agile/TDD evangelist. Everybody claiming otherwise please provide links to peer-reviewed scientific research which proves this, or at least reference to some open source project where benefits of TDD can be potentially studied by its code changes history.

Title: Why does TDD work?


问:
Forking a dual licensed app: How to license on my end?
I forked a project that was dual licensed under the GPL and a commercial license. Since my code was open source and the GPL being what it is, I started by releasing my app under the GPL.

But now I'm thinking about dual licensing the project and can't figure out what to do. Since I have copyright on a majority of the code (most of the code was either rewritten or new), can I just pick a commercial license or do I have to buy the upstream commercial license since I'm technically a "derivative" of the project?

答:
In order to distribute your project that is a derivative of the original project, you must have permission to do so, because by default copyright law forbids that. Such permission is called a license.

You apparently have multiple choice for how to obtain permission. One of them is the GPL. If you choose that way, then you must comply to the GPL's terms: release the entire thing under the GPL.

If you don't want that, you need to get permission another way. Maybe you can get the commercial license, if it allows redistribution of derived works under the kind of license you want.

If you can't use either license for what you want to do, you need to contact the original copyright holder to see if they want to work out a different license with you.

If none of those three things work out, copyright law simply forbids distribution of derived works, and you won't be able to do it.

ContentLicense: CC BY-SA 2.5


问:
Is naming a class based on its implementation acceptable?
Is naming a class according to its implementation an acceptable practice?

e.g. SortedSet if the class is maintains a sorted list of unique items or TreeSet if it using a binary search tree structure instead.

答:
A class identifier should reflect things that outside users of that class identifier are likely to care about.  Because different users are likely to care about different things, it will generally not be possible to find a name with the "perfect" level of descriptiveness for all usage scenarios.

Note that there is a common pattern of List foo<Bar> = new ArrayList<Bar>();  Code which creates the list selects a kind of list to create, but code which uses the list doesn't need to use the identifier ArrayList.  It's debatable whether the word "Array" is semantically meaningful, or would have been omitted if such were possible.  Arguably a better pattern would have been List foo<Bar> = List<Bar>.CreateNew();, in which case most client code would never have to see the class name ArrayList; the collection types were implemented early on in the development of Java, however, and thus reflect a mixture of good and bad practices.

Note, by the way, that while Java will not allow an interface to be used in a new expression, there really wouldn't be anything wrong semantically with allowing programmers to say new List() when they want a new object which implements the List interface, they don't need the object to do anything beyond what's included in the interface, and they don't want to promise to refrain from using any particular features of the interface.  Most code which wants a new empty list shouldn't care whether it's backed by a single array, an array of arrays, a linked list of arrays, or some other structure.


答:
Be aware that languages change throughout their life, regardless of how well it might be designed up front. Instead of trying to immediately ship the most awesome language on earth, first try to be useful and extensible. A mediocre langauge which I can actually use is worth more than any wonderful programming language that only exists in theory.

Consider facilities to make the syntax extensible, e.g. macros. Macros are not automatically a good thing and can be too powerful. Some languages have a very flexible syntax from the start which reduces the need for macros. A couple of scenarios to consider:

Can I introduce a new operator such as |> without leaving the language? Can I choose precedence and associativity for this operator?

How much ceremony do I have to go through for an inline function/lambda/closure?

Can I use existing language syntax to implement a foreach loop syntax? E.g. Ruby and Scala can do this through their flexible method call syntax with lambdas.

Consider facilities to keep semantics extensible. Common needs are:

Operator overloading, where user-defined types can assign their own meaning to existing operators. This makes a language much more enjoyable in maths-heavy applications.

Literal overloading. Can I make string literals be of my own string type? Can I make all numeric literals in the current scope be bignums?

Metaobject protocols. If the language doesn't have traits, can I implement them inside the current object system? Can I implement a different method resolution order? Can I swap out the way objects are stored or how methods are dispatched?

Have regression tests. Lots of test. Not only written by the language designers, but also by users. When adding a feature breaks these tests, carefully weigh the benefits of that feature against the benefit of backwards compatibility.

Version your language. Not just in your documentation, but also in the source code itself. Once you do that, the only part of your language that cannot change is this version pragma syntax. Examples: Racket allows you to specify a dialect. Perl allows you to use v5.20, which enables all backwards-incompatible features of Perl v5.20. You can also load single features explicitly like use feature 'state'. Similar: Python's from __future__ import division.

Consider designing your language in a way that results in few reserved words. Just because class introduces a class does not imply that I wouldn't be able to have a local variable named class. In practice, this results in keywords that introduce variable or method declarations, counter to the C-like tradition of using type names to introduce declarations. Another alternative is to use sigils for your $variables, as in Perl and PHP.

Parts of this answer are influenced by Guy Steele's speech “Growing a Language” (1998) (pdf) (youtube).

Title: Is there any mechanism to make programming language more stable(compatible) for changes?

Body:
There are a big number of programming languages. Some of them grow up and become very popular. People use such languages more and more often. The founder of such language (or founding organisation/community) may try to implement changes to make the language better. But sometimes it's hard to make some changes because of backward compatibility and such ugly things have already existed in the language for years, and are used by many users.

Are there any architectural principles or steps, during the language design phase, which can help to make it more stable so the language designers won't be as afraid to break backward compatibility?


答:
Since other (Java) implementations of Collections describe their implementation, sometimes to great detail (e.g. CopyOnWriteArrayList) I would say yes, naming after the implementation is fine, and is expected.

Unlike @supercat, I think this detailed naming is a good thing, as, unfortunately, at some point, somebody actually has to pick a specific implementation - a HashMap where things are super fast but unsorted, or a TreeMap which is slightly slower but things are sorted, or some ConcurrentXXX version?

It might be o.k. to follow his idea and have List.newInstance() or Map.newInstance(), but "they" would have to spec which kind of "default, best general purpose" implementation it does create.  This might cause a lot of arguments.

Often in my code I will implement a protected method to generate a new collection, e.g.

```<code>protected Map newMap() {
   return new HashMap();
}
</code>```

and allow end users to override if they prefer something else.

Title: Is naming a class based on its implementation acceptable?

Body:
Is naming a class according to its implementation an acceptable practice?

e.g. SortedSet if the class is maintains a sorted list of unique items or TreeSet if it using a binary search tree structure instead.

Body:
Since other (Java) implementations of Collections describe their implementation, sometimes to great detail (e.g. CopyOnWriteArrayList) I would say yes, naming after the implementation is fine, and is expected.

Unlike @supercat, I think this detailed naming is a good thing, as, unfortunately, at some point, somebody actually has to pick a specific implementation - a HashMap where things are super fast but unsorted, or a TreeMap which is slightly slower but things are sorted, or some ConcurrentXXX version?

It might be o.k. to follow his idea and have List.newInstance() or Map.newInstance(), but "they" would have to spec which kind of "default, best general purpose" implementation it does create.  This might cause a lot of arguments.

Often in my code I will implement a protected method to generate a new collection, e.g.

protected Map newMap() {
   return new HashMap();
}

and allow end users to override if they prefer something else.


问:
Jenkins to automate deployment of ASP.NET applications
Is there any possibility to automate/semi-automate deployments of ASP.NET web applications using Jenkins. It can be under controlled or uncontrolled environments, for uncontrolled user needs to enter userid and password. I am looking out for ways to copy the files from target to destination and run sql scripts in web farm scenario.

Edit
Currently we are using bat files to xcopy/configure app pool/sql cmd, etc to deploy the application. But for this to work, production support team needs to download the source code, build the project and run the bat files to deploy the application.

Now, we want to automate the deployment without user downloading the source code and end user just needs to visit a url and fill userid and password parameters and select svn tag and it should get deployed. But Jenkins is running under anonymous login, so the existing bat file will not work since it doesn't have permissions to run the script.

So, I would like to know if there exists any alternatives for this kind of situation. It will be good if user context is impersonated by using entered userid and password allowing existing batch file to run without further changes. If it is not possible, we would like to explore other ideas too but we don't have flexibility to choose a automated tool like  puppet, etc, we should stick around with these batch files.

答:
I am already using Jenkins for .Net apps and TFS.

Add required configuration in your project and transformation & check-in the code.

Get the latest from TFS (use TFS Plug-in)

Build the Project (use MSBuild Plug-in). you can publish the code from Msbuild using command line arguments.

Sync the code from publish location to destination using msdeploy.exe command (located at
"C:\Program Files (x86)\IIS\Microsoft Web Deploy V2\msdeploy.exe")

You can send emails and do the backup via Jenkins too.

You can also use MSTest.exe to execute unit test and show it at jenkin console or publish the test result also.


问:
In Python, is there any difference (apart from a few listed exceptions) between classes and dictionaries?
My logic goes like this:

```<code>def A(val):
    return {'a':val}

print(A(7)['a'])
</code>```

is the same as

```<code>class A:
    def __init__(self, val):
        self.a = val

print(A(7).a)
</code>```

Obviously, there are problems and some differences:

This only applies to languages like python where you can create a dictionary with different types in it.

The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.

Special shortcut treatments. Like str(x) calls __str__ and obj.function() changes into cls.function(obj).

Inheritance.

Actual class objects (if A is the class, you can get A.__init__ (for example) as an unbound method.

Apart from these small cases, dictionaries == classes (to me). Do you agree with me?

答:
You can think of an object o as an entity containing

a collection of local variables v1, v2, ... (the state of the object),

a collection of closures m1, m2, ... that close over v1, v2, m1, m2 (the methods of the object),

a mechanism to access the local variable and methods by name: an object is basically a higher-order function that takes a name as input and returns a field or a method as a result.

In a Python object you use the dot notation (o.var, o.foo()) to access members and methods. Of course, you can easily simulate this by means of a dictionary as you have described: a dictionary is also a mapping (see point 3) and you can use it to store object fields or methods.

So I would say that the class construct is a more convenient syntax to express the object pattern. You can simulate objects with dictionaries too, it just gets more verbose.

The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.

Instead of having functions to create classes, I would imagine using functions to create objects (i.e. special dictionaries), which would correspond to class constructors. See also your example: function A() is the constructor function corresponding to the __init__() method of class A.

Inheritance.

I think that if you model classes with constructor functions returning dictionaries, then you can model inheritance by using the superclass constructor in the subclass constructor.
The subclass constructor can call the superclass constructor and then extend / override the resulting dictionary with its own definitions.

For example:

```<code># Superclass A.
def A(val):
    def toString(a):
        return str(a['a'])

    def printOut(a):
        print(a['toString'](a))

    return {'a': val, 'toString': toString, 'printOut': printOut}

# B is a subclass of A.
def B(val):
    # Override method.
    def toString(a):
        return 'value = ' + str(a['a'])

    r = A(val)
    r['toString'] = toString
    return r
</code>```

Summarizing, I would not say that dictionaries are the same as classes:

A dictionary is an arbitrary mapping.

An object is a special mapping from names to variables and methods.

A class is a language construct that gathers together objects with similar structure and helps to create objects.

Objects and classes can be simulated in a straightforward way using functions and dictionaries.

Body:
You can think of an object o as an entity containing

a collection of local variables v1, v2, ... (the state of the object),

a collection of closures m1, m2, ... that close over v1, v2, m1, m2 (the methods of the object),

a mechanism to access the local variable and methods by name: an object is basically a higher-order function that takes a name as input and returns a field or a method as a result.

In a Python object you use the dot notation (o.var, o.foo()) to access members and methods. Of course, you can easily simulate this by means of a dictionary as you have described: a dictionary is also a mapping (see point 3) and you can use it to store object fields or methods.

So I would say that the class construct is a more convenient syntax to express the object pattern. You can simulate objects with dictionaries too, it just gets more verbose.

The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.

Instead of having functions to create classes, I would imagine using functions to create objects (i.e. special dictionaries), which would correspond to class constructors. See also your example: function A() is the constructor function corresponding to the __init__() method of class A.

Inheritance.

I think that if you model classes with constructor functions returning dictionaries, then you can model inheritance by using the superclass constructor in the subclass constructor.
The subclass constructor can call the superclass constructor and then extend / override the resulting dictionary with its own definitions.

For example:

# Superclass A.
def A(val):
    def toString(a):
        return str(a['a'])

    def printOut(a):
        print(a['toString'](a))

    return {'a': val, 'toString': toString, 'printOut': printOut}

# B is a subclass of A.
def B(val):
    # Override method.
    def toString(a):
        return 'value = ' + str(a['a'])

    r = A(val)
    r['toString'] = toString
    return r

Summarizing, I would not say that dictionaries are the same as classes:

A dictionary is an arbitrary mapping.

An object is a special mapping from names to variables and methods.

A class is a language construct that gathers together objects with similar structure and helps to create objects.

Objects and classes can be simulated in a straightforward way using functions and dictionaries.


答:
You're right. Objects in dynamic languages evolved from, and in some ways resemble, fancy dictionary/mapping objects. This is very true for prototype-based languages like JavaScript, and still true for class-based languages like Python and Ruby.

However, the question is overly reductionistic. You ask "is there any difference?" only to quickly exclude quite a few very important differences. Capabilities like inheritance (Python has an elaborate multiple inheritance system with extensive metaclass support) and the special processing of dunder methods are not trifles. They're extensive bodies of work that define much of the language's semantics, operation, and extensibility.

You might want a listing of other ways Python classes are different, such as the the ability to

Intervene at object creation time and systematically re-orchestrate how objects are created (metaclasses),

Use static, non-dictionary representations (slots),

Access members through attribute notation (obj.attr),

Specialize functional attributes (aka methods) as virtual properties (@property), class rather than instance methods (@classmethod), or class-relative normal functions (@staticmethod).

We could list out even more ways that classes are different than mere "syntax sugar" on top of dictionaries. And the option to use a slotted, non-dictionary implementation should seal the deal. But such listings miss the number one issue:

Classes define new data types.

Classes and objects may be at some level just fancied dictionaries, but they're sufficiently evolved that they become something else entirely.

Classes define new data types. In all recent versions of the language--2.x forward, using "new style objects" that subclass object--user-defined classes are largely equivalent too, and fully parallel with, built-in data types. You can ask type(x) and instance(x, (int, str, MyClass)), interacting with classes and instances just as you do built-in datatypes and their values. That is not possible in most traditional static languages, where you may be able to build new abstract data types, but they will never, ever be comparable to, or as flexible as, the built-in types.

Full disclosure: There are a few remaining differences, largely subtle, and mostly based on the fact that built in types are implemented "under the covers" in C, and are not Python objects. per se.

But largely, classes are different from dictionaries in ways that pervade the language design, and that put them and their instances on par with language-define types. In Python, their similarity to mapping objects is decidedly secondary.

Title: In Python, is there any difference (apart from a few listed exceptions) between classes and dictionaries?

Body:
My logic goes like this:

```<code>def A(val):
    return {'a':val}

print(A(7)['a'])
</code>```

is the same as

```<code>class A:
    def __init__(self, val):
        self.a = val

print(A(7).a)
</code>```

Obviously, there are problems and some differences:

This only applies to languages like python where you can create a dictionary with different types in it.

The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.

Special shortcut treatments. Like str(x) calls __str__ and obj.function() changes into cls.function(obj).

Inheritance.

Actual class objects (if A is the class, you can get A.__init__ (for example) as an unbound method.

Apart from these small cases, dictionaries == classes (to me). Do you agree with me?


问:
Is there an accepted design pattern for storing a few global variables in a NoSQL database?
I'm wanting to create an admin dashboard for my app, and to show new events there. In order to know which events are new, I'll need to store at least one extra datapoint to the server: the last date at which the admin user (me) looked at the events and marked them all as read.

I'm trying to figure out where it makes sense to store that data.

I'm using Mongoose, and have a few different document types. Options I've considered include:

create an extra field on the user schema, that will be undefined for all non-admin users

create a new document type just to store admin data

use mongodb directly, rather than going through mongoose

Is one of these better than the others? Have I missed something that's obviously better than all of them?

答:
I'm not familiar with mongoose specifically, but I note that your first suggestion has an interesting problem: if you later expand the number of admin users, you will have multiple copies of the data that do not necessarily agree with each other, whereas it seems that for your application you truly do want the data to be global (as multiple admin users shouldn't have to all review the same events).  This points strongly toward your second option.

As I'm unfamiliar with mongoose, I don't know if there is any reason talking directly to mongodb would be beneficial to you, but if the second option is a possibility I see no reason it should be necessary.


问:
The source is the documentation - part 1
Searching the specification for the btrfs file system i stumbled once more over the catchphrase: "The code is the documentation". This implies that changing the code changes the specification.

Does this approach make sense while working on a file system that will be used from various drivers or applications?

I can understand that a smal group can split the job and everyone works on her own task. But how should this work with a larger group, spread over several places?

(btrfs spec would still be welcome)

答:
I disagree: The tests are the documentation/specification. The code is the documentation of how it was implemented.

Tests are stable, long lived, publishable and legible by most (you don't publish the test code, just what is being tested). The implementation is impermanent, or at least there is no requirement or expectation that it be permanent, and code is not realistically publishable (only developers can decipher it).

My team uses Spock testing framework, which can publish reports. We publish these reports as our specifications - the name of the test describes the behaviour. Whenever a spec change is requested, we create a test that captures the desired behaviour, then code to make that test go green (BDD).

Btw I can recommend Spock.