问:
Stopping developers committing to the wrong branch on DVCS

The problem

I am on a software project which has about 10 developers, we share source code via Mercurial. We have a development and production branch per release. Repeatedly during the course of the project we have had source code from one branch i.e. v1 getting into patch and maintenance branches for earlier releases of software i.e. v2.

This results in either time spent backing out the wrong commit, or wrong (possibly non-QAd) code reaching and getting deployed in the wrong branch if we don't notice that the code has gone into the wrong branch.

Our branch and merge design/method

```<code>               v1-test   v1-patch1   v1-patch2
               ^---------^-----------^                v1-prod
              /         / \           \
-----------------------/   \           \              v1-dev
              \             \           \
               --------------------------\            v2-dev
                             \       \    \
                              ^-------^-------------  v2-prod
                              v2-test v2-patch1
</code>```

Hence we will work on a release development branch, until it's deemed ready, branch it off for a single testing/UAT/Production branch, where all releases and maintenance is done. Tags are used to build releases of this branch. While v1 is being tested, a branch will have been made for v2 and developers will start working on new features.

What tends to happen is that a developer commits work due for v2-dev branch into v1-dev or v1-prod, or worse, they merge v2-dev into v1-prod (or similar such mistakes).

We tell most developers not to access the -prod branches, however code still sneaks in. A group of more senior developers `look after' the -prod branch.

It should be noted that while v2 has just started development, there may still be some quite hefty patches going into v1 to fix issues. I.e. v1 may not just be getting the odd small patch.

What we've tried so far

Having a separate -prod branch, with gatekeepers. A -prod branch should raise warnings through its name and most developers don't need to ever be in that branch. This has not really reduced the problem.

Raised awareness of this problem amongst the developers, to try and make them more vigilant. Again this has not been very successful.

Possible reasons I see for developers committing to the wrong branch

Too complex a branch design

Having active development in multiple branches in parallel. (The project does exhibit symptoms of using the avalanche-model.)

Developers don't understand the DVCS well enough

Questions I've read which were somewhat relevant

I've read this question on not committing to the wrong branch and I feel that the answers regarding visual cues may be helpful. However I am not entirely convinced that the problems we're experiencing are not symptoms of a more fundamental problem.

With the visual clues, we can incorporate them into the command line easily, however about half the team use eclipse which I'm unsure how to incorporate visual cues.

Question

What methods, in the form of software, project management or governance can we use to reduce (ideally stop) commits to the wrong branch taking up our time or dirtying our deployed code?

Specific comment on the reasons I believe may be contributing as outlined above would be appreciated, but this shouldn't limit your reply.

答:
This looks like you have identified one of my major bug bears.  The majority of source control tools are exactly that, source control tools. They allow a bunch of developers to work on the same source directory, making changes and handling conflicts.  There have been a few rough edges along the way, but cvs, subversion, git, mercural etc all deliver on this.

Then you have the next step, when you need to stabilise code for release, and you introduce branching.  This is where the tools start to fail the developers.  The tools are capable at making the branch, and even identifying the sets of changes that have accrued on the branches after they have been branched, but that's not the problem you have now faced.

The tools are really poor at selecting which changes need to be copied to other branches, and when that needs to occur.  Git-flow attempts to solve this by creating a branching strategy that means that when branches are merged, its ALL changes are merged, and then requires the programmer to make sensible choices about when and which branches are merged.

On a single repository where all the developers are working on one project that has a single release thread, git flow solves the problem, but life is not that simple for many companies.

The complex environment is where you have multiple teams responsible for different aspects of the total solution, performing internal releases to other teams.  git-flow is just not capable of solving this kind of issue.

The only way I have seen this work, is if each team is responsible for defining their releases, and controlling when their dependencies change.  Just because team A have released release 1.3, team B only start using team A's 1.3 release when team B chooses.

In effect a team of developers define the groups of changes that need to be moved, and the developers receiving the changes define when they receive the group of changes.

The only source control tool I have seen that genuinely delivers this is accurev - and even then, most of your developers will grumble about it because the GUI is too confusing for them, and it doesn't behave like subversion...


问:
Is try-finally expensive
In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.

Cleaning the resource before every return statement

```<code>void func()
{
    login();

    bool ret = dosomething();
    if(ret == false)
    {
        logout();
        return;
    }

    ret = dosomethingelse();
    if(ret == false)
    {
        logout();
        return;
    }

    dootherstuff();

    logout();
}
</code>```

Cleaning the resource in a finally block

```<code>void func()
{
    login();

    try
    {
        bool ret = dosomething();
        if(ret == false)
            return;

        ret = dosomethingelse();
        if(ret == false)
            return;

        dootherstuff();

    }
    finally
    {
        logout();
    }
}
</code>```

I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the finally way of doing this - but I was wondering if it will cause any performance hit in a big project.

答:
https://stackoverflow.com/questions/299068/how-slow-are-java-exceptions

The accepted answer on this question shows wrapping a function call in a try catch block costs less than 5% over a bare function call. Actually throwing and catching the exception caused runtime to balloon to more than 66x the bare function call.  So if you expect the exception design to throw regularly then I would try to avoid it (in properly profiled performance critical code), however if the exceptional situation is rare then it isn't a big deal.

ContentLicense: CC BY-SA 3.0

Title: Is try-finally expensive


问:
Should I use abstract or virtual methods?
If we assume that it is not desirable for the base class to be a pure interface class, and using the 2 examples from below, which is a better approach, using the abstract or virtual method class definition?

The advantage of "abstract" version is that it is probably looks cleaner and forces the derived class to give a hopefully meaningful implementation.

The advantage of the "virtual" version is that it can be easily pulled in by other modules and used for testing without adding a bunch of underlying framework like the abstract version requires.

Abstract Version:

```<code>public abstract class AbstractVersion
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

Virtual Version:

```<code>public class VirtualVersion
{
    public virtual ReturnType Method1()
    {
        return ReturnType.NotImplemented;
    }

    public virtual ReturnType Method2()
    {
        return ReturnType.NotImplemented;
    }
             .
             .
    public virtual ReturnType MethodN()
    {
        return ReturnType.NotImplemented;
    }

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

答:
I would suggest that you reconsider having a separate interface defined which your base class implements, and then you follow the abstract approach.

Imaging code like this:

```<code>public interface IVersion
{
    ReturnType Method1();
    ReturnType Method2();
             .
             .
    ReturnType MethodN();
}

public abstract class AbstractVersion : IVersion
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

Doing this solves these problems:

By having all code that uses objects derived from AbstractVersion can now be implemented to receive IVersion interface instead,  This means that they can be more easily unit tested.

Release 2 of your product can then implement an interface IVersion2 to provide additional functionality without breaking your existing customers code.

eg.

