答:
I'd only like to point out the following:  This use of super

```<code>super.aBarMethod();
</code>```

is actually harmful because it disables dynamic dispatch for this call.  This means that if a sub-class overrides aBarMethod, you will still call the one defined in Bar, not the overriding one.  Probably not what you'd expect.  What was supposedly meant to be a stylistic nuance turned out to change the semantics of the code!  It might work as expected now, but as you start refactoring later (moving method definitions around) your code will start to break in subtle ways.  If you think that overriding the method would be a bad idea anyway, you should forbid it by declaring aBarMethod as final.1  In any case, the call inside Foo should read

```<code>this.aBarMethod();
</code>```

(Where the this is disposable but I like it and you seem to like it too.)  Since Foo inherits aBarMethod, it actually belongs to this so referring to it via this makes perfect sense.  Only if you really mean to disable dynamic dispatch, refer to it via super.  A common use case (though of questionable style) is if you want to extend a method that wasn't designed for this.  For example, you could add to the toString method of your super class.

```<code>class Base {
    @Override
    public String toString() {
        return "base";
    }
}

class Derived extends Base {
    @Override
    public String toString() {
        return super.toString() + " & derived";
    }
}
</code>```

Calling toString on a Derived object will yield "base & derived".

Personally, I always feel dirty if using the super keyword in my Java code.  The only exception is calling the super-class constructor via super(…), which is fine.  Sometimes, if overriding the toString, equals, hashCode and clone methods inherited from java.lang.Object using super (as in the example above) can hardly be avoided.

1 Doing so is generally a good idea.  Some people – including me – prefer to make any method either abstract, final or empty.  There is also a Checkstyle rule to enforce this.  If you are concerned about good and consistent coding style, you'll probably like Checkstyle if you are not already using it.

Body:
I'd only like to point out the following:  This use of super

super.aBarMethod();

is actually harmful because it disables dynamic dispatch for this call.  This means that if a sub-class overrides aBarMethod, you will still call the one defined in Bar, not the overriding one.  Probably not what you'd expect.  What was supposedly meant to be a stylistic nuance turned out to change the semantics of the code!  It might work as expected now, but as you start refactoring later (moving method definitions around) your code will start to break in subtle ways.  If you think that overriding the method would be a bad idea anyway, you should forbid it by declaring aBarMethod as final.1  In any case, the call inside Foo should read

this.aBarMethod();

(Where the this is disposable but I like it and you seem to like it too.)  Since Foo inherits aBarMethod, it actually belongs to this so referring to it via this makes perfect sense.  Only if you really mean to disable dynamic dispatch, refer to it via super.  A common use case (though of questionable style) is if you want to extend a method that wasn't designed for this.  For example, you could add to the toString method of your super class.

class Base {
    @Override
    public String toString() {
        return "base";
    }
}

class Derived extends Base {
    @Override
    public String toString() {
        return super.toString() + " & derived";
    }
}

Calling toString on a Derived object will yield "base & derived".

Personally, I always feel dirty if using the super keyword in my Java code.  The only exception is calling the super-class constructor via super(…), which is fine.  Sometimes, if overriding the toString, equals, hashCode and clone methods inherited from java.lang.Object using super (as in the example above) can hardly be avoided.

1 Doing so is generally a good idea.  Some people – including me – prefer to make any method either abstract, final or empty.  There is also a Checkstyle rule to enforce this.  If you are concerned about good and consistent coding style, you'll probably like Checkstyle if you are not already using it.


问:
Notifications in Use-case Diagrams
I'm writing a use-case diagram in which an actor gets a notification. My question is similar to this one except that I'm not sure if my notification use-case is a crosscutting concern.

Suppose my system is an egg timer. The actor is a cook. The cook can set the interval after which the egg timer goes off. The cook also wants to hear the egg timer.

Is this the proper diagram? The cook doesn't perform the "Be Notified" action. However, if I only leave the "Set Alarm Time" use-case, it isn't specified that the egg timer should actually notify the cook.

Should I put the "Be Notified" use-case in a different type of diagram? Should I make another use-case diagram where the cook is the system and the egg timer is the actor?

答:
I don't think that "be notified" should be something that is even on a use case diagram. Each use case is a sequence of steps or actions. What appears on a use case diagram is just a summary of what the full use case is, since it doesn't capture all of the steps, preconditions and postconditions, minimal guarantees, triggers, or any of the other information that is typically associated with a use case.

In your specific use cases, the kinds of use cases that I'd expect would be to "set alarm time", "start timer", and "stop timer". The notification would be one result of the "start timer" use case. It's something that the system does as an output, not something that someone uses the system to accomplish.

I would recommend reading the Wikipedia article on use cases and Scott Ambler's Agile Modeling pages on Use Case Diagrams and Use Cases.

As an aside, in UML Distilled, Martin Fowler doesn't give much weight to use case diagrams, asserting that use cases are best captured in textual or tabular form. I tend to agree with this, since a use case table would capture more details. However, a diagram may provide a quick index of the use cases and their relationships to each other and to actors.

ContentLicense: CC BY-SA 3.0

Title: Notifications in Use-case Diagrams


问:
Is it actually possible (practically) to sell Open Source software?
Open source software can be used for commercial purposes. It is said that

You can even sell Open Source software.

How does this work?

If I sell my open-source product (copyleft or permissive), there is nothing to prevent the next guy from selling it as well. Because of this, it is not clear how money can be made directly from an open source product.

How can you have free-as-in-speech without also having free-as-in-beer? Examples?

Note: This question as well as this one ask about general ways to make money in Open Source. There are many ways to make money around and tangential to the software, upon which a business can be based, but what about selling the software itself?

答:
When you sell something -- anything -- you are trading something of value (the product, services or experience) for something of value (money). When you sell open source software, what you are typically selling isn't the software, but rather the services and experience that you've bundled with the software.

For example, you may have made an installer that takes the pain out of gathering dozens of dependencies. Or, you provide 24x7 support. Or, you provide consulting services along with the software.

You are correct, that the next guy can sell the same software. To make a viable business, you must provide something in addition to the software that the other guy can't.


问:
Is there an alternative to instanceof when filtering a Java stream by class?
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

答:
I hope I'm not missing anything obvious here (also as suggested by @Tristan Burnside's comment), but why can't SpecificItem.method() call also() first?

```<code>public class SpecificItem extends Item {
    ...
    public void method() {
        also();
        super.method();
    }
}
</code>```

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

A stream-y way I can think of, at the expense of maybe some performance impact( YMMV), is to collect()  via Collectors.groupingBy() on the class as the key, then pick what you want from the resulting Map. The values are stored as a List, so if you were expecting to do such a filtering on a Set and you hope to get a filtered Set out of it, then you will need an additional step to further put the values into a resulting Set as well.

Body:
I hope I'm not missing anything obvious here (also as suggested by @Tristan Burnside's comment), but why can't SpecificItem.method() call also() first?

public class SpecificItem extends Item {
    ...
    public void method() {
        also();
        super.method();
    }
}

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

A stream-y way I can think of, at the expense of maybe some performance impact( YMMV), is to collect()  via Collectors.groupingBy() on the class as the key, then pick what you want from the resulting Map. The values are stored as a List, so if you were expecting to do such a filtering on a Set and you hope to get a filtered Set out of it, then you will need an additional step to further put the values into a resulting Set as well.


答:
Modifying open source software.  Sometimes people need open source software to do something it doesn't already do and no one is willing to do that for free.  So a company might pay someone to do it for them.

For instance, a company might want to release some hardware running linux.  But their hardware requires new drivers.  So they pay someone (or maybe some company) to write the requisite drivers.  They typically pay a fairly large fee as this is a one-time sale as these drivers are then open source.  If you charge $100k, you only have to sell one and in this situation, it may be well worth it to the hardware manufacturer to pay $100k for that one driver.

Or in a related example: I create a router.  I use linux to power that router.  I then sell that router in Best Buy for $79.  In essence, I am selling linux as part of my package.  No one can really undercut me there because the OS is useless without the hardware I sell.

Title: Is it actually possible (practically) to sell Open Source software?

Body:
Open source software can be used for commercial purposes. It is said that

You can even sell Open Source software.

How does this work?

If I sell my open-source product (copyleft or permissive), there is nothing to prevent the next guy from selling it as well. Because of this, it is not clear how money can be made directly from an open source product.

How can you have free-as-in-speech without also having free-as-in-beer? Examples?

Note: This question as well as this one ask about general ways to make money in Open Source. There are many ways to make money around and tangential to the software, upon which a business can be based, but what about selling the software itself?