```<code>public interface IVersion
{
    ReturnType Method1();
    ReturnType Method2();
             .
             .
    ReturnType MethodN();
}

public interface IVersion2
{
    ReturnType Method2_1();
}

public abstract class AbstractVersion : IVersion, IVersion2
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();
    public abstract ReturnType Method2_1();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

It's also worth reading up about dependency inversion as well, to prevent this class from containing hard coded dependencies that prevent effective unit testing.

Body:
I would suggest that you reconsider having a separate interface defined which your base class implements, and then you follow the abstract approach.

Imaging code like this:

public interface IVersion
{
    ReturnType Method1();
    ReturnType Method2();
             .
             .
    ReturnType MethodN();
}

public abstract class AbstractVersion : IVersion
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}

Doing this solves these problems:

By having all code that uses objects derived from AbstractVersion can now be implemented to receive IVersion interface instead,  This means that they can be more easily unit tested.

Release 2 of your product can then implement an interface IVersion2 to provide additional functionality without breaking your existing customers code.

eg.

public interface IVersion
{
    ReturnType Method1();
    ReturnType Method2();
             .
             .
    ReturnType MethodN();
}

public interface IVersion2
{
    ReturnType Method2_1();
}

public abstract class AbstractVersion : IVersion, IVersion2
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();
    public abstract ReturnType Method2_1();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}

It's also worth reading up about dependency inversion as well, to prevent this class from containing hard coded dependencies that prevent effective unit testing.


问:
How would you evaluate object oriented design skills?
what kind of insights or questions would lead you to determine a person's OOAD skills.</p>

答:
Something that seems to work rather well, and actually only takes a few seconds: ask them to design an object model. It doesn't matter for what. It can be absolutely trivial. In fact, it probably should be trivial, to not drag out the test unnecessarily.

If the first thing they write is an object, they are already ahead of 99% of their peers in their understanding of OO. If the first thing they write is a class, kindly ask them to go out and send the next candidate in, and contemplate about why it's called OOP and not COP.

ContentLicense: CC BY-SA 2.5


答:
As indicated in How slow are Java exceptions? one can see that the slowness of try {} catch {} is within the instatiation of the exception itself.

Creating an exception will fetch the entire call stack from the runtime and this is where the expense is.  If you are not creating an exception, this is only very slightly an increase of time.

In the example given in this question there aren't any exceptions, one wouldn't expect any slowdown from creating them - they aren't created.  Instead, what is here is a try {} finally {} to handle resource deallocation within the finally block.

So to answer the question, no, there is no real runtime expense within a try {} finally {} structure that doesn't use exceptions (it isn't unheard of, as seen). What is possibly expensive is the maintenance time when one reads the code and sees this not typical code style and the coder has to get their mind around that something else happens in this method after the return before returning to the previous call.

As has been mentioned, maintenance is an argument for both ways of doing this.  For the record, after consideration, my preference would be the finally approach.

Consider the maintenance time of teaching someone a new language structure.  Seeing try {} finally {} isn't something that one often sees in Java code and thus can be confusing to people.  There is a degree of maintenance time for learning a bit more advanced structures in Java than what people are familiar with seeing.

The finally {} block always runs.  And this is why you should use it.  Consider also the maintenance time of debugging the non-finally approach when someone forgets to include a logout at the proper time, or calls it at the improper time, or forgets to return / exit after calling it so that it is called twice.  There are so many possible bugs with this that the use of try {} finally {} makes impossible to have.

When weighing these two costs, it is expensive in maintenance time not to use the try {} finally {} approach. While people can dicker about how many fractional milliseconds or additional jvm instructions the try {} finally {} block is compared to the other version, one must also consider the hours spent in debugging the less than ideal way of addressing resource deallocation.

Write maintainable code first, and preferably in a way that will prevent bugs from being written later.

Title: Is try-finally expensive

Body:
In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.

Cleaning the resource before every return statement

```<code>void func()
{
    login();

    bool ret = dosomething();
    if(ret == false)
    {
        logout();
        return;
    }

    ret = dosomethingelse();
    if(ret == false)
    {
        logout();
        return;
    }

    dootherstuff();

    logout();
}
</code>```

Cleaning the resource in a finally block

```<code>void func()
{
    login();

    try
    {
        bool ret = dosomething();
        if(ret == false)
            return;

        ret = dosomethingelse();
        if(ret == false)
            return;

        dootherstuff();

    }
    finally
    {
        logout();
    }
}
</code>```

I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the finally way of doing this - but I was wondering if it will cause any performance hit in a big project.


问:
Where should I place my interface?
I have an interface to communicate with a DB (actually it is not a database, but this is to give a concrete example):

```<code>interface DbInterface{
    Result sendQuery(Query q);
}
</code>```

And I am trying to improve reusability by separating specific components into individual projects:

App1, an application that requires access to a database

App2, an application that requires access to a database

DB1, a concrete implementation of DbInterface (let's say SQL)

DB2, a concrete implementation of DbInterface (let's say using some NoSql database)

How do you typically design such an architecture and where should DbInterface be located?

in one of the applications? but that means all other three component depend on that project to access the interface - does not sound right

in one of the DB implementations? same - does not sound right.

in both DB implementations? code duplication.

in a separate project, which would only contain that interface? seems abusive to include a dependency for one interface only.

For reference, this is Java + maven, but the issue is fairly generic I suppose.

答:
I would personally go with the separate project. Pretty much every project I have worked on has had some kind of 'common' project/library that all others reference.

While it probably is overkill just for a single interface, it seems likely that there might similar cases in the future, and when that happens you already have a dedicated place to put them.

I don't know the ins and outs of your applications, but are there no helper classes etc that might be of benefit to both projects that could also go in a common project?

Title: Where should I place my interface?


答:
The interfaces are what you use to define a contract between the Applications and the implementation. That contract is usually managed by a middle project referred to as the API or SDK.

The application uses interfaces from the SDK, and the DB1 project implements those interfaces, but it's the SDK project that defines those interfaces.

Title: Where should I place my interface?

Body:
I have an interface to communicate with a DB (actually it is not a database, but this is to give a concrete example):

```<code>interface DbInterface{
    Result sendQuery(Query q);
}
</code>```

And I am trying to improve reusability by separating specific components into individual projects:

App1, an application that requires access to a database

App2, an application that requires access to a database

DB1, a concrete implementation of DbInterface (let's say SQL)

DB2, a concrete implementation of DbInterface (let's say using some NoSql database)

How do you typically design such an architecture and where should DbInterface be located?

in one of the applications? but that means all other three component depend on that project to access the interface - does not sound right

in one of the DB implementations? same - does not sound right.

in both DB implementations? code duplication.

in a separate project, which would only contain that interface? seems abusive to include a dependency for one interface only.

For reference, this is Java + maven, but the issue is fairly generic I suppose.


问:
Coding Style for Visually Impaired Programmer
I am visually impaired.  With glasses I see well enough to drive, but at the font size I'm comfortable working at I can only see about 15 lines of 100 characters at a time.  This has affected my coding style.

One thing I do is write shorter functions.  My code tends to get good reviews because these short functions with good names make the higher level functions very readable, but in high performance situations some folks make comments about how much space I'm taking up on the stack by passing variables down several layers for processing.

A second thing I do is divide classes up between files to make shorter files.  This reduces the scrolling distance to get to relevant functions and depending on organization may allow me to put the files up on different monitors to look at them together.

Both of these practices make for more documentable units that most coding styles require I document, which further aggravates the issue by extending the length of my file and the distance between related functions.

I'm currently using Visual Studio, which allows code folding at the function and comment block level (which I use frequently) but does not fold at the bracket level like Notepad++ does.  The editor that offers better code folding doesn't have all the intellisense features of VS.  I could use regions in VS, but this looks very cluttered if used every 10 lines.  Folding is occasionally helpful to get completed code out of view while I'm working on a different feature of the code.

Can anyone recommend better coding practices to help with limited visibility of the code?

答: You mention missing Notepad++'s bracket folding. You can add this behavior to Visual Studio with an extension. The C# outline extension is an example. It's free and does the job. There's no need to mess with regions inside a function or control block.</p>


问:
Creating an entity relationship in REST: May I create the parent by posting to a child id?
We are currently designing a REST API to access classical customer data.
One of the elements in the API are the assets of an user. The assets are added under a given service.  The backend API will only add an asset to an user under a given service. So, there's no User--Asset relation, but a  User--[Service]--Asset relationship.

Our URI's will look like this:

```<code>/users/{id}/assets/{id}/services/{id}
</code>```

Uses of the API will know the asset id and the service id to create a new entry.
What we are struggling with is the creation of this relation.

One straightforward way would be to post the whole relation to /users/{id}/assets/

```<code>POST /users/{id}/assets
{asset:${id}, service:{id}, attribute1:"{var}", attribute2:"{var}"}
</code>```

but then we are not actually creating an asset as the URI might indicate, but an asset-service relation.

As an alternative, we are considering POST'ing to the URI addressing the relation, like this:

```<code>POST /users/{id}/assets/{id}/service/{id}
{attribute1:"{var}", attribute2:"{var}"}
</code>```

But in this case, the resource path /users/{id}/assets/{id} will not exist before the POST and will be created as a side-effect.

Is POST'ing to a resource path that does not exist yet allowed at all?

Thanks for your thoughts,

Gerard.

答:
There are multiple points here:
First:
You should not put the id when create new resource as this id could be already exist, or may be the system using specific technique to generate the id and you are forcing it to use yours, and for the propose of that the id have to be created by the system the location header attribute have to be set in case of creation resource, to get the feed back with the generated id.

Second:
Your JSON is not correct, you have to deal with service as another object inside asset object also as in resource URI service"s" you have to deal with it as array.

```<code>POST /users/{id}/assets
{asset:${id}, service:{id}, attribute1:"{var}", attribute2:"{var}"}
</code>```

has to be:

```<code>POST /users/{id}/assets
{services:[{ attribute1:"var", attribute2:"var"}]}
</code>```

If you are going to use this way

Third:
I do not prefer to use this way for design propose, if this case failed how could you know it is failed while creating asset or service,

Body:
There are multiple points here:
First:
You should not put the id when create new resource as this id could be already exist, or may be the system using specific technique to generate the id and you are forcing it to use yours, and for the propose of that the id have to be created by the system the location header attribute have to be set in case of creation resource, to get the feed back with the generated id.

Second:
Your JSON is not correct, you have to deal with service as another object inside asset object also as in resource URI service"s" you have to deal with it as array.

POST /users/{id}/assets
{asset:${id}, service:{id}, attribute1:"{var}", attribute2:"{var}"}

has to be:

POST /users/{id}/assets
{services:[{ attribute1:"var", attribute2:"var"}]}

If you are going to use this way

Third:
I do not prefer to use this way for design propose, if this case failed how could you know it is failed while creating asset or service,


问:
Why use a database instead of just saving your data to disk?
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?

答:
TLDR

It sounds like you made an essentially valid, short term data-store technical decision for your application - you chose to write a custom data store management tool.

You're sitting on a continuum, with options to move in either direction.

In the long term, you'll likely (almost, but not 100% certainly) find yourself running into trouble, and may be better off to change to using existing data store solutions. There are specific, very common, predictable, performance problems you will be forced to deal with, and you're better off using existing tools instead of rolling your own.

It sounds like you've written a (small) custom-purpose database, built into and directly used by your application. I assume you're relying on an OS and file system to manage the actual disk writing and reading, and treating the combination as a data-store.

When to do what you did

You're sitting at a sweet-spot for data storage. An OS and file system data store is incredibly convenient, accessible, and cross-platform portable. The combination has been around for so long, that you're certain to be supported, and have your application run, on almost any standard deployment configuration.

It's also an easy combination to write code for - the API is fairly straight-forward and basic, and it takes relatively few lines of code to get it working.

Generally, it's ideal to do what you've done when:

Prototyping new ideas

Building applications which are highly unlikely to need to scale, performance wise

Constrained by unusual circumstances, such as lack of resources for installing a database

Alternatives

You're on a continuum of options, and there are two 'directions' you can go from here, what I think of as 'down' and 'up':

Down

This is the least likely option to apply, but it's here for completeness sake:

You can, if you want, go down, that is, bypass the OS and filesystem altogether and really write and read directly from disk. This choice is usually relevant only in cases where extreme efficiency is required - think, for example, of a minimal/tiny MP3 player device, without enough RAM for a fully functional OS, or of something like the Wayback Machine, which requires incredibly efficient mass data write operations (most data stores trade off slower writes for faster reads, since that's the overwhelmingly more common use case for almost all applications).

Up

There are several sub-categories here - these aren't exactly exclusive, though. Some tools span both, providing some functionality in each, some can completely switch from working in one mode to working in the other, and some can be layered on top of each other, providing different functionality to different parts of your application.

More powerful data stores

You may find yourself needing to store higher and higher volumes of data, while still relying on your own application for managing the data manipulation complexity. A whole range of key-value stores are available to you, with varying extents of support for related functions. NoSQL tools fall into this category, as well as others.

This is the obvious path to scale up on when the following describe your application:

It is unusually heavy read reliant

You're OK with trading off higher performance for lower (short term) consistency guarantees (many offer "eventual consistency").

Is "directly" managing most of the data manipulation and lack of consistency (in practice, you'll probably end up using a third party tool at first, though eventually you'll bring this into your application or into a custom written intermediate layer).

You're looking to massively scale the amount of data you're storing and/or your ability to search through it, with "relatively simple" data manipulation requirements.

There is some wiggle room here - you can force better read consistency, for slower reads. Various tools and options provide data manipulation apis, indexing and other options, which may be more or less suited for easily writing your specific application. So if the above points almost completely describe your application, you might be "close enough" to work with a more powerful data store solution.

Well-known examples: CouchDB, MongoDB, Redis, cloud storage solutions like Microsoft's Azure, Google App Data Store and Amazon's ECE.

More complex data manipulation engines

The "SQL" family of data storage application, as well as a range of others, are better described as data manipulation tools, than pure storage engines. They provide a wide range of additional functionality, beyond storage of data, and often beyond what's available in the key-value store side of things. You'll want to take this path when:

You absolutely have to have read consistency, even if it means you'll take a performance hit.

You're looking to efficiently perform highly complex data manipulation - think of very complex JOIN and UPDATE operations, data cubes and slicing, etc...

You're OK with trading off rigidity for performance (think forced, fixed data storage formats, such as tables, which cannot easily and/or efficiently be altered).

You have the resources to deal with an often times more complex set of tools and interfaces.

This is the more "traditional" way of thinking of a database or data store, and has been around for much longer - so there is a lot that's available here, and there's often a lot of complexity to deal with. It's possible, though it takes some expertise and knowledge, and build simple solutions/avoid much of the complexity - you most likely will end up using third-party tools and libraries to manage most of it for you, though.

Well known examples are MySQL, SQL Server, Oracle's Database, and DB2.

Outsource the work

There are several, modern, third-party tools and libraries, which interpose themselves between your data storage tools and your application, to help you manage the complexity.

They attempt to initially take away most or all of the work that goes into managing and manipulating data stores, and, ideally, allow you to make a smooth transition into complexity only when and if it is required. This is an active area of entrepreneurship and research, with a few recent results that are immediately accessible and useable.

Well-known examples are MVC tools (Django, Yii), Ruby on Rails, and Datomic. It is hard to be fair here as there are literally dozens of tools and libraries which act as wrappers around the APIs of various data stores.

PS: if you prefer videos to text, you might want to watch some of Rich Hickey's database related videos; he does a good job of elucidating most of the thinking that goes into choosing, designing and using a data store.


问:
Storing a drawn graph information in database for web application
Well while developing a web application that allow users to draw graphs (flow charts, ER diagram , UML, .... etc) the information of drawn items and their relation to each other and position on canvas is expressed as JSON object

The question is:

1- is saving such graph in database as raw (json object text) is enough (in one field of a table)
2- or is it always required to break down the json object into logical pieces and store them into a well built database structure!

option 1- other than making devilopers life easier it will eleminate the need of recreating json object from small bits and pieces of information when the user open a graph he have built and saved long time ago

option 2- will have fine grain details in proper structure but will cost kind of heavy processing while opening a saved graph from Database

which way is correct way to go ?

答:
is it always required to break down the json object into logical pieces and store them into a well built database structure

Well, I don't know who tells you what is required and what not, but in most typical use cases I know of it won't make sense. A flow chart, an ER diagram etc. is some kind of graphical document where it seldom makes sense to

edit the document concurrently with more than one user on it (I have seen some trials in the past, but never one that worked well)

query for things like "get me all graphs with a line starting at point x1,x2".

However, what makes sense is to store some meta-data in standard table fields associated with your JSON string. For example, the diagram title, the author, time of creation, type of diagram, category tags, a short description, geographic information, a version number and so on. Think about what kind of search queries you really expect, those kind of data you should model explicitly.


答:
Splitting a user's drawing up into nodes and edges (and all their associated attributes) and storing them in tables would give you the advantage of being able to query a drawing.

The question is: do you really need that functionality? Or could you get away with just storing some metadata with the text representation of the graph?

Consider that there will be a lot more work involved in getting a drawing out of the database if it has many nodes, compared to extracting one large text field.

Title: Storing a drawn graph information in database for web application

Body:
Well while developing a web application that allow users to draw graphs (flow charts, ER diagram , UML, .... etc) the information of drawn items and their relation to each other and position on canvas is expressed as JSON object

The question is:

1- is saving such graph in database as raw (json object text) is enough (in one field of a table)
2- or is it always required to break down the json object into logical pieces and store them into a well built database structure!

option 1- other than making devilopers life easier it will eleminate the need of recreating json object from small bits and pieces of information when the user open a graph he have built and saved long time ago

option 2- will have fine grain details in proper structure but will cost kind of heavy processing while opening a saved graph from Database

which way is correct way to go ?


答:
A separate project would be best in this scenario. Though now it will contain just a single interface, it may grow. Normally this type of project is called something like "API". There is no reason that a project such as this cannot contain some logic (for example, if you wanted to provide a facade on disparate API interfaces), but it should not be implementation specific.

Most applications should only have to rely on this API project as you should be coding to interfaces anyway. Only projects which tie in some sort of specific implementation will actually have to know about the API implementations. In modern applications that extensively use DI, the implementation is usually just a runtime concern.

Examples abound in the Java realm. JPA and Apache Commons Logging (or any other logging API) are a couple that you have probably already worked with.

As far as your comment "seems abusive to include a dependency for one interface only". I can see how this feels a bit awkward the first time you encounter it, but I would argue that it is more abusive to include dependencies you don't need in a project as you would be doing if you had to include the implementation to get only the interface.

Title: Where should I place my interface?


问:
Storing graphs with json and db
I have a Rails 4 app having to do with graphs. These graphs need to be stored and I'm not sure of the best way to do it. Firstly, the app has a SQLite db in development and PostgreSQL in production. I would love to have graphs in JSON, but that can be achieved in several ways. Also, these graphs are going to be manipulated using some interface. I was thinking a graphical solution and a raw one in JSON.

I have some alternatives to implementation:

Store the graph JSON files directly in the db. (how?)

Store the graphs in db with tables (graph, edges, vertex) (probably not...)

Store the graphs in db with tables and build a parser to manipulate the in JSON format.

What is your recommendations?

答: It looks like you're talking about mathematical graphs, not charts per se.  I read a pretty nice presentation on using Postgres for storing graph-type data.  It covers several different data modeling options that can work with an RDBMS.  You might also want to consider using a specialized graph database (neo4j) for graph-related needs.</p>

Title: Storing graphs with json and db


问:
Is this a violation of the Liskov Substitution Principle?
Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain:

public class Task
{
     public Status Status { get; set; }

     public virtual void Close()
     {
         Status = Status.Closed;
     }
}

public class ProjectTask : Task
{
     public override void Close()
     {
          if (Status == Status.Started)
              throw new Exception("Cannot close a started Project Task");

          base.Close();
     }
}
```

Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation of the Liskov substitution principle?

答:
An LSP violation requires three parties.  The Type T, the Subtype S, and the program P that uses T but is given an instance of S.

Your question has provided T (Task) and S (ProjectTask), but not P.  So your question is incomplete and the answer is qualified:  If there exists a P that does not expect an exception then, for that P, you have an LSP violation.  If every P expects an exception then there is no LSP violation.

However, you do have a SRP violation.  The fact that the state of a task can be changed, and the policy that certain tasks in certain states should not be changed to other states, are two very different responsibilities.

Responsibility 1: Represent a task.

Responsibility 2: Implement the policies that change the state of tasks.

These two responsibilities change for different reasons and therefore ought to be in separate classes.  Tasks should handle the fact of being a task, and the data associated with a task.  TaskStatePolicy should handle the way tasks transition from state to state in a given application.


问:
When using your own API (Dog Fooding). How do you avoid giving away the secret key?
I read this article on soundcloud's api:

http://backstage.soundcloud.com/2011/08/soundcloud-mobile-proxies/

It talks about consuming your own API.
What I don't understand is how they avoid giving away the secret key. If you normally give the secret key to a developer who is going to use it in his API how do you give the secret key to yourself and avoid divulging it without transferring it over the wire?
I am assuming there is a new secret key for each user. Otherwise each user would have the same secret key and a new public key and I am not sure if that would work.