答:
You assume that the recipient wants to give away your software. It's possible that your customer has a vested business interest in not sharing the software. For example, if you sell an open-source industry-specific application to a business, that business might want to keep that application out of the hands of competitors in the same industry. (Of course, this is a bit of a degenerate case, since it doesn't actively demonstrate any of the benefits of open source software.)

Otherwise, yes, the market value of any freely-distributed software that you have written will rapidly approach zero. As soon as the software leaves your control into the wild (now assuming pro-sharing recipients), the software is no longer salable. Therefore, your open-source software holds the greatest potential for monetary value before you release it. This can utilized by at least two models:

The ransom model, where you advertise the existence of the software (or soon-to-be existence) but do not release it until you've collected enough money. This could be implemented easily on a crowdfunding site like Kickstarter.

The paid enhancement model, where customers pay you to prioritize development of specific features.

Otherwise, to make money, you'll need to sell something else, like support contracts or a legally-enforced guarantee that your software will work safely for a particular domain.


问:
Is it legal to include BSD licensed code within an MIT licensed project?
If this is possible, how do I go about putting this in the license file or in the source files where the BSD licensed code was used?</p>

答:
Exhibit A: BSD license text

Exhibit B: MIT license text

First off, you really ought to read both of those licenses.  Really, go on now, it shouldn't take more than a few minutes to read both.

What you should immediately notice is just how similar the two licenses are. Really, they are.  Basically, they both state "retain the copyright notice" and "retain the as-is / no warranty statement."

That's it.  That's really all there is to them.

So you asked:

Is it legal to include BSD licensed code within an MIT licensed project?

Well, why wouldn't it be legal?  You read the licenses, right?  There's nothing within either license restricting combining two projects together with those licenses.

To be more clear, yes, it's perfectly legal to combine Project A licensed with the MIT license along with Project B that is licensed with the BSD license.

You also asked:

If this is possible, how do I go about putting this in the license file or in the source files where the BSD licensed code was used?

The easiest way to do this is to keep each project in their own separate sub-folder within your overarching project that utilizes the two other projects.  From there, you can put a LICENSE.txt file in each sub-folder as appropriate.  Another bonus for using the sub-folder within the overarching project is that you can just copy things in verbatim from the original projects.  That makes it very clear what code is owned under what copyright and what license.

If, for whatever reason, you can't keep the projects isolated to their own sub-project folder, then you simply need to state that various portions are owned by different projects and licensed under X terms.

Copyright for portions of project Foo are held by [MIT original author, year] as part of project Bar and are provided under the MIT license.

  Copyright for additional portions of project Foo are held by [BSD original author, year] as part of project Baz and are provided under the BSD license.

  All other copyright for project Foo are held by [your name, year].

Note that the ordering of projects Bar and Baz is immaterial.

Also note how similar that is to my answer on your other question.

Also note that you don't really have to specify the license that each portion is provided under, but it certainly doesn't hurt.2

You need to have a section within your LICENSE.txt file that says Project Bar is provided under such-and-such license whereas Project Baz is provided under such-and-such license.2

Editorial note: The BSD and MIT licenses are called permissive licenses for a reason.  All they really say is A) "You can't exclusively claim this as your own" and B) "I'm not taking any liability for how you use the code I provided."

Once you understand the spirit behind the two licenses, it becomes much more clear on how to apply their terms.

1Note, we're using the 2-clause, not the 3-clause version of BSD as a) most everyone uses the 2-clause now and b) 3-clause just adds a bit more hassle with the "no endorsements" bit.

2This would appear to be a contradiction of statements, but it really isn't.  To be more clear - you don't have to specify the license when you identify the copyright ownership.  It's convenient, but not required.  Likewise, when you state the license for incorporated projects you don't have to state the copyright ownership at the same point.  It's just convenient to capture both aspects at the same time.


答:
There are several business models for Free Software (which I feel is a more interesting terminology thant Open Source), and you should also look into the FSF site and its what is free software page.

Notice also that even proprietary software is often non-profitable thru licensing. It is rumored that the development costs of SAP software is not paid by the pricy tag of the software licenses they are selling (and the same is probably true for Windows). The profit is even for them made around services.

However, free software has also a major benefit : the community working on it. Hence, it does usually happen that free software has good quality (often better than for proprietary software).

There are several books on Economics of Free Software (or Open Source). I found interesting The Success of Open Source by Steven Weber. An important notion is Externality

BTW, you generally don't sell profitably software (even proprietary ones). You sell something else, and you have to identify what that else is (it really depends on your case).

On the corporate side, many companies are spending many billions of dollars (or euros) on free software, many of them are paying developers to work on it (a vast majority of developers on FireFox, Linux Kernel, GCC are paid full time to work on free software development). And several companies are specialized on free software development and are making profit (usually thru "service", "support", etc...)

At last, I don't believe that it is easy to sell software with profit (a lot of proprietary software projects are failing!), and probably not easier than selling support or service on free software.


问:
What algorithm can I use to find the biggest subarray within a 2d array with only n different numbers?
Let's say I have a 2d array 100x100 in size, each cell in that array has a number from 1 to 50 randomly.

How do I find the biggest subarray in a rectangle size in that array that has only n different numbers?

Small example:

```<code>array: 1 2 3 3 3 2 2
       7 4 3 3 4 9 8
       1 2 3 3 3 4 2
       7 6 1 9 9 4 2
In this case the biggest sub rectangle with only 1 number allowed would be
       3 3
       3 3
With 2 numbers allowed it would be
       3 3 3
       3 3 4
       3 3 3
</code>```

Does something for this exist?

答:
I can think of one auxiliary technique that may be sometimes useful for a related question.

Note that this auxiliary technique doesn't solve the main question. One shouldn't use this technique if the goal is to solve a given puzzle where the solution is guaranteed to exist.

This auxiliary technique is used to prove the contrary: that given an M-by-N array, for any possible A-by-B subarrays, no fewer than C different labels will be found. This technique solves C when given A and B.

In other words, it tries to solve a lower-bound for C.

The utility in this technique is that one can return a negative result if someone makes an impossible query, or simply as a heuristic rule to be used within some other solving techniques.

Numbers A and B are given.

If one uses this technique as a heuristic, one can try subarray sizes that are square-shaped, such as (3, 3), (5, 5), (7, 7), etc.

if one uses this technique to check for a negative result for a given query, use the (A, B) from that query.

Convert each number into a length-N bitvector. (For example, N = 50 if at most 50 different numbers can occur in the whole array.)

Define an associative operator "☀" to be the bitwise-OR of these bitvectors.

Define a horizontal (row-wise) "blur" (convolution) using the associative operator as follows, which operates over a subarray of 1-by-B.

Output(row, column) = Input(row, column) ☀ Input(row, column + 1) ☀ Input(row, column + 2) ☀ ... ☀ Input(row, column + B - 1)

Note: when this filter is applied to the input array of size M-by-N, the result will have size M-by-(N-B+1).

Likewise, define a vertical (column-wise) "blur" (convolution), this time operating over a subarray of A-by-1.

Note: when the vertical filter is applied to an intermediate array of size M-by-(N-B+1), the result will have size (M-A+1)-by-(N-B+1).

Generate the "filtered" whole array as follows.

Let IntermediateArray = HorizontalBlur(InputArray)

Let FilteredArray = VerticalBlur(IntermediateArray)

Now, scan the FilteredArray to find the element (bitvector) that has the least number of bits set.

This number is the solution for C, for the given values of A and B.

As I cautioned above, this technique isn't a solution to the puzzle. It is a kind of performance optimization technique when one needs to solve the puzzle repeatedly, or on large arrays, or on some practical applications (not for personal entertainment, learning or programming competitions).

The technique is based on a bunch of image processing / 2D pattern recognition techniques such as Image morphological operation.


问:
Is it the standard accepted practice to install software using VBScript?
Consider the following requirements

Windows software which communicates with a web application using basic authentication

The software is an MSI package

The software requires a token to be placed in order to authenticate itself to the web application

The token is unique to every user, but the user is expected to install the software with the same token on several machines

The question is:

What is the best strategy to distribute the software from the web application with appropriate token in it ? (The user should not be asked to enter the token.)

The proposed solution is::

When the user clicks the download software button from the web application instead of giving then the software, we generate a VBScript file which contains the token and download location of the software package (MSI), and deliver it as a download. After that, when the user invokes the script, the following things will happen.

The software will be downloaded and the token is passed to the installer and a custom action inside the installer will get the token and configure the application accordingly

Will the Windows world accept the above solution? Do they feel it unnatural? Is there a better solution to the problem at hand?

答:
Downloadable scripts to be run - VBScript or Javascript - always sounds very fishy to me, especially since there are too many black sheep out there abusing such things to install malware. You don't want to train anyone using your program to trust, download, and use such scripts.

Unfortunately I can't think of any secure fire & forget solution to this that won't include possible security vulnerabilities (like someone unintentionally passing the token to a co-worker as part of the installer package).

Theoretically you could install a browser plugin to act as an authentication/communication bridge between the web application and the native program (similar to what EA does with their Battlelog plugin for the newer Battlefield games), but even that isn't something perfect.

As such I'd still strongly advice you to go the (a tiny bit) more intrusive way and asking the user for login details once the program is installed. Keep in mind that you might want some way to revoke tokens as well (even if it's just due to a stolen machine).


答:
There are two aspects involved in this question.

Packaging of your application

Distribution of user tokens

For the point 1, I recommend the ClickOnce deployment model. I have made assumption you have built a Microsoft .NET framework application. Even if otherwise, you could implement something similar to ClickOnce deployment in your technology platform. I intend to highlight more on the deployment model rather than the particular technology.

For the point 2, it could be addressed in two different ways -

Consider building a small application (something similar to your current VBScript code). However this application would be an executable like .exe. This application will be packaged along with the program which you intend to distribute. Let us call it as Product Activator. Its sole purpose would be to connect to a token-generating service and get one token for the current user. Assuming you have UI fields to collect user id from the user. This product activator could be part of your larger portfolio of applications which you distribute through the web.

As part of the application there could be a one time startup module / code which does the same activity as the product activator described above.

Let me focus on the token generating service. This element is present in both the options of the solution. The service is the piece of code which you have today to generate tokens for users. You should consider hosting it as a web service with limited discovery and access to avoid exposing your logic of generating the token.

In both the approaches, the user is not prompted for a token. However, user id might be an user input expected from the user. In both the approaches, like @Mario pointed out, the risk of educating the user to run an VBScript script is avoided. On top of it, the process of installing the application is now a task of registering the binaries of your application on the client machine. The logic of registering the user is a different perspective and is not open for the user to tweak around with as it would be if the user opened the VBScript file.

Title: Is it the standard accepted practice to install software using VBScript?

Body:
Consider the following requirements

Windows software which communicates with a web application using basic authentication

The software is an MSI package

The software requires a token to be placed in order to authenticate itself to the web application

The token is unique to every user, but the user is expected to install the software with the same token on several machines

The question is:

What is the best strategy to distribute the software from the web application with appropriate token in it ? (The user should not be asked to enter the token.)

The proposed solution is::

When the user clicks the download software button from the web application instead of giving then the software, we generate a VBScript file which contains the token and download location of the software package (MSI), and deliver it as a download. After that, when the user invokes the script, the following things will happen.

The software will be downloaded and the token is passed to the installer and a custom action inside the installer will get the token and configure the application accordingly

Will the Windows world accept the above solution? Do they feel it unnatural? Is there a better solution to the problem at hand?


答:
The other answers have already shown you how to make money off software without making money directly off the sale, however, there is still one reason why someone would straight up buy your software: some people or organizations like to have someone to sue, and it is easier to sue someone you have given money to (and thus have a contract of sale with) than someone who gave you something for free.

Of course, this means that technically speaking, they are not really paying you for your software, but rather for the ease of suing you, but it's probably the closest you can get.


问:
Can I have more than one describe per test spec?
I started to writing tests a few time ago and faced a non-mature question: can I have more than one describe per unit test file?

If so, in what circumstances this will happen?

Because so far, I'm describing a/an module/object like this:

tests/User-spec.js

```<code>describe ('A user', function () {
  it ('should add a "to do" into the list', function () {
    var user = new User;
    var list = new List({ name: 'Home' });

    user.add('Buying some groceries.').to(list);

    expect(list.items[0]).to.be('Buying some groceries.');
  });
});
</code>```

In other words, each file of my tests describes an object—there's no space for another describe.

I know there are a few good/bad practices about tests, and technically I can add more than one describe per spec—I just do not know wether this is the "best" way to go or even good.

Can you describe to me some scenarios where more than one describe could be within the same spec file? Or even wether my describe is or isn't wrong?

答:
I'm going to assume you're using the Jasmine testing framework since that's the only one I know of with describe() and it().

Yes, it's totally fine. The only thing that describe() does is designate a piece of text to be the "header" that describes a group of tests. The Jasmine intro page even says

The describe function is for grouping related specs

and Jasmine supports nested describes() too.

So the real question here is what is the most intuitive and readable way to group your tests. If it's a small class with not very much to test, one header is probably fine.

```<code>Class A
    Foo
    Bar
    Foo with non-ASCII characters
    Bar with MAX_INT
</code>```

If this is it, using more than one describe() is probably overkill.

After a few years of feature creep it may warrant a bit more.

```<code>Class A

    Basic Calls
        Foo
        Bar
        Baz
        Shazam

    Edge Cases/Regression Tests
        Foo with non-ASCII characters
        Bar with MAX_INT
        Shazam after Foo(Bar(42*-6))
        Baz before m_count is initialized

    Compatibility Shims/Polyfills
        Foo without generators
        Bar without getPrototypeOf()
</code>```

Do whatever makes the output more readable for your team.

Body:
I'm going to assume you're using the Jasmine testing framework since that's the only one I know of with describe() and it().

Yes, it's totally fine. The only thing that describe() does is designate a piece of text to be the "header" that describes a group of tests. The Jasmine intro page even says

The describe function is for grouping related specs

and Jasmine supports nested describes() too.

So the real question here is what is the most intuitive and readable way to group your tests. If it's a small class with not very much to test, one header is probably fine.

Class A
    Foo
    Bar
    Foo with non-ASCII characters
    Bar with MAX_INT

If this is it, using more than one describe() is probably overkill.

After a few years of feature creep it may warrant a bit more.

Class A

    Basic Calls
        Foo
        Bar
        Baz
        Shazam

    Edge Cases/Regression Tests
        Foo with non-ASCII characters
        Bar with MAX_INT
        Shazam after Foo(Bar(42*-6))
        Baz before m_count is initialized

    Compatibility Shims/Polyfills
        Foo without generators
        Bar without getPrototypeOf()

Do whatever makes the output more readable for your team.


答:
The standard solution which you have surely seen from other software vendors is to

let the user download and install the software, maybe with or without the registration, but let the software itself lead the user through the registration process afterwards.

Through that process, after the user is authentificated, the token is downloaded in form of a license file. If you want to let the user install the software on a second machine without a new authentification, allow the license file to be copied to the other machine. You wrote "user should not be asked to enter the token" - but actually, where is the difference for the user if he has to copy a VBS file to a second machine, or if he has to copy a license file?

Note that this does not prevent your user to give away the software together with the license file to another person, but since your own approach does not prevent that either, I guess you are not after a solution for that problem.

A different approach is not to use VBS, but generate a personalized downloader in form of an exe file (it is not too hard to provide a C or C++ source code which is personalized by modifiying just one small code file and then compiled on-the-fly by your web server). At least this prohibits modifications by the average user with a simple text editor like Notepad, which would be possible for a VBS downloader. And you do not have to teach your users how to run a VB script.

And if you really want to provide personalized installer packages, there is a third option. It is possible to generate or regenerate your MSI packages on-the-fly, so you can replace the personal token file inside an MSI package for each individual download. This SO post contains some information about this, and here is shown how a single file can be replaced inside a compressed MSI. That may be the smoothest solution for your case.


问:
When and how to apply application settings in .Net
I know that I can access application settings in .Net using Properties.Settings.Default.aSetting.

What is the best way to apply them:

To directly read them in the function which relies on
them. This approach eliminates some class properties or function parameters
which otherwise are used to pass the settings; the function may loose its flexibility to be used with other parameters than the settings but it has this advantage that they are applied as the user change them in the settings form.

Define and set corresponding member variables and parameters in classes or functions. Then how can I apply them after user changed a setting while the dependent object has been already initialized?

答:
I strongly advise against using Properties.Settings.Default.aSetting all over the place.

If you do

You bind yourself hand and foot to whatever storage mechanism you hook up (by default the app.config and user.config files).

You turn every function that uses Properties.Settings.Default into something that can only be tested through slow integration tests instead of quick, fast executing and more focused unit tests.

You will have a hard time to arrange your tests properly as it turns out that is a lot of work, even somewhat of a hack, to get Properties.Settings.Default to work with test content instead of the actual application and user configuration files. See How do I select a .Net application configuration file from a command line parameter? and
Change default app.config at runtime for more information on this.

Defining and setting member variables and parameters in classes or functions isn't very nice either as you would indeed have to come up with some sort of observer/observed (publisher/subscriber) mechanism to be able to respond to changes in settings' values.