I am not talking about developers. I am talking about users like us are to Stack Exchange (actual users of the app itself). My app will be consuming it's own API. Each user that signs up for the app (I assume) would get a private and public key. Each call to the API would need to (potentially) authenticate with a public and private key. If in this situation the user is a regular user of the app, how does one get the private key to the user. Or is this not the best way to do this?

答: I would guess the same way as https works now: you don't publicise the private key, only the public key. Only your internal code will confirm the public key against the private key.</p>


问:
Automating database deployment using a CMS
My team are developing Umbraco websites and looking to improve the automation of our database deployment.  Currently we have automated builds and deployments of our source code using Kiln and Team City, but cannot work out how to handle the database deployment.

The challenge is applying changes made in the development environment, while keeping new database content that has been added in the live environment via the CMS.  Currently our changes are deployed using courier manually, but we aim to convert this into a '1 click deployment' which is what we desire for running our automated tests and ease of deployment.  How can we automate this without wiping new content added in the CMS?

答:
In general what you are looking to do is called database migrations. The simplest possible solution is to just have a series of SQL DDL scripts that are run in order to create and modify the schema to get to a certain point. Because it is SQL you could also use it to insert structural data if required by the CMS.

I'm not familiar with umbraco personally, but I've used a number of other CMS products and most of them have some sort of migration system in place that satisfies your requirements. I would first look to leverage that system -- it probably has all you'd need and will mesh well with the database changes required by CMS upgrades or plugins.

If you need to roll your own on top of or in parallel to that system, I would probably use RoundhouseE as it should be able to work astride whatever umbraco is doing. It can be run from a command line and we certainly use it very effectively every day from TeamCity up to and including live deployments on running web applications.


问:
Static methods or static functions?
I was just reading https://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function and all of a sudden, the thing came to my mind was the static methods. </p>

<p>As static methods are no way associated with an object how can it be called as static methods (almost all developers do)? Is my understanding about the methods/functions is correct? </p>

答: I agree with you. I usually call them procedures, since they are neither methods (associated with a dynamic object), nor functions (side-effect free).</p>

Title: Static methods or static functions?


答:
The cryptographically secure way is for each client to generate its own secret key, and to generate a key signing request to the the server.  The server then reviews the incoming requests and decides if it wishes to sign that key.

The API service then works like this.  It requires client authentication using certificates.  If the certificate is signed by the servers authority, and is not on the blocked list then the connection is accepted, otherwise the connection is rejected.

The end result, as long as you only sign a signing request when you are sure of its source then you can be sure that the client is who it claims to be (or its private key has been compromised)  By maintaining a blocked list on the server, validly signed certificates can still be failed to be allowed access.

Title: When using your own API (Dog Fooding). How do you avoid giving away the secret key?

Body:
I read this article on soundcloud's api:

http://backstage.soundcloud.com/2011/08/soundcloud-mobile-proxies/

It talks about consuming your own API.
What I don't understand is how they avoid giving away the secret key. If you normally give the secret key to a developer who is going to use it in his API how do you give the secret key to yourself and avoid divulging it without transferring it over the wire?
I am assuming there is a new secret key for each user. Otherwise each user would have the same secret key and a new public key and I am not sure if that would work.

I am not talking about developers. I am talking about users like us are to Stack Exchange (actual users of the app itself). My app will be consuming it's own API. Each user that signs up for the app (I assume) would get a private and public key. Each call to the API would need to (potentially) authenticate with a public and private key. If in this situation the user is a regular user of the app, how does one get the private key to the user. Or is this not the best way to do this?


答:
Here is a different line of thought:

```<code>POST /relationships
{ relationship:${id}, asset:{id}, service:{id}, user:{id}, data:"some data" }
</code>```

This way you are defing the relationships as a three way link between asset, service and user and not implying any hierarchical relationship

You can then retrieve a specific relationship by:

```<code>GET /relationships?id="2144321"
</code>```

or search for a subset of relationships by:

```<code>GET /relationships?user="43434"
</code>```

or

```<code>GET /relationships?asset="12433"
</code>```

The original way is not wrong, but this approach may give you more flexibility over who it gets used.

Title: Creating an entity relationship in REST: May I create the parent by posting to a child id?

Body:
We are currently designing a REST API to access classical customer data.
One of the elements in the API are the assets of an user. The assets are added under a given service.  The backend API will only add an asset to an user under a given service. So, there's no User--Asset relation, but a  User--[Service]--Asset relationship.

Our URI's will look like this:

```<code>/users/{id}/assets/{id}/services/{id}
</code>```

Uses of the API will know the asset id and the service id to create a new entry.
What we are struggling with is the creation of this relation.

One straightforward way would be to post the whole relation to /users/{id}/assets/

```<code>POST /users/{id}/assets
{asset:${id}, service:{id}, attribute1:"{var}", attribute2:"{var}"}
</code>```

but then we are not actually creating an asset as the URI might indicate, but an asset-service relation.

As an alternative, we are considering POST'ing to the URI addressing the relation, like this:

```<code>POST /users/{id}/assets/{id}/service/{id}
{attribute1:"{var}", attribute2:"{var}"}
</code>```

But in this case, the resource path /users/{id}/assets/{id} will not exist before the POST and will be created as a side-effect.

Is POST'ing to a resource path that does not exist yet allowed at all?

Thanks for your thoughts,

Gerard.

Body:
Here is a different line of thought:

POST /relationships
{ relationship:${id}, asset:{id}, service:{id}, user:{id}, data:"some data" }

This way you are defing the relationships as a three way link between asset, service and user and not implying any hierarchical relationship

You can then retrieve a specific relationship by:

GET /relationships?id="2144321"

or search for a subset of relationships by:

GET /relationships?user="43434"

or

GET /relationships?asset="12433"

The original way is not wrong, but this approach may give you more flexibility over who it gets used.


问:
Unit Test passing conditions as well as failing conditions?
Should unit tests test passing all cases as well as all failing cases?

For example, imagine I have a test Widget_CannotActiveWidgetIfStateIsCancelled.

And let's say there are 25 possible states.

Can I get away with testing only that I cannot activate my widget when State == Cancelled, or do I have to also test that I CAN activate it in each of the other 24 states?

答:
While you certainly should test that your unit fails correctly in addition to passing correctly, there is no reason to write a test that does not add to your confidence in the code.