There is a third option.

Isolate all your code from the use of Properties.Settings.Default.aSetting by wrapping it in a class you define yourself. Give that class the settings your software needs as properties. The getter and setter for each of these properties simply reads from and writes to the corresponding member in Properties.Settings.Default.aSetting.

If you ensure that the rest of your code gets a reference to an instance of your wrapper class when it needs to retrieve or store a setting, then

Only your wrapper class is dependent on Properties.Settings.Default.aSetting requiring integration tests.

All your other code can be tested with quick, fast running unit tests.

A code example using C# of this approach can be found on my blog: Property.Settings.Default makes it hard to unit test any method that uses it


问:
Piwik License question
I need to create a specialized analytics app based on Piwik, it will be a commercial SaaS service for small businesses. It uses the piwik javascript tracker, API and the DB to store events, custom variables etc.. just like piwik and extra functionality built on top. I'm just not sure if Piwik license allows it.

If you distribute a modified version of Piwik, or software that
  includes Piwik as a module, or develop a website for a customer/client
  that integrates closely with Piwik, you must give access to the code
  source and publish all the code under the GPL.

However, it also states:

The data coming from the Piwik API belongs to you and is not covered
  by the GPL.

You can use Piwik as a service, and reuse, publish, display, modify,
  process the data coming from the Piwik API using the REST API web
  services call.

.. so does that mean If I use Piwik Tracker, APIs and the database, but NOT its front-end admin panel, then GPL doesn't apply to me?

答:
Piwik is open-source software released under the GPLv3 license. This means that you have the right to create a service that is built upon the functionality of piwik. If you use any part of Piwik in your project, the GPL applies to you.

The limitations on your project depend on the business model you are going for.

If your customers will always connect to your server when using the SaaS service you are providing, then you don't need to publish anything. This is because giving someone the possibility to interact remotely with your software is not considered to be distribution under the GPL.

If your customers run your software on their own servers, then the GPL license requires you to release the code for your entire service under the GPL license and to give your customers the same rights as you have with regards to changing the code and/or distributing it.

In any case, the data gathered using Piwik does not have to be made public.

Title: Piwik License question


问:
Where view models inside Web project of n-tier application should be placed?
Let's assume we have an ASP.NET MVC web application with following tiers:

Business logic

Entities (business domain and database POCOs)

Common (resources, consts)

Data access (database EF queries, EDMX EF models and so on)

Web application (MVC web application)

We're using view models approach. Currently view models are placed in Entities layer. Data access queries returns view models (due to efficiency issues, so we avoid using mapper).

Web layer references all other layers.
Data access references Common and Entities layers.
Business logic references Entities and Common layers, in the future also Data access layer.

There's an idea to move view models to Web layer. Why? Because they're in fact bound with a particular technology (MVC) and UI implementation.
But we're facing a problem here, because in this scenario Data access layer must reference Web and Web references Data access, so we have a circular dependency issue.

Moreover we have scenario when some validation of view model requires reference to Data access layer. We're going to keep validation method inside view models. Currently we want to implement it by injecting database context class (which is in Data access layer) to view model by constructor.

Do you have any idea how can we avoid it? Is it good idea to keep view models inside our Web layer?

答:
I keep view models in the web project, for reason you stated, it's usually only useful to the relevant view. </p>

<p>I'm not sure why your data access layer would reference the web project though? </p>

Body:
I keep view models in the web project, for reason you stated, it's usually only useful to the relevant view.

I'm not sure why your data access layer would reference the web project though?


问:
Multiple CS Sheets or Javascript
I have a homepage with a navigationBar on top of the Viewport contains two buttons.

One is the default selected home button which calls/displays home.html. The other for example is Ubuntu which calls UbuntuTutorial.html.

When home is selected, the home-buttons bottom-border is colored while the bottom-border from Ubuntu-button is transparent to show the user that he is actually at the home-section of my website

Now, from a professional view, is it a common pattern to create two nearly similar CSS where the only difference is the colored bottom-border of the clicked button (i.e home or ubuntu) or, which I would prefer, fetch the current displayed html-file and color the bottom-border of the specific button with js... avoiding multiple css where just one line differs. (But also keeping in mind that some(high amount, low amount?) of user disabled js..)

Everything is kept, in my opinion, professional. I am using external CSS and external JS-Files.

答:
The usual solution in this situation is to have a selected class that defines the style of a button that represents the current page - i.e. a different color for the bottom border.

When the current page changes, use JS to remove the selected class from all buttons and add it to the one that was just clicked.

Title: Multiple CS Sheets or Javascript


问:
Why are objects instantiated this way?
Some times I see an object instantiated this way.

```<code>ICustomer oCustomer = new Customer
</code>```

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

```<code>Customer oCustomer = new Customer
</code>```

答:
In C# there isn't much difference.

The difference lies in what you can call on the reference you created.

This code

```<code>ICustomer customer = new Customer();
</code>```

creates an interface reference named customer to the instance created by the new Customer(); call.

This code

```<code>Customer customer = new Customer();
</code>```

creates an object reference name customer to the instance created by the new Customer(); call.

While both references point to an instance of the Customer class, they are different. The interface reference only offers what is defined in the ICustomer interface, regardless of what else the Customer class makes available. Using the object reference you can use everything the Customer class has to offer.

Using an interface reference you would have to cast it back to the implementing class in order to use the "additional" stuff on offer by the class. Something you really do not want to do. After all, when you are passed an interface reference you can't be certain which class was used to instantiate the object referenced by it. There really is only one exception to this rule: when you just created the interface reference yourself and need to use methods that you do not want to put in the interface because they are only needed during construction/building/initialization of the instance. And even this should be a rare case.

For C# that's about it.

For languages in which the developer is responsible for explicit lifetime management of the objects that are instantiated (iow having to free each object explicitly), there can be a huge difference between the two ways of referencing the instantiated object.

In Delphi for example, interfaced objects (instances of a class implementing an interface) are reference counted by default and are freed "automatically" when their reference count drops to zero. The reference count is incremented and decremented by _AddRef and _Release calls that are added to your code automatically by the compiler.

In Delphi you really do not ever want to create an object reference to an instance of an interfaced class. Doing so means the compiler won't insert the _AddRef call that increments the reference count to 1 upon instantiation. Which means the reference count is one too low. Which means the instance will be freed too soon.

That's why the advice for languages such as Delphi is to never to mix interface and object references and to always use interface references for interfaced classes.

Title: Why are objects instantiated this way?

Body:
In C# there isn't much difference.

The difference lies in what you can call on the reference you created.

This code

ICustomer customer = new Customer();

creates an interface reference named customer to the instance created by the new Customer(); call.

This code

Customer customer = new Customer();

creates an object reference name customer to the instance created by the new Customer(); call.

While both references point to an instance of the Customer class, they are different. The interface reference only offers what is defined in the ICustomer interface, regardless of what else the Customer class makes available. Using the object reference you can use everything the Customer class has to offer.

Using an interface reference you would have to cast it back to the implementing class in order to use the "additional" stuff on offer by the class. Something you really do not want to do. After all, when you are passed an interface reference you can't be certain which class was used to instantiate the object referenced by it. There really is only one exception to this rule: when you just created the interface reference yourself and need to use methods that you do not want to put in the interface because they are only needed during construction/building/initialization of the instance. And even this should be a rare case.

For C# that's about it.

For languages in which the developer is responsible for explicit lifetime management of the objects that are instantiated (iow having to free each object explicitly), there can be a huge difference between the two ways of referencing the instantiated object.

In Delphi for example, interfaced objects (instances of a class implementing an interface) are reference counted by default and are freed "automatically" when their reference count drops to zero. The reference count is incremented and decremented by _AddRef and _Release calls that are added to your code automatically by the compiler.

In Delphi you really do not ever want to create an object reference to an instance of an interfaced class. Doing so means the compiler won't insert the _AddRef call that increments the reference count to 1 upon instantiation. Which means the reference count is one too low. Which means the instance will be freed too soon.

That's why the advice for languages such as Delphi is to never to mix interface and object references and to always use interface references for interfaced classes.


问:
Check distance between all elements in a list of numbers in O(n*lg(n))
I have an exercise for my algorithms and data structures class, where I basically have to implement a divide and conquer algorithm or function called check_distance to determine whether all numbers in a list X have distance greater or equal to k from each other, and I have to show that the worst case complexity of this algorithm is O(n*lg(n)).

When I think at algorithms that have to run in at most n*lg(n) time asymptotically, I think immediately about merge sort, which is exactly the divide and conquer algorithm that I used. Are my functions are correct or not?

Before this exercise, I had already one, where I had to create another divide and conquer function to check if there are duplicates in a list. This function should also run in O(n*lg(n)).

This is my function check_duplicates, which uses again the merge sort algorithm (I am not posting the code of the merge sort algorithm, because it's a typical merge sort. If you want me to post it, just ask!):

```<code>def check_duplicate(X):
    S = merge_sort(X)               # O(n*lg(n))
    for i in range(0, len(S) - 1):  # O(n)
        if S[i] == S[i + 1]:
            return True
    return False
</code>```

My first questions are: Is it correct, and does it run in O(n*lg(n)) time?

Now, I pass to the real problem, my second function, which (as I said) should check that the distance between each element in a list is greater or equal than a constant k. For this check_distance function, I used the check_duplicate function above, to ensure that are no duplicates, otherwise it returns immediately false.

Now, my main reasoning was again to sort the list. Once the list is sorted, the ai + 1 element will always be greater or equal than ai, therefore, for all ai in X, ai <= ai + 1 <= ai + 2, etc.

Now, again, for all ai in X, if I sum ai + k, and this is less or equal than ai + 1, then the distance between all elements should be >= k.

Am I correct?

```<code>def check_distance(X, k):
    if check_duplicate(X):        # n*lg(n)
        return False
    else:                         # no duplicate values
        A = merge_sort(X)
        for i in range(len(A) - 1):
            if A[i] + k > A[i + 1]:
                return False
        return True
</code>```

If I am not correct, is there a better approach?

答:
check_duplicate is redundant. The list must not be sorted because sorting rearanges elements.

Calculate the difference between two consecutive elements and compare the value against k.

```<code>def check_distance(x, k):
    l = len(x)
    if l in [0,1]:
        return False

    for i in range(l-1):
        if x[i+1] - x[i] < k:
            return False
    return True
</code>```

Using recursion,

```<code>def check_dist(x,k):
    l = len(x)
    if l == 2:
        return x[1] - x[0] >= k
    if l in (0,1):
        return False
    return x[1] - x[0] >= k and check_dist(x[1:],k)
</code>```

Body:
check_duplicate is redundant. The list must not be sorted because sorting rearanges elements.

Calculate the difference between two consecutive elements and compare the value against k.

def check_distance(x, k):
    l = len(x)
    if l in [0,1]:
        return False

    for i in range(l-1):
        if x[i+1] - x[i] < k:
            return False
    return True

Using recursion,

def check_dist(x,k):
    l = len(x)
    if l == 2:
        return x[1] - x[0] >= k
    if l in (0,1):
        return False
    return x[1] - x[0] >= k and check_dist(x[1:],k)


问:
Why are people making tables with divs?
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

答:
There are already tons of great answers here. But I wanted to add that table elements have rendering limitations that don't exist for div elements.  Try and make a table that does virtual scrolling (like: SlickGrid, DataTables, and others) and you'll be sorely disappointed. It just doesn't work. Most (All?) modern Javascript grids use divs because the css allows for much more flexible rendering.

There are other limitations as well. My general rule is that if I'm going to see the whole table on a single screen, and I don't want any/much custom rendering for it I use a table element, otherwise I go with divs because I can control the results much, much more easily.

Title: Why are people making tables with divs?


答:
You could, although I'm not certain I actually recommend it, embed the user's token in the filename of the installer, and put code in the installer to retrieve it.

To prove I didn't make it up, Sophos anti-virus does this. Rather predictably, number one on their list of Most common Installation issues is "Renaming the installer file name". But I assume the benefit is that since they don't modify the contents of the installer at all, the server that distributes it doesn't need access to the private keys that sign it.

Anyway the general principle is that for serious software you probably want to distribute a signed executable generated in the most secure location you have, together with an unsigned token that's generated on the fly by some public-facing web server. If you don't want to make the user download two files, copy-paste the token, or anything of that kind, then the filename is about the only bits you have left to communicate with.

Putting the token into unsigned code intended to run with full user privileges on the user's machine, even just a script, rather defeats the purpose of signing the installer. If you want to go that route, then you almost might as well distribute an unsigned installer with the user's token patched into it. To a tiny proportion of geeky users, a very simple VBScript doesn't need to be signed since it can be verified by eye not to be malicious. But there aren't many of them, so "almost" is "very nearly indeed".


问:
equal distribution within given set of users
I have a requirement where I have a list of entity and users who that entity can be assigned

E1 can be distributed by U1 or U2

E2 must be distributed by U5

E3 can be distributed by U2 or U3 or U4

I have such 50K entities and for each entity there might be 1 or more users. In case of 1 user, its clear and entity will be assigned to that user only. In case of multiple users, it can be assigned to any one them.

We want to distribute it such that each user gets equal amount of entities. and there are minimal possible/unavoidable skewed distributions, also each user might already posses some entities : U1 has 2K and U2 has 3K entitis already, so the distribution should take care of this fact as well.

EDIT 1

We have already tried a solution of going sequentially and assigning one entity at a time as per the allocation to users at that point in time, but that producing skewed results, because we are getting users who have less allocation earlier but more allocation later or viceversa...

E1 to E25 "must be handled by any of" U1 & U2

E26 to E50 "must be handled by any of" U2 & U3

if we go sequentially, in the end : U1 gets 12 (from E1-E25), U2 gets 19 (13 from E1-E25 & 6 from E26-E50) & U3 gets 19(from E26-E50).
So all in all 50 allocated. fine. but see the skewed results

EDIT2

Why do we have different users per entity? there are multiple products to be distributed. Some users handle multiple products and some users handle single product, but still all the users need to be load balanced.

答:
This brings back memories of an Operations Research class I had in college a very long time ago.  You might want to do some googling on the Assignment problem and the Generalized Assignment problem for some background info and more rigorous solutions.

Having said that, I'd do the following:

Put all the entities that can be processed by the same set of users into a "bucket".  Bucket 1 might contain all the entities that
  can be processed by U1 or U2. Bucket 2 might contain all the entities
  that can be processed by U2 or U3.  Bucket 3 (not in your examples)
  might contain all the entities that can only be processed by U4.

Process all the "single entity" buckets (Bucket 3).  There are no choices to be made here, and you may as well get this out of the way
  first.  You mentioned that 80% of your entities may fall into this
  category.

At this point, stop looking at buckets and entities, and process users.  Find the user with the least number of entities assigned and
  have them pick one entity from the most full bucket (bucket with the
  largest number of entities).

Repeat step 3 until all entities are assigned.

This will definitely require testing - I reserve the right to be wrong :-)


问:
When making a fix to an earlier commit, should I rebase or add a separate fix up commit?
A common scenario in software development is code reviewing somebody else's code. A common tool for doing this is opening a Pull Request.

My question is, when issues are found in the review, should the changes

be committed separately (new commit)

or should the existing commit be modified (assuming nobody is branching from your earlier commit... since re-writing history from a shared branch is bad news).

For the first scenario, it's easy to track incremental changes, though it adds some noise to the commit history. The second options has the reverse pros and cons.

答: You assume the fix does not introduce any new issues and fixes the old ones complete. But lots of fixes are worth a review on their own - and that is probably much easier when the incremental changes can be reviewed separately.</p>


问:
Libraries licenses in proprietary product
Our closed-source proprietary web application uses quite a lot of libraries with different licenses (namely Apache 2.0, MIT, BSD-like, LGPL 2.1, etc). We want to distribute binaries (ear files, specifically) together with these libraries' jars.

If I understand correctly, most of the licenses demand from the distributor to put libraries licenses into the distribution package.

This problem must come up all the time. Is there a standard/canonical way to do this? As I saw in other projects (e.g. PostgreSQL), there does not appear a standard way to specify the list of licenses. Is it sufficient to put somewhere all the licenses and the list of libraries and which library is issued under each license?

UPDATE:
In the comments the link to the similar question was posted and if i get it correctly, i need to put library license file and 'NOTICE' file.
Is there a standard way of doing it? For example, in PostgreSQL there's one big file for all licenses. Also what should i put in 'NOTICE' file?

答:
There is no standard way to mention which licenses are used by the third-party libraries that you use. This has to do with the different requirements that licenses place on this.

For some licenses(like BSD), it is possible that the license text is only present as a comment in the source code, while other licenses (like GPL and Apache) are so lengthy that the full license text is distributed in a separate file.

A good strategy to deal with this is the following

For each library you use, check if there is a file containing just the license information and if there are any other files that the license requires you to include (such as a NOTICES file for the Apache license). Put these files together in a 'licenses' folder. If necessary, rename the files to make it clear what licence is contained in it.

Mention in your documentation which libraries you use and under which license they are distributed