However, if your "unit" has twenty-five possible states, it may be better to think of each state as a distinct unit, and construct your tests appropriately.  (don't forget that your tests can share code where appropriate.)


问:
How can designing for inheritance cause extra cost?
So I wanted to inherit from a sealed class in csharp and got burned. There is just no way to unseal it unless you have access to the source.

Then it got me thinking "why sealed even exists?". 4 months ago. I couldn't figure it out, despite reading many things about it, such as:

Jon Skeet's wishes "classes were sealed by default in .NET."

Prefer composition over inheritance?

"You should not seal all classes (...)"

How do you mock a Sealed class?

I've tried to digest all that since then, but it's just too much for me. Eventually, yesterday I tried it again. I've scanned over all of them again, plus few more:

Why should a class be anything other than "abstract" or "final/sealed"?

In over 15 years programming, first time I've heard of SOLID, out of an answer from a question already linked and I obviously didn't read it all 4 months ago

Finally, after lots of pondering, I decided to heavily edit the original question based on the new title.

The old question were too broad and subjective. It was basically asking:

In the old title: One good reason to use sealed

In the body: How to properly modify a sealed class? Forget about inheritance? Use composition?

But now, understanding (which I didn't yesterday) that all sealed does is preventing inheritance, and we can and should indeed use composition over inheritance, I realized what I needed was practical examples.

I guess my question here is (and in fact have always been) exactly what Mr.Mindor suggested me in a chat: How can designing for inheritance cause extra cost?

答:
sealed is used to indicate that the writer of the class hasn't designed it to be inherited.  Nothing less, nothing more.

Properly designing an interface is already difficult enough for lots of programmers. Properly designing a class which can be potentially inherited adds difficulty and lines of code. More lines of code written means more code to maintain. To avoid this increasing difficulty, sealed can show that the class was never intended to be inherited, and in this context, sealing a class is a perfectly valid solution to a problem.

Imagine the case where the class CustomBoeing787 is derived from Airliner. This CustomBoeing787 overrides some protected methods from Airliner, but not all of them. If the developer has enough time and it's worth it, he can unit test the class to ensure that everything works as expected, even in a context when non-overriden methods are called (for example protected setters which change the state of the object). If the same developer (1) doesn't have time, (2) doesn't want to spend additional hundreds or thousands of dollars of his boss/customer, or (3) doesn't want to write additional code he doesn't need right now (YAGNI), then he can:

either release the code in the wild as is, considering that it's the concern of the programmers who will maintain this project later to care about potential bugs,

or mark the class as sealed to explicitly show to the future programmers that this class is not intended to be inherited, and that unsealing it and using it as a parent should be done at your own risk.

Is it a good idea to seal as many classes as possible, or as few as possible? From my experience, there is no definitive answer. Some developers tend to use sealed too much; others don't care about how the class would be inherited and the problem it can cause. Given such usage, the problem is similar to the one which consists in determining whether programmers should use two or four spaces for indentation: there is no right answer.


答:
I think this question doesn't have objective answer and that it all depends on your perspective.

One side, some people want everything "open" and burden of ensuring everything is working correctly is on person who extends the class. This is why classes are open to inheritance by default. And why Java methods are all virtual by default.

On the other side, some want everything to be closed by default and to provide options to open it. In this case, it is base class's author who needs to ensure everything he makes "open" is safe to use in any way imaginable. This is why in C# all methods are non-virtual by default and need to be declared virtual to be overriden. It is also for those people, that need to be way to circumvent "open" defaults. Like making class sealed/final, because they see someone deriving from the class a big problem to their own class's design.

Body:
So I wanted to inherit from a sealed class in csharp and got burned. There is just no way to unseal it unless you have access to the source.

Then it got me thinking "why sealed even exists?". 4 months ago. I couldn't figure it out, despite reading many things about it, such as:

Jon Skeet's wishes "classes were sealed by default in .NET."

Prefer composition over inheritance?

"You should not seal all classes (...)"

How do you mock a Sealed class?

I've tried to digest all that since then, but it's just too much for me. Eventually, yesterday I tried it again. I've scanned over all of them again, plus few more:

Why should a class be anything other than "abstract" or "final/sealed"?

In over 15 years programming, first time I've heard of SOLID, out of an answer from a question already linked and I obviously didn't read it all 4 months ago

Finally, after lots of pondering, I decided to heavily edit the original question based on the new title.

The old question were too broad and subjective. It was basically asking:

In the old title: One good reason to use sealed

In the body: How to properly modify a sealed class? Forget about inheritance? Use composition?

But now, understanding (which I didn't yesterday) that all sealed does is preventing inheritance, and we can and should indeed use composition over inheritance, I realized what I needed was practical examples.

I guess my question here is (and in fact have always been) exactly what Mr.Mindor suggested me in a chat: How can designing for inheritance cause extra cost?


答:
As evident by my question, I'm no expert here. But I see no reason for sealed to even exist.

It seems to be made to help code architects to design an interface. If you want to write a class that will go out in the wild and many people will inherit from it, modifying anything in that class can break it for too many people. So we can seal it and nobody can inherit. "Problem solved".

Well, looks like "covering a spot and uncovering another". And it's not even solving a problem - it's just eliminating a tool: inheritance. As any tool, it has many usages and inheriting from a unstable class is a risk you take. Whoever took that risk should know better.

Maybe there could be a keyword stable, so people would know it's safer to inherit from it.

Title: How can designing for inheritance cause extra cost?


答:
the problem with sealed in C# is that its rather final. In 7 years of C# commercial development, the only place I have seen it used is on Microsoft .NET classes where I feel I had a legitimate reason to extend a framework class to implement adjusted behaviour, and because the class was sealed, I could not.

It is impossible to write a class thinking about every possible way it could be used, and deciding that none of them are legitimate.  Likewise if framework security is dependent on the class not being inherited, then you have a security design flaw.

So, in conclusion, I'm firmly of the view that sealed serves no useful purpose, and nothing I have read here so far has changed that view.

I can see there have so far been three arguments that justify sealed placed so far.

Argument 1 is that it eliminates a source of bugs when people
inherit from classes and then have increased access to the internals
of that class without really understanding the internals properly.

Argument 2 is that if you extend a microsoft class and then microsoft
implement a bug fix in that class but your extention relied on that bug
then your code is now broken, microsoft gets the blame, and sealed prevents
that

Argument 3 is that as the developer of the class, its my choice whether to allow you to extend it, as part of my design of the class.

Argument 1 seems to be an argument that you the end programmer don't know how to use my code. That may be the case, but if you still allow me to access the objects interface it still holds true that I am using your object, and making calls to it without understanding how to use it, and so can make just as much damage that way. This is a feeble justification of the need for sealed.

I understand where the factual base for arg 2 comes from. In particular when microsoft put additional OS checks on win32 api calls to identify malformed calls, which have improved the general stability of the Windows XP compared to Windows NT, but at the short term cost that many apps were broken when Windows XP was released. Microsoft resolved this by putting 'rules' in for these checks to say, ignore when app X breaks this rule, its a known bug

Argument 2 is a poor argument because sealed at best makes next to no difference to this because if there is a bug in the .NET library you have no choice but to find a work around, and when the microsoft fix comes out, its quite likely means that your work around which depends on the broken behaviour is now broken. Whether you worked around this by using inheritance or by some other additional wrapper code, when the code is fixed, your work around will be broken.

Argument 3 is the only argument that has any substance to justify its self. But it is still weak. It just goes against the grain of code reuse.


问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
Three questions you put and I think short-form answers could aid the longer arguments given so far.

How relevant is this test to development in industry?

Depends on the industry.

Anywhere where code speed or code space is an issue, it is entirely relevant to the industry involved.  Often you need to know how long a routine will take, or how much memory (on/offline) it will require.

How often do you reeeally use it?

Depends on the industry.

If performance and scaling is of little concern to the job at hand, then rarely, only when there is a serious performance shortfall.  If you are an engineer for a highly used critical system, every day probably.

How necessary is it to have a honed mindset for the problem?

Entirely necessary.

You may have to use it everyday, or only in dire circumstances; but sometimes it will be needed.  Preferably during design before an issue arrives, than desperately profiling a choking system.


答:
It depends on the implementation, but most likely you'd write two tests: one for Cancelled and one for any of the other 24 states.

Why is this enough? Because all 24 other states form an equivalence class. Testing these two cases should cover all branches in the implementation of Activate.

Also note that this approach is what you would end up with if you used Test driven development. The other approach - writing 25 test cases - is a form of black box testing that generally leads to multiple tests testing the same thing.

Title: Unit Test passing conditions as well as failing conditions?

Body:
Should unit tests test passing all cases as well as all failing cases?

For example, imagine I have a test Widget_CannotActiveWidgetIfStateIsCancelled.

And let's say there are 25 possible states.

Can I get away with testing only that I cannot activate my widget when State == Cancelled, or do I have to also test that I CAN activate it in each of the other 24 states?


问:
Design of interface for finding one of something or a list
I am developing a telephony call model and thinking about how best to design the interface.

One basic idea is that a call has a unique call identifier.  I have a list of calls and finding a specific call is easy by callid.

Each call has zero or more parties.  A party has a device identifier (eg extension 201) and a state.  Eg my extension 201 can be alerting or established or whatever.

I have a class to represent a call which has functions to find a party on the call,  I have the following findxxx functions:

```<code>party* find_party_by_dn(const std::string& dn) const;
int find_parties_by_dn(const std::string& dn, std::list<party*> pties) const;
</code>```

find_party_by_dn seems ok, but it has a problem in that a call may have 2 parties with the same device identifier. Eg a user may put a call on hold and make a new consult call to another device.  In which case the call has a party with dn 201 in state hold and another party with dn 201 and state dialling for example.

So if I use function find_party_by_dn only the first party in the list with this dn will be returned.

So I thought ah, why not return (well via reference) a list of parties with a given dn.  Hence the second function.  Does that seem like a useful interface?  Could it be improved?

I also have these functions:

```<code>party* find_party_by_state(const std::string& dn, pstate state) const;
party* find_party_by_states(const std::string& dn, int states) const;
</code>```

In which case the caller needs to specify either a specific state or a number of states - eg state1 | state2

I am looking for feedback on this interface.  Does it seem logical?  Could it be improved to make it more user friendly or robust?

答:
With your find_party_by_dn/find_parties_by_dn functions, you will see that in practice only one of them will get used (I predict it will be find_party_by_dn as that is the easier one). The reason for this is because the user of the function will not know if and when the search for a DN would return multiple results.
In your particular case, I highly doubt the validity of the possibility that one DN represents multiple parties in a call, but if you have something like that, it is best to have just a single function that returns a list of the found items. If there is only one, then the list will simply be one long.

With your find_party_by_state/find_party_by_states, there is less confusion about which function to use, but having two functions makes the interface more complicated than needed. You could just as easily offer one function find_party_by_state that accepts a bit-wise or combination of one or more states. There is no need to have a separate function for the special case of searching on one state.


答:
When a class is sealed it allows code using that type to know exactly what they're dealing with.

Now in C# string is sealed, you can't inherit from it, but let's assume for a second that that wasn't the case.  If you did, then someone could write a class like this:

```<code>public class EvilString// : String
{
    public override string ToString()
    {
        throw new Exception("I'm mean");
    }
    public override bool Equals(object obj)
    {
        return false;
    }
    public override int GetHashCode()
    {
        return 0;
    }
}
</code>```

This would now be a string class that is violating all sorts of properties that the designers of string knew to be true.  They knew that the Equals method would be transitive, this is not.  Heck, this equals method isn't even symmetric, as a string could be equal to it but it wouldn't be equal to that string.  I'm sure there are all sorts of programmers who have written code under the assumption that the ToString method of string won't throw an exception for non-null values.  You will now be able to violate that assumption.

There are any number of other classes we could do this for, and all sorts of other assumptions that we could violate.  If you remove the language feature for sealed then the language designers now need to start accounting for things like this in all of their library code.  They need to perform all sorts of checks to ensure that extended types of the types they wish to use will be written "properly", which can be a very expensive thing to do (both in dev time, as well as at run time).  By being able to seal a class they can ensure that this isn't possible, and that any assertions they make about the implementation details of their own types can't be violated, except for those types that are intentionally designed to be extended.  For those types designed to be extended you'll find the language code needs to be much more defensive about how it deals with them.

Body:
When a class is sealed it allows code using that type to know exactly what they're dealing with.

Now in C# string is sealed, you can't inherit from it, but let's assume for a second that that wasn't the case.  If you did, then someone could write a class like this:

public class EvilString// : String
{
    public override string ToString()
    {
        throw new Exception("I'm mean");
    }
    public override bool Equals(object obj)
    {
        return false;
    }
    public override int GetHashCode()
    {
        return 0;
    }
}

This would now be a string class that is violating all sorts of properties that the designers of string knew to be true.  They knew that the Equals method would be transitive, this is not.  Heck, this equals method isn't even symmetric, as a string could be equal to it but it wouldn't be equal to that string.  I'm sure there are all sorts of programmers who have written code under the assumption that the ToString method of string won't throw an exception for non-null values.  You will now be able to violate that assumption.

There are any number of other classes we could do this for, and all sorts of other assumptions that we could violate.  If you remove the language feature for sealed then the language designers now need to start accounting for things like this in all of their library code.  They need to perform all sorts of checks to ensure that extended types of the types they wish to use will be written "properly", which can be a very expensive thing to do (both in dev time, as well as at run time).  By being able to seal a class they can ensure that this isn't possible, and that any assertions they make about the implementation details of their own types can't be violated, except for those types that are intentionally designed to be extended.  For those types designed to be extended you'll find the language code needs to be much more defensive about how it deals with them.


答:
Is there any good reason to use sealed?

Enh? Not often. I will only used sealed when I have an immutable type (or some other limitation) that really really needs to remain immutable and I cannot trust inheritors to furfill that requirement without introducing subtle, catastropic bugs into the system.

Suppose there is a good reason to use sealed and we should use it as default for everything, what we do with inheritance?

We use inheritence for those things that are not default. Even if composition is favored over inheritence (and it is), that doesn't mean inheritence is to be discarded. It means that inheritence has some intrinsic problems that it introduces into design and code maintainability and composition does much of the same thing with (in general) less problems. And it means that even if composition is favored that inheritence is good for certain subsets of problems.

I don't mean to be too mean but if you've just now heard of SOLID and unit testing, maybe you should get out from underneith your rock and actually write code. Things aren't clear cut, and rarely will "always do X" or "never use Y" or "Z is best" be the right way (like it seems you gravitate towards based on your question's views). As you write code you can see cases where sealed could be good and cases where it causes you grief - just like any other tradeoff.


问:
Class Design for special business rules
I'm developing an application that allows people to place custom manufacturing orders. However, while most require similar paperwork, some of them have custom paperwork that only they require. My current class design has a Manufacturer class, of which of one of the member variables is an array of RequiredSubmission objects.

However, there are two issues that I am somewhat concerned about.

First, some manufacturers are willing to accept either a standard form or their own custom form. I'm thinking of storing this in the RequiredSubmission object, with an array of alternate forms that are a valid substitute. I'm not sure that this is ideal, however.

The major issue, however, is that some manufacturers have deadline cycles. For example, forms A, B and C have to be delivered by January 1, while payment must be rendered by January 10. If you miss those, you'll have to wait until the next cycle. I'm not exactly sure how I can get this to work with my existing classes—how can I say "this set of dates all belong to the same cycle, with date A for form A, date B for form B, etc."

I would greatly appreciate any insights on how to best design these classes.

答:
Part of the challenge you're having is because you aren't separating out the responsibilities appropriately.  You also need to separate out the logical, or data construct, of the order from the physical order that will be placed.

Let's start with the orders.  You should have a class MyMfgOrder that contains all the information you would need for generating a custom order.  This will correlate pretty closely to the standard form you mentioned, but may have extensions due to custom form requirements.  This is your logical order form construct.

Next, you'll need classes for each vendor's custom order form, such as VendorAMfgOrder.  To simplify your life, have it take your MyMfgOrder as part of the constructor and then have the custom form build itself based upon your order form class.  This would be one of several physical order form constructs.

I'll segue over to the Vendor class at this point.  The Vendor has some specific properties, such as if they require a custom form and any dates associated with delivery.  Locating this properties goes back to responsibility - the Vendor "owns" their need for a custom form as well as their delivery requirements.

When you go to work with an instance of the logical MyMfgOrder, you will end up selecting a Vendor at some point before placing the order.  Once a Vendor is selected, you'll need to populate any delivery deadline information for that vendor as well as their accepted type of order form.

In my sample below, I didn't really specify how to track the particular forms to use because you didn't specify a particular language.  And there are a number of ways to track what the final form needs to look like through enums, generics, arrays, or what not.  The point is that MyMfgOrder represents a logical view of the order that will need to be transformed into a physical view of the order that is submitted to the actual vendor.  It's appropriate for the logical view to understand what it's physical form should be.

Breaking things out that way allows you to keep track of the immediate concerns with some vendors and their particular delivery cycles.  This also structures you so you can compare multiple vendors' requirements against each other for the same custom order.  By using a logical order separate from the physical, you buy that ability to compare.  You can also use the logical construct to generate repeating custom orders that are independent of any particular vendor since the physical order form is derived from the logical form.

Here's some sample code to layout the classes as I discussed.

```<code>public class MyMfgOrder
{
     Vendor PrefVendor;
     string StockNumber;
     int Quantity;
     float QuotedCost;
     DateTime QuotedDelivery;
     DateTime MustDeliverBy;
     DateTime MustPayBy;
     object FormToSubmit;
}

public class VendorAMfgOrder
{
    VendorAMfgOrder(MyMfgOrder myOrder) { }
}

public class Vendor
{
    bool RequiresCustForm;
    object CustFormType;
    DateTime DeliveryDeadlineCycle;
    DateTime PaymentDeadlineCycle;
}
</code>```

Title: Class Design for special business rules

Body:
Part of the challenge you're having is because you aren't separating out the responsibilities appropriately.  You also need to separate out the logical, or data construct, of the order from the physical order that will be placed.

Let's start with the orders.  You should have a class MyMfgOrder that contains all the information you would need for generating a custom order.  This will correlate pretty closely to the standard form you mentioned, but may have extensions due to custom form requirements.  This is your logical order form construct.

Next, you'll need classes for each vendor's custom order form, such as VendorAMfgOrder.  To simplify your life, have it take your MyMfgOrder as part of the constructor and then have the custom form build itself based upon your order form class.  This would be one of several physical order form constructs.

I'll segue over to the Vendor class at this point.  The Vendor has some specific properties, such as if they require a custom form and any dates associated with delivery.  Locating this properties goes back to responsibility - the Vendor "owns" their need for a custom form as well as their delivery requirements.

When you go to work with an instance of the logical MyMfgOrder, you will end up selecting a Vendor at some point before placing the order.  Once a Vendor is selected, you'll need to populate any delivery deadline information for that vendor as well as their accepted type of order form.

In my sample below, I didn't really specify how to track the particular forms to use because you didn't specify a particular language.  And there are a number of ways to track what the final form needs to look like through enums, generics, arrays, or what not.  The point is that MyMfgOrder represents a logical view of the order that will need to be transformed into a physical view of the order that is submitted to the actual vendor.  It's appropriate for the logical view to understand what it's physical form should be.

Breaking things out that way allows you to keep track of the immediate concerns with some vendors and their particular delivery cycles.  This also structures you so you can compare multiple vendors' requirements against each other for the same custom order.  By using a logical order separate from the physical, you buy that ability to compare.  You can also use the logical construct to generate repeating custom orders that are independent of any particular vendor since the physical order form is derived from the logical form.

Here's some sample code to layout the classes as I discussed.

public class MyMfgOrder
{
     Vendor PrefVendor;
     string StockNumber;
     int Quantity;
     float QuotedCost;
     DateTime QuotedDelivery;
     DateTime MustDeliverBy;
     DateTime MustPayBy;
     object FormToSubmit;
}

public class VendorAMfgOrder
{
    VendorAMfgOrder(MyMfgOrder myOrder) { }
}

public class Vendor
{
    bool RequiresCustForm;
    object CustFormType;
    DateTime DeliveryDeadlineCycle;
    DateTime PaymentDeadlineCycle;
}


问:
Is renewal of MIT license needed on github at the beginning of each year?
I am using the MIT LICENSE in all of my github projects. The second line says 2013 at the top. For having the copyright to hold in future(i.e. after 2013) does it need to be changed each year or is it good as it is? Do I add to it, modify it or leave it as it is?</p>

```<code>The MIT License (MIT)

Copyright (c) 2013 Aseem Bansal <aseembansal@ymail.com>

//Rest of the MIT LICENSE
</code>```

答:
License != Copyright

Short, not fully accurate, answer: No, you do not need to renew the license each year.

Longer, more accurate, answer:  No, licenses do not need to be renewed, so the basis of your question is incorrect.

Licenses address how others may use your code.  Once you specify a license for the code, you don't need to modify the license ever again.  In some cases, you may choose to re-license the code under a different license.  If you did that, then you are simply providing differing terms that someone else needs to follow to use your code.

Copyright refers to ownership of the code.  The copyright is what legally defines the code as "yours."  Copyright on code is renewable if you make material changes to the code.  And if you do make a material change, then yes, you should update the copyright date.  IANAL, but simply updating the copyright date without a material change does not actually move the date of ownership / copyright.  But given how long copyrights last, it's kind of a moot point.


问:
Using a flag in in-memory-repository to indicate update to entity
I'm about to write a lot of test for my application. While some of the tests check whether everything works if the user enters the right data, most of them deal with wrong/missing data. In these cases nothing should be updated and an exception should be thrown.

At the moment, this leads to a lot of duplicated code, because every test has to make sure that not only the exception is thrown but that no data in my (mocked in-memory) database is changed.

My first idea was to move these tests into a function and to call this function in every test. Pro: I still can use very explicit tests. Contra: I have to remember changing the function and adding more tests whenever I add more functionality to the checked function.

But I could as well add a property to my mocked in-memory-repository that indicates whether an entity was updated. Pro: I'll never have to worry about a forgotten check. Contra: The check is quite vague - When it fails I'll only knew that something was changed. In order to find the error I'll have to debug step by step through the function.

What is the better approach? Maybe there's an even better third solution?

答:
Are you sure that you're actually talking about a Mock and not a Stub (or a fake)?

Mocks don't have "flags" - you configure them to behave however you want them to, so if there was in fact a flag then that flag would also be mocked and therefore be meaningless to the test.

You use Mocks to verify interactions with a dependent component. In the case of a repository, you should only have to verify that a particular update method was not called, which in all mocking frameworks I know of is just one line of code.

The fact that repositories are so trivially easy to mock and verify is one of the main (only?) reasons to use them in the first place.

If the verification line is long e.g. due to a method having a lot of parameters or something then sure, refactor it to a common test method. If it really starts to get messy then you can create a fluent test builder that abstracts the most common steps and verifications, so that your tests look like a sort of DSL. But when I say "messy" I'm talking about literally hundreds of these tests; less than a dozen and it's definitely not worth the bother or the added complexity.

Keep in mind that unit tests are specifications and are supposed to tell you in very simple terms how the code actually behaves. While it's important to keep test code clean and periodically refactor, it's also important not to overdo it and end up creating test code that's just as complex as the SUT.

I don't know exactly what your specs are, but if they include something like "should not update entity X with ID Y" then that's exactly what the test code should look like as well, and a Mock is the most appropriate tool. On the other hand, if your specs talk about the end state of the data (e.g. "entity X should still status Y and not Z") then a Mock isn't a very good choice, you'll want to use an actual fake database - usually an in-memory database - and have your tests actually look up those entities and check them. In either case, I don't see what property you could add to the repository itself that would really help.


答:
This is not so difficult to comprehend. sealed was created SPECIFICALLY for Microsoft in order to make their lives easier, save tons of money and help their reputation. Since it is a language feature everyone else can use it also but YOU will probably never ever need to use sealed.

Most people are complaining about not being able to extend a class and if they do then they say well everyone knows it is the developers responsibility to make it work correctly. That is correct, EXCEPT those same people have no clue on the history of Windows and one of the problems sealed is trying to solve.

Let's suppose a developer extended a .Net core class (because sealed did not exist) and got it to work perfectly. Yay, for the developer. The developer delivers the product to the customer. The developer's app works great. The customer is happy. Life is good.

Now Microsoft releases a new operating system, which includes fixing bugs in this particular .Net core class.  The customer wants to keep up with the times and chooses to install the new operating system. All of a sudden, the application that the customer likes so much no longer works, because it did not take into account the bugs that were fixed in the .Net core class.

Who gets the blame?

Those familiar with Microsoft's history know that Microsoft's new OS will get the blame and not the application software that misused windows libraries. So it then becomes incumbent on Microsoft to fix the problem instead of the application company who created the problem. This is one of the reasons why Windows code became bloated. From what I've read, the Windows operating system code is littered with specific if-then checks for if a specific application and version is running and if so then do some special processing to allow the program to function. That's a lot of money spent by Microsoft to fix another company's incompetence.

Using sealed doesn't completely eliminate the above scenario, but it does help.


答:
Normally you would let your test names do the talking. What I mean is, if you can have these two tests:

When_state_is_canceled_then_cannot_activate_widget

When_state_is_not_canceled_then_can_activate_widget

And if both of the above tests are an accurate description of the behaviour, then no, you don't need to write tests for all 25 possible states, because there are only 2 states that actually matter, "canceled" and "not canceled". In the actual implementation of "not canceled", of course, you will have to pick some specific other state. From a pure code coverage standpoint, you'll get full coverage this way.

On the other hand, you should also try to predict how the SUT might change. Maybe today there are 24 states that all behave exactly the same way, but three weeks from now the rules may change in a very subtle way that either breaks or isn't covered by the test you wrote today.

One thing I've sometimes done is, in the "negative" test, have a loop that enumerates all possible states, excludes the ones that don't apply, and verifies them each in sequence. That's the lazy way, but it's a little less flaky than just picking a state at random.

But most of the time I prefer to write Context/Specification style tests, which just remove this ambiguity altogether by making each possible state a separate test class, and yes, that does mean testing all 25 states, although there are numerous ways you could use inheritance or composition in the tests to reduce code bloat while still maintaining the tests for all states.

There's no rule, you can "get away with" whatever you want, it's just a question of how thorough you want your tests to be, which is probably going to depend on such things as how many other developers are working on the code, what the cost of each defect is to the business, how often you release, etc. If you're trying to do TDD or BDD, use context/specification for each state. If you're just trying to get half-decent code coverage, then just test one "on" and one "off" state.


问:
Is a NoSQL database suitable for me?
I'm developing a WPF application whose core functionality involves creating a large object graph (often tens of thousands of entities) which the user can modify certain parts of, then save to a database. A graph can also be subsequently retrieved, modified and saved again. It's feasible that a user can create dozens of these graphs per day.

The app also provides the user with different ways to search the entities in the database (predominantly text searches on various fields), presenting the search results to the user and allowing the user to select one, which will result in the relevant entity graph being retrieved in full and presented for the user to view and modify as above.

Currently I'm using Entity Framework and SQL Express, but I'm uneasy about certain aspects of the architecture and design, and the client isn't keen on having to install SS. I've only recently come across the concept of NoSql databases, and sounds like they might be a good fit for what I'm doing, but I have a couple of questions.

First, I'm assuming performance wouldn't be any worse than EF when reading or writing one of these object graphs?

What about my app's search functionality? Will a NoSql db support this sort of thing, and what would the performance be like, bearing in mind the size and quantity of "documents" that I'm likely to have.

What about lookup (reference) data? Would I duplicate such data in each NoSQL document, or would I keep it all in a single NoSql document and store their IDs in the main documents?

Finally, any recommendations for a product? MongoDb and RavenDb seem to be the main OSS contenders for Windows.

答:
There is no such thing as noSQL. There is only a whole bunch of new database technologies with completely different philosophies and use-cases, and all they have in common are things they also have in common with SQL databases. That means when you plan a project and are unsure about the database technology, you need to evaluate each noSQL database individually.

When your data is based on large graphs, it sounds like a perfect use-case for a graph-oriented database like Neo4j.

Document-oriented databases like MongoDB are generally not a good fit for graphs, because they don't support connections between documents very well.

Title: Is a NoSQL database suitable for me?


问:
Best way to choose random element from weighted list
I want to create a simple game. Every so often, a power up should appear. Right now the different kinds of power ups are stored in an array.

However, not every power up should appear equally often: For instance, a score multiplier should appear much more often than an extra life.

What is the best/fastest way to pick an element at random from a list where some of the elements should be picked more often than others?

答:
Just a simple weighting system would work. Create a 100 index array, and things that happen 1 time in 100, appear in only 1 spot, while things that appear 1 time in 5 appear in 20 spots. Generate a random number between 1 and 100, and the event that happens is the one in that index of the array.

This is how they compute loot tables for RPGs. You can also generate a list of events that store their probability range internally, so instead of having a large array filled with redundant entries, you can have a smaller two dimensional array that stores an event, along with the numeric range in which it occurs.


答:
If by "best" you actually mean "fastest", then by far the fastest way (although not nearly the most efficient way) is to choose a multiplier that makes all of the weights integers, at least to whatever precision you care about, and then store that many copies of each in one large array.

For example, if you assign "score multiplier" a weight of 80%, and "extra life" a weight of 20%, then create a 5-element array with 4 references to the "score multiplier" object/variable and 1 reference to the "extra life". Then generate a random number between 1 and 5 and pick from the corresponding index. Distribution doesn't matter.

In practice, unless you've got tons of memory and a very slow CPU, this is a waste of memory. It's far, far simpler and more efficient to write a bunch of if statements comparing a random number to a low/high bound, and if the number of possible items isn't that big (let's say less than 10?) then it shouldn't be that hard to maintain.

If you've got hundreds or thousands of possible items/power-ups/whatever then this is no longer a very maintainable solution. In that case the best option I know of is to maintain a sorted list of tuples with the key as the minimum weight; you don't need to store the maximum as that's implied by the next item. For example [ [0, scoreMultiplier], [80, extraLife], [95, invincibility] ]. Then you can do a binary search on this list to find the appropriate item corresponding to a random number in O(log N) time.

Title: Best way to choose random element from weighted list

Body:
I want to create a simple game. Every so often, a power up should appear. Right now the different kinds of power ups are stored in an array.

However, not every power up should appear equally often: For instance, a score multiplier should appear much more often than an extra life.

What is the best/fastest way to pick an element at random from a list where some of the elements should be picked more often than others?


答: I only use sealed keyword on classes that contain only static methods.


答:
This is simply the wrong question to be asking.

"NoSQL" doesn't refer to a specific database, it refers to an entire superclass of databases including document databases, distributed key-value stores, graph databases, and object databases.

Speed is generally the least important factor in making decisions about data storage, no matter what some people might tell you. A SQL Server table with a billion rows can do key and index lookups at about the same rate as a MongoDB collection with a billion documents or a db4o database with a billion objects. The exception of course is if you can do sharding, in which case you'll want a product that supports it, but if your users are antsy about installing SQL Express then rest assured they'll run for the hills if you tell them to grab 200 old desktop PCs and shard an HBase instance across all of them.

Do you need full-text search? The industry standard for that is Lucene. It's not really a database by itself, it's something that's bolted onto other databases and sometimes packaged more nicely by tools like Elastic Search or Solr. Most SQL databases also have some form of full-text search; it's generally slower and inferior to Lucene. Some NoSQL databases have full-text search (RavenDB, for example, actually uses Lucene) but most have either no support or are in a very primitive stage.

Do you need to store very deep hierarchies of objects all at once, hierarchies that always have a single well-known aggregate root? If so, then document databases like MongoDB or CouchDB would work well for you. But if you ever need to change your hierarchy, or find that you need transactional consistency (and not the "eventual" kind) then you're in for a world of hurt.

Does your data consistent of multiple related entities that each have independent lifetimes? If so, then a relational database like SQL Server or mysql is by far the best choice. Relational databases allow you to defer or ignore many difficult modeling decisions and in general you'll only have to model once, as compared with document databases or key-value stores where you may have to frequently change your model or maintain multiple parallel models in order to solve various different use cases. If you want to keep things simple, you definitely want to stick with SQL.

If you need an embedded database, consider SQLite. It's not as powerful as SQL Server but it's fast and easy to use and easy to deploy, and you'll find the syntax to be mostly familiar.

Incidentally, if you're really that worried about speed (and by the sounds of it, your needs are way too small to justify any such worry) then you might want to look at the benchmark done some time ago by the ServiceStack guys. Entity Framework comes in dead last, and by a pretty wide margin too. NHibernate is probably the best choice when you balance out the mutually exclusive requirements of compatibility and performance. Although personally I prefer not to use any ORM at all, and you definitely won't be able to use a pretty little ORM if you switch to NoSQL. Good luck learning the eleventy billion Redis commands if you've got no prior experience with the product.

Title: Is a NoSQL database suitable for me?

Body:
I'm developing a WPF application whose core functionality involves creating a large object graph (often tens of thousands of entities) which the user can modify certain parts of, then save to a database. A graph can also be subsequently retrieved, modified and saved again. It's feasible that a user can create dozens of these graphs per day.

The app also provides the user with different ways to search the entities in the database (predominantly text searches on various fields), presenting the search results to the user and allowing the user to select one, which will result in the relevant entity graph being retrieved in full and presented for the user to view and modify as above.

Currently I'm using Entity Framework and SQL Express, but I'm uneasy about certain aspects of the architecture and design, and the client isn't keen on having to install SS. I've only recently come across the concept of NoSql databases, and sounds like they might be a good fit for what I'm doing, but I have a couple of questions.

First, I'm assuming performance wouldn't be any worse than EF when reading or writing one of these object graphs?

What about my app's search functionality? Will a NoSql db support this sort of thing, and what would the performance be like, bearing in mind the size and quantity of "documents" that I'm likely to have.

What about lookup (reference) data? Would I duplicate such data in each NoSQL document, or would I keep it all in a single NoSql document and store their IDs in the main documents?

Finally, any recommendations for a product? MongoDb and RavenDb seem to be the main OSS contenders for Windows.


答:
Design First, Shop Later

You should design your system before you start shopping for specific implementations. Specifically:

Design your data structures based on how you plan to search and retrieve data.

Evaluate the efficiency and performance of comparable solutions that implement your design requirements.

There's really no substitute for benchmarking various solutions on a representative corpus of data, and no one else but your organization can evaluate the various trade-offs for your particular project.

Graphing? Then Graph!

Choosing the right data structure to represent your data is essential to preventing premature aging in programmers. Selecting the right models for searching, storing, and retrieving your data is very context-dependent, but it's the essential first step in designing a new system.

I've never found a practical need for it myself, but if your fundamental data structure is a graph, why not take a look at a graphing database solution? Neo4j seems like it's designed to address your problem domain, but I can't shill for it since I've never used it.

Even if Neo4j is not the right solution for your project, you should certainly investigate all the options that make it easy to work with your core data structures. A key goal is to reduce the number of transformations you need when converting data between input and output formats, so keep the focus on how you will use the solution.

Title: Is a NoSQL database suitable for me?


答:
That year in your code is part of a copyright notice. It indicates the effective creation date of your software, which affects the time window of your copyright. It is not, strictly speaking, related to the license (although the MIT license happens to include a provision that the copyright notice must be preserved in all copies of the software).

You should update the year if and only if you made changes to your software in that year. Updating your copyright notice to include a year in which you made no copyrightable changes would be a misrepresentation of your copyright term. In the United States, this is currently only relevant if you are a corporation, but may be relevant to non-corporate authors in other countries. (In the U.S., copyright terms for natural individuals are currently a function of how long you live, not when you create a work.)

The FSF has some helpful guidance on including a correctly-dated copyright notice in your software (intended for use with the GPL, but applicable to all software):

The copyright notice should include the year in which you finished preparing the release (so if you finished it in 1998 but didn't post it until 1999, use 1998). You should add the proper year for each release; for example, “Copyright 1998, 1999 Terry Jones” if some versions were finished in 1998 and some were finished in 1999. If several people helped write the code, use all their names.

For software with several releases over multiple years, it's okay to use a range (“2008-2010”) instead of listing individual years (“2008, 2009, 2010”) if and only if every year in the range, inclusive, really is a “copyrightable” year that would be listed individually; and you make an explicit statement in your documentation about this usage.

It is not clear from the FSF guidance whether uploading incomplete, in-progress work to a public repository counts as "finishing a release". My guess is yes, if the work was deliberately made available for public download, but I'm not a lawyer.

So, to summarize:

if you made changes that year, do include the year in a comma-separated list in your copyright notice.

if did not make copyrightable changes that year, do not include that year in your copyright notice.

Title: Is renewal of MIT license needed on github at the beginning of each year?

Body:
I am using the MIT LICENSE in all of my github projects. The second line says 2013 at the top. For having the copyright to hold in future(i.e. after 2013) does it need to be changed each year or is it good as it is? Do I add to it, modify it or leave it as it is?</p>

```<code>The MIT License (MIT)

Copyright (c) 2013 Aseem Bansal <aseembansal@ymail.com>

//Rest of the MIT LICENSE
</code>```