Distribute the content of the 'licenses' folder together with your application.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答: As long as it needs to be to do what it needs to do, but no longer.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
For specialized code, use custom interfaces and types or available generic ones?
I will use Java as example, but the question pops up in my mind with any language / framework / stack / pattern / ...

For instance in python, should I just use a dict(), or should I subclass it to make my intentions clear? or is that violating duck-typing principal of python? or ...

Imagine a simple Echo Server running on port X. The Server consists of:

Server accepts clients, and hands them to client handlers.

ClientHandler, who handle connected clients (doh!)

Main server has a list of registered client handlers, and passes the received request to client handlers in this list, so they can handle or ignore it (not a good design but it's simple). We may now have a ClientHandler who echoes back the received text capitalized, one that only echoes half of it, one that ...

Now consider these two versions:

```<code>interface GenericServer {
    void start();
    void stop();
    // ... other server related stuff, such as set backlog.

    void registerHandler(java.util.Observer o);
}
</code>```

It looks like duck-typing to me, but in Java! It's okay to pass in any object of type java.util.Observer as handler. As far as GenericServer is concerned, it should be able to observe.
We could also do:

```<code>interface SpecializedServer {
    // Marker interface to make everything more clear.
    interface ClientHandler extends java.util.Observer { }

    void start();
    void stop();
    // ... other server related stuff, such as set backlog.

    void registerHandler(ClientHandler ch);
}
</code>```

Now it uses a Marker Interface to say Attention! The passed in observer MUST be a ClientHandler! it must know about clients.

But too much use of marker interface may be sign of bad design too. Which version of these two servers is the right way to do it? what is the right thing to do?

答:
I wouldn't extend java.util.Observer with another interface unless you're actually adding new member definitions to it.

Merely wrapping an interface in another one just to change its name is not enough of a justification, in my opinion.  Your fellow programmers will believe that ClientHandler defines additional members, when it fact it does not.  And the purpose of java.util.Observer is presumably already well-understood.


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
The benefit of the first method is that it is more vertically compact, so you can fit more code on your screen, and that is why I prefer it. The only argument I heard in favor of the second method is that it makes it easier to pair opening and closing brackets, but most IDE's have a keyboard shortcut for that, and it's actually a false statement- instead of pairing an opening bracket to a closing bracket you can pair a closing bracket to the "start of block" expression (if, else, for, while) on the same indentation level, so it's just as easy to determine where the start of the block is.

I see no reason to waste an entire line just for a bracket when the preceding for/while/if construct already visually indicates the start of a block.

That said, I do believe that the closing bracket should be in its own line because we need something to indicate the end of a block and its indentation structure in a visible way.


问:
Notifications table design?
I'm trying to create a notification system for my social network. But I'm stuck on the database design. so when a user comments on another user I want to display "X commented on your post." or when someone follows another I want to display a notification.

This is my table so far:

```<code>CREATE TABLE IF NOT EXISTS `notifications` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `notification_id` int(11) NOT NULL,
  `text` text NOT NULL,
  `read` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</code>```

The part where I'm confused at is, Should I insert a record when someone follows another person? Like... Right after when someone clicks follow button? If so, What should I insert to the row?

答:
One way to do that :
Create a new table , Name it something like : Followers with a composite primary key and reference the foreign keys to your 'Notifications" table
Something like:

```<code>CREATE TABLE Follower (
  userid integer,
  Followeruserid integer,
  primary key (userid, Followeruserid)
);
</code>```

Title: Notifications table design?

Body:
One way to do that :
Create a new table , Name it something like : Followers with a composite primary key and reference the foreign keys to your 'Notifications" table
Something like:

CREATE TABLE Follower (
  userid integer,
  Followeruserid integer,
  primary key (userid, Followeruserid)
);


答:
Design your database around the data. What I mean by this is:

You have users

You have posts

You have comments

You have users you are following

You have notifications

It looks like you are trying to design your database around one use case rather than better organizing your data.

Try something like:

```<code>CREATE TABLE Users(
   id int not null auto_increment,
   name string not null
)

CREATE TABLE Posts(
   id int not null auto_increment,
   userID int foreign key Users(id),
   text string,
   whenPosted datetime default getDate()
)

CREATE TABLE Comments(
   id int not null auto_increment,
   userID int foreign key Users(id),
   postID int foreign key Posts(id),
   text string
)

CREATE TABLE Followers(
   userID int foreign key Users(id),
   followedUserID int foreign key Users(id)
)

CREATE TABLE Notifications(
   id int not null auto_increment,
   generated date default getDate(),
   text string //and other meta-data
   isRead bit not null default 0
)
</code>```

so when a user comments on another user I want to display "X commented on your post."

When you generate a comment you can immediately insert a notification into the Notification table (this is straightforward).

Should I insert a record when someone follows another person? Like... Right after when someone clicks follow button? If so, What should I insert to the row?

Now, since you have a Followers table you can add them to that table on clicking that button.

You can then do either:

Check when you submit a post in the future add a new notification (and ignore all previous posts)

Immediately create a notification for all posts after a given time period

I recommend the first option, to me "follow" implies "follow all new content."

Title: Notifications table design?

Body:
I'm trying to create a notification system for my social network. But I'm stuck on the database design. so when a user comments on another user I want to display "X commented on your post." or when someone follows another I want to display a notification.

This is my table so far:

```<code>CREATE TABLE IF NOT EXISTS `notifications` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `notification_id` int(11) NOT NULL,
  `text` text NOT NULL,
  `read` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</code>```

The part where I'm confused at is, Should I insert a record when someone follows another person? Like... Right after when someone clicks follow button? If so, What should I insert to the row?

Body:
Design your database around the data. What I mean by this is:

You have users

You have posts

You have comments

You have users you are following

You have notifications

It looks like you are trying to design your database around one use case rather than better organizing your data.

Try something like:

CREATE TABLE Users(
   id int not null auto_increment,
   name string not null
)

CREATE TABLE Posts(
   id int not null auto_increment,
   userID int foreign key Users(id),
   text string,
   whenPosted datetime default getDate()
)

CREATE TABLE Comments(
   id int not null auto_increment,
   userID int foreign key Users(id),
   postID int foreign key Posts(id),
   text string
)

CREATE TABLE Followers(
   userID int foreign key Users(id),
   followedUserID int foreign key Users(id)
)

CREATE TABLE Notifications(
   id int not null auto_increment,
   generated date default getDate(),
   text string //and other meta-data
   isRead bit not null default 0
)

so when a user comments on another user I want to display "X commented on your post."

When you generate a comment you can immediately insert a notification into the Notification table (this is straightforward).

Should I insert a record when someone follows another person? Like... Right after when someone clicks follow button? If so, What should I insert to the row?

Now, since you have a Followers table you can add them to that table on clicking that button.

You can then do either:

Check when you submit a post in the future add a new notification (and ignore all previous posts)

Immediately create a notification for all posts after a given time period

I recommend the first option, to me "follow" implies "follow all new content."


问:
Inheritance or Composition?
Let's say I have a main class A and another class B.

In the B class the user can change some settings and variables of the program that belongs to A, I want to be able to apply these changes to the A class, should I use inheritance and apply the changes to the father of B which is A or should I use composition and pass the instance of A to class B and change the variables of A in this manner?

which one is best practice and why?

note : If it helps in anyway, I'm writing a gui application and A is my main window and B is a setting window opened from A.

答:
Inheritance is "is-a", composition is "has-a". Is it the case that "a B is-an A", or it is the case the "a B has-an A for some reason"?

It is obvious that setting window is-not-a main window, but is an external actor. So it should have an A passed in.

EDIT: Since you told what A and B is, that is, windows, you should separate domain from presentation; that is, not even B should be passed an A (no, those are just views), but B's model should be passed A's model. But treat this just as an additional note, as original question was about inheritance vs. composition.

Title: Inheritance or Composition?


问:
Approaching SICP in Clojure instead of Scheme
I am a third year bachelor student in a software engineering program, and I brought up the idea of reading SICP to an adviser to gain a deeper and more fundamental understanding of the principles behind all this software we engineer.

He suggested not to learn Scheme to complete the book (because it's not as common as modern dialects of Lisp) but to do the exercises in Clojure instead.

It's an already difficult book, if I do attempt the book's exercises in the more modern Clojure, how would that work? For example, I can't find any real solutions, the syntax they teach for Scheme is different, etc.

答: I found your question just after finding this site which looks like it is right up your alley (though you may have found it or an alternative in the intervening months): SICP in Clojure</p>


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Make PHP truly object oriented. The slap on another global function evolution of PHP needs to end.

```<code>array_merge(array_filter(array_intersect_key($arr1, $arr2), "is_int"), $arr3);
</code>```

This is hard for me to read. I have to make my own mental stack and sort of compile it myself. Basically it should read in the reverse. $dog->wakeup()->bark(); is easy to read compared to bark(wakeup($dog))

```<code>$arr1->array_intersect_key($arr2)->array_filter("is_int")->array_merge($arr3);
</code>```

You've made the step towards enabling object/method support now please use it in actual core PHP functions.

Let's rename 500 functions and change parameter order for them.

Shifting this functionality to methods would enable them to be renamed using some consistently. Would it break any backwards compatibility if strings and arrays had their own methods?

Body:
Make PHP truly object oriented. The slap on another global function evolution of PHP needs to end.

array_merge(array_filter(array_intersect_key($arr1, $arr2), "is_int"), $arr3);

This is hard for me to read. I have to make my own mental stack and sort of compile it myself. Basically it should read in the reverse. $dog->wakeup()->bark(); is easy to read compared to bark(wakeup($dog))

$arr1->array_intersect_key($arr2)->array_filter("is_int")->array_merge($arr3);

You've made the step towards enabling object/method support now please use it in actual core PHP functions.

Let's rename 500 functions and change parameter order for them.

Shifting this functionality to methods would enable them to be renamed using some consistently. Would it break any backwards compatibility if strings and arrays had their own methods?


问:
Is lazy loading always required?
I know lazy loading is required when an expensive database call is being made. It would make sense using lazy loading in this example. The below example is in the context of asp.net so it's thread safe.

```<code>private list<Customer> _AllCustomers;
public list<Customer> AllCustomers {
get {
    if (_AllCustomers == null) {
        _AllCustomers = ExpensiveDataCall();
    }

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

Even if it's just instantiating an object that is used in multiple places, I always use lazy loading. Consider the following example:

```<code>private _Customer;
public Customer Customer {
get {
    if (_Customer == null) {
        _Customer = new Customer;
    }

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

Recently someone told me that lazy loading is only required for expensive database calls. Is that right? I thought every time an object is instantiated memory increases(apologize for the terminology. I don't have lot of technical knowledge.)

答:
There's an additional thing you may want to take into account besides the sheer speed factor.

The code itself. And it's maintainability.

Does this kind of lazy loading make the code slower to write, or harder to understand and change?

Does it make the architecture more complex that it needs to be?

Some examples follow.

```<code>if (_AllCustomers == null) {
    _AllCustomers = ExpensiveDataCall();
}

return _AllCustomers; // Was: _Customers, not sure if by design.
</code>```

Now, think of a scenario where you've read the AllCustomers attribute once already and then made some changes that could relate to that data. How does the caller get a fresh list of customers should it need one?

Can it somehow force nullify _AllCustomers to make the ExpensiveDataCall() happen again? Should it even know about the fact that the data in _AllCustomers may be old by now?

You can always create an additional method RefreshAllCustomersData(), or similar, but that adds the complexity of your code.

This, of course, may not be a problem in your application. It depends on the overall architecture. And even if it is, the solution to refresh may very well be suitable. It's still something to consider.

Even more simple scenarios, like the one you really were interested in, could create additional overhead for a programmer, if not to the application itself.

```<code>if (_Customer == null) {
    _Customer = new Customer;
}

return _Customer;
</code>```

What happens, if a programmer, doing a class, does accidentally forget to check for null and create a new object, and only just returns null? It probably won't take too many seconds to notice, but it could.

When it comes to coding styles, this is an additional thing to remember and apply to each and every similar class. Having, for instance, only couple of model classes that follow this convention, could be confusing.

Furthermore, that's couple of extra lines that you perhaps could do without. At least, up until the point that you run your application with profiler and do note that adding lazy loading to certain places really do improve performance in a noticeable way. Less code means there's less to read and less to understand.

However, as with the first example, the practicality of this, too, depends. If you do know that you have performance culprits that go away by doing lazy loading on some spesific classes, go for it.

It is still useful to measure how much of an impact they are making, before making the decision. And whenever you form a solid convention, stick to it.

tl;dr: While lazy loading is useful tool for improving performance, it is not always required. That's because there are other factors to consider, too. Namely, maintainability of the code.

Title: Is lazy loading always required?

Body:
There's an additional thing you may want to take into account besides the sheer speed factor.

The code itself. And it's maintainability.

Does this kind of lazy loading make the code slower to write, or harder to understand and change?

Does it make the architecture more complex that it needs to be?

Some examples follow.

if (_AllCustomers == null) {
    _AllCustomers = ExpensiveDataCall();
}

return _AllCustomers; // Was: _Customers, not sure if by design.

Now, think of a scenario where you've read the AllCustomers attribute once already and then made some changes that could relate to that data. How does the caller get a fresh list of customers should it need one?

Can it somehow force nullify _AllCustomers to make the ExpensiveDataCall() happen again? Should it even know about the fact that the data in _AllCustomers may be old by now?

You can always create an additional method RefreshAllCustomersData(), or similar, but that adds the complexity of your code.

This, of course, may not be a problem in your application. It depends on the overall architecture. And even if it is, the solution to refresh may very well be suitable. It's still something to consider.

Even more simple scenarios, like the one you really were interested in, could create additional overhead for a programmer, if not to the application itself.

if (_Customer == null) {
    _Customer = new Customer;
}

return _Customer;

What happens, if a programmer, doing a class, does accidentally forget to check for null and create a new object, and only just returns null? It probably won't take too many seconds to notice, but it could.

When it comes to coding styles, this is an additional thing to remember and apply to each and every similar class. Having, for instance, only couple of model classes that follow this convention, could be confusing.

Furthermore, that's couple of extra lines that you perhaps could do without. At least, up until the point that you run your application with profiler and do note that adding lazy loading to certain places really do improve performance in a noticeable way. Less code means there's less to read and less to understand.

However, as with the first example, the practicality of this, too, depends. If you do know that you have performance culprits that go away by doing lazy loading on some spesific classes, go for it.

It is still useful to measure how much of an impact they are making, before making the decision. And whenever you form a solid convention, stick to it.

tl;dr: While lazy loading is useful tool for improving performance, it is not always required. That's because there are other factors to consider, too. Namely, maintainability of the code.


问:
elevator algorithm and implementation
I wanted to know how (real) elevators work. But, so far, I could not find much material about the algorithms they use, nor software (if any) for simulation. Could anybody give me references for that?</p>

答:
Elevator algorithm is best described using Knuth's Elevator algorithm.

But in the simple steps, the algorithm can be stated as:

Travel in the single direction until the last request in that
direction.

If there is no request, stop and proceed towards other direction, if
there is any request from other direction.

Title: elevator algorithm and implementation


问:
Parking Simulation Software Design
I've been requested to develop a quite well known problem for a job interview. The Parking Simulation which an example can be found here.

I came up with some ideas for which design pattern should I use and so on, but I got confused when I searched about how other people interpreted that.

This might be a really dumb question, but I need to be sure that I am not the only one who thinks like this.

I've found a lot of people who use a Vehicle Interface which is implemented by classes Car, and Truck (So far, so good). But all of them put the properties of the size occupied by the vehicle and the fee which it has to pay, on those classes as well.

I can understand that. But for me it is not making much sense, since the size is not the actual Vehicle size, but how much parking space it requires. For example (a little no sense but...) you could create another Parking based on motorcycles/bikes size, so the values would differ because the Parking is different, not vehicles themselves.

The same goes for the prices, at least for me, the parking tell the fees, not the vehicles.

But, if the parking do everything the vehicle classes will have nothing to do, and it will not look very cohesive.

Is that clear? Does this make sense or I'm being dumb?

答:
I agree fully to you, for the given task, introducing a Vehicle class IMHO does not make much sense. It could make sense in the future, assumed you need to record more information about cars than currently requested, but when someone tells me to write "production ready" code, I would stick as near to the YAGNI principle as possible and would not design any features not requested yet.

To how "other people" might interpret the task: I have seen examples of Vehicle and Car in so many introductory OO examples, especially for introducing the concept of inheritance, that I am pretty sure lots of devs who read the requirement description half-way through are tempted to shoehorn the problem into the Vehicle/Car abstraction they have learned earlier ago.

IMHO that's a form of "programming by conincidence", something which is mentioned in the book "The Pragmatic Programmer" as a kind of anti-pattern.

Title: Parking Simulation Software Design


答:
I think there is a trade off.  If you have a lot of short methods, it is often harder to debug them than one long method.  If you have to jump around the editor 20 or 30 different times to trace one method call, it will be hard to keep it all in your head.  Meanwhile if there is one well written clear method, even if it is 100 lines, it is often easier to keep in your head.

The real question is why should items be in different methods, and the answer as given above is code re-use.  If you aren't re-using the code (or don't know) then it may make sense to leave it in one giant easy to follow method and then as you need to re-use it, split the parts that need re-using into smaller methods.

In reality part of good method design is making functionally cohesive methods (essentially they do one thing).  The length of the methods do not matter.  If a function does one well defined thing and is 1,000 lines than it is a good method.  If a function does 3 or 4 things and is only 15 lines, then it is a bad method...

Title: What is proven as a good maximum length of a function?

Body:
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.


问:
Any advantage to using multiple build systems?
When working on a large project which happens to have multiple build systems, (C, C++) in this case, they may use multiple build systems -- for different platforms, or for historic reasons.

With the popularity of meta-build systems, there is the opportunity to use a single build system which can generate files for different platforms.

The disadvantages for using multiple build-systems seem rather obvious...

maintenance overhead.

higher barrier of entry for developers,
(needing some experience in multiple build systems)

more files to navigate in the source repository.

Ignoring the effort it may take to do the initial migration, are there any advantages to keeping multiple build-systems in use? (when there is the opportunity to use only one?)

Said differently, if someone comes into a project and suggests to use a single cross platform build system, are there any reasonable arguments against this?

Since it was requested I be more specific, the projects I have in mind are large C/C++ code bases, using a mix of automake, MSVC-project-files, SCons & in one case CMake (which is an example of a meta-build system).

答:
Your question is still too broad.

Notice that Cmake is explicitly a cross-platform and compiler independent meta-builder.

You are mentionning Windows products, and I don't know and never used Windows, and notice that Unix and POSIX have a little bit standardized building: invocation of cc, standardization of a POSIX make specification.

Notice also that builder systems (even legacy ones) are still making significant progress. In particular GNU make has made very significant process in its 4.x version, with important features like Guile integration which would enable projects to avoid metabuilders. However, most software are not using recent features of GNU make (which I feel could be used even to avoid autoconf etc...)

I feel that the main advantage of Cmake is cross-platform abilities.

Notice also that other build systems (e.g. omake) could probably be used to avoid metabuilder.


问:
Better to write your .NET library with COM limitations in mind, or separate your .NET library from Interop?
I came across this interesting article: How I Came to Love COM Interoperability on CodeProject, which got me thinking...

The author argues that they do not want any COM-ities in their .NET library because it takes away from the beauty of their .NET library. Instead, they'd rather write a separate Interop library that exposes their .NET library to COM. This Interop library would handle the fact that COM doesn't support Constructors with Parameters, Overloaded Methods, Generics, Inheritance, Static Methods, etc.

And while I think that is very novel, doesn't it just complect the project?

Now you need to unit test your .NET library AND an Interop library.

Now you need to spend time figuring out how to work around your beautiful .NET library and expose it to COM.

You need to, effectively, double or triple your class count.

I can certainly understand if you need your library to support both COM and non-COM. However, if you only intend to use COM does this sort of design bring any benefits that I don't see? Do you only gain the benefits of the C# language?

Or, does it make versioning your library easier by providing you a wrapper? Does it make your Unit Tests run faster by not requiring the use of COM?

答:
Well, to be fair, the original author of that article did not use the word "beauty" anywhere in his article, that was you, which might give a biased impression on that for those who did not take the time to read the article by themselves.

As far as I have understood that article, the .NET library already existed and was written without COM in mind - probably because at the time when the library was created, there was no requirement to support COM.

Later on, the additional requirement of supporting COM was introduced. Facing such a situation, you have two options:

redesign the original lib to make it compatible with COM interop (with the risk of breaking things)

let the original working library mostly as it is, and instead create a separate  assembly with the function of a "wrapper" (or "adapter")

Creating wrappers or adapters is a well-known design pattern (or in this case more an architectural pattern), and the pros and cons are also well known. One argument for it is the better "separation of concerns", and that has nothing to do with beauty.

To your concerns

Now you need to unit test your .NET library AND an Interop library.

When you introduce your COM interface to your existing .NET library by redesign, you have to test that interface either. Introducing a manually written adapter may need some additional tests that the interface is working, of course, but there is no need to copy all unit tests of the core business functionality of the lib. Don't forget it is just another interface to the lib.

Now you need to spend time figuring out how to work around your beautiful .NET library and expose it to COM.

When you have to redesign the original library you have to figure that out, too, and I guess it will be much more work.

You need to, effectively, double or triple your class count.

Only for the classes which are exposed through the public COM interface, which should be a small number of the classes part of the original library.

Said that, for a different situation you mentioned, when you already know you have to support COM as a first-class citizen right from the start, I think you are correct: one should save the hassle of adding a separated adapter lib and design the .NET lib with COM support directly.


问:
Should my program be flawless at release
I'm building a big, very complex piece of open-source software, and it's killing me trying to make what I have as "clean" as it needs to be.

What I want to know is: If there is an undetected flaw in my program and/or my code cleanliness (is that a word?), can that harm my reputation?

Likewise, is it bad that I've reused code from an already open-source app but have rewritten it my way?

Thanks.

答:
No. There is no such thing as a flawless program, so don't aim for that.

What you should aim for in for a first release is good/thorough documentation, some automated tests, one or more places for people to tell you about any problems they have or features they'd like to see, and a clear/prominent description of what your program library is and is not supposed to accomplish. And it should actually work, obviously.

Regarding reputation, I would expect people to care more about how you respond to bug reports/feature requests and how your program evolves rather than how pristine it might be at version 1.0. If you have at least the things I mentioned above, you'll be in a good position to respond well to all the input you'll inevitably get.

Reusing code from another app is fine if the license allowed it and you follow all the license terms. I would also try to attribute it somewhere even the license doesn't require it; that's just more polite.


答:
When changing or reorganizing tools from your development infrastructure, the tradeoffs are almost always the same, if it is the compiler, the IDE, the VCS or the build system:

the change will need some effort - with no immediate customer value

the team (or parts of it) typically knows the existing tools, but not the new tools. So people have to get training, which takes time and money, with no immediate customer value.

when trying to introduce a "one size fits all" solution, you have the risk learning that not every feature which was available in the old tool will be available in the same quality in the new one.

So when changing the build tools, there must be some clear value in it at least for the existing team, not just for new devs, and the value must be enough to convince even your boss that it outweighs the disadvantages above.

In your current situation I suggest you identify if there are parts of current the build process where the team is unsatisfied with. That's the part where you have a chance to remove an old build tool and replace it by a newer, more standardized one.

Title: Any advantage to using multiple build systems?

Body:
When working on a large project which happens to have multiple build systems, (C, C++) in this case, they may use multiple build systems -- for different platforms, or for historic reasons.

With the popularity of meta-build systems, there is the opportunity to use a single build system which can generate files for different platforms.

The disadvantages for using multiple build-systems seem rather obvious...

maintenance overhead.

higher barrier of entry for developers,
(needing some experience in multiple build systems)

more files to navigate in the source repository.

Ignoring the effort it may take to do the initial migration, are there any advantages to keeping multiple build-systems in use? (when there is the opportunity to use only one?)

Said differently, if someone comes into a project and suggests to use a single cross platform build system, are there any reasonable arguments against this?

Since it was requested I be more specific, the projects I have in mind are large C/C++ code bases, using a mix of automake, MSVC-project-files, SCons & in one case CMake (which is an example of a meta-build system).


问:
In MVC, what is the difference between controller and router?
Do they mean the same thing (attaching URLs to actions, or actions to URLs) or is there any difference I'm missing?

Example: http://github.com/dannyvankooten/PHP-Router vs. http://konstrukt.dk

答:
A Frontend-Controller should collaborate with a Router and a Dispatcher to decide based on the (HTTP) request against the application which concrete Action has to be executed and then dispatches it.

Depending on how detailed a design is, some Controllers work without Routers and they do the routing their own or the routing is implicit in the design how the request is processed.

Some Dispatchers also pass a Request object to the dispatched action methods. Action-Methods then decompose themselves the Request in part so that even Controller actions still can do some routing based on the request. A typical example for this is the case when a framework offers to do a redirect as the response. This also shows how related or near Router and Controller are.

The difference that is normally drawn here is that the routing takes care of or helps with identifying which action method to execute and the controller then is responsible to provide this action but both handle the request.

As you can see, the differences between Router and Controller can vary greatly between implementations and frameworks. In the end, the concrete application has it's needs whether or not a certain level of abstraction is useful or stands in the way.

However from the terms I'd say that Controller is in a higher role in the overall application. This is where the action goes so to say.