答:
If we were to generalize the rule a bit and make it less legalistic, it might look something like this:

Limit what each module/class/function/etc knows about the rest of the system.

So you have two types of code:

Code that glues our layers of abstraction together (App)

The meat of the software that actually solves a problem (Book, Database)

Glue code exists solely so the meat code can do its work. Regardless what kind of code you're writing, you don't want your functions or modules to know too much about other areas of your software. This is for the sake of maintainability; the more pieces of code a module touches, the more likely you will have to change code in all those areas. Yuck.

Now when you're writing the "glue" code, you will obviously have to deal with modules that are spread widely throughout your software. But you're not actually using those modules. The glue code is actually quite dumb. It's calling some constructors and mostly just shuffling around references to objects. If your application gets large enough, your glue code will indeed get quite large and complex, but that's what the factory pattern is for.

So in my eyes, it's ok to traverse through multiple layers of abstraction in the glue code, so long as your glue code stays uninformed about how those layers are actually working together.

Side note:

You should look into inversion of control containers. They are great little tools that allow you to really minimize how much glue code you have to write, thereby potentially increasing maintainability.

Title: Dependency Injection vs Mixing Levels of Abstraction

Body:
I've been reading Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. One point he makes:

G34 Functions should descend only one level of abstraction

However, I'm wondering about the functions that actually create the objects for an application. Say we have dependencies

```<code>App -> Book -> Database
</code>```

Then using dependency injection, App would need to create both a Book and Database instance, and inject the database instance into Book.

Is this an acceptable breaking of the mixing level of abstraction rule?

If yes / no, why?


问:
One Event Sent to Multiple Listeners, Want to Log Notification Once

I have a system in place where a Cache is made up of many Cache Nodes.  When one is added, a CacheNodeAdded event is raised by the Cache.  The Cache has a redundant set of Monitors listening for this event.  Monitors are responsible for notifying on Cache events.

Since I have multiple Monitors, but only want to be notified once, Step 3 is what I am looking to implement.

Solutions I can't use:

Cache notifying directly.  Monitors must be used.

Have each Monitor check the log to see if the notification has been sent.  Since they all run separately, they could all access the list of notifications at the same time, see the notification hasn't been sent, and notify multiple times as a result.

Solution I'm toying with:

When event is received, get a list of all Monitor IDs (GUID), order the list, and the first Monitor in the list gets to send the notification.  This is a simple solution but it seems a little inelegant.

Are there any other simple solutions that I may be overlooking?

答:
It isn't really clear what your other monitors are for if they aren't going to be sending notifications.

Is there some reason why you can't add or have a single monitor instance that is responsible for passing on the notifications?

ContentLicense: CC BY-SA 3.0


问:
Should static data be stored in a database or somewhere else?
I'm working on some software at them moment and I'm not sure which route to take with this. I have some data to store somewhere on a mobile device. The data will never change, and has a hierarchical relationship, and will be used to populate the display. There is a reasonably amount of this data.

I have the following options:

A set of enums/objects

An XML file

The embedded SQLite database

In this particular case I think that the enums option is the least work, but I get a smell from the data being embedded in the code like that.

The XML file makes the most sense I think, but parsing it will be a resource hit that seems like a waste since it will 'never' change.

The database should provide less of a performance hit, but seems like overkill for static data.

Which is the correct design path here?

Note: By 'Never' change I mean that it will rarely change. The data in question is a model of a set of government standards, so they may well change at some point in the future but its not going to be regularly and its not going to automatically update our software either as a change in the standards could well trigger a change in our requirements.

答:
There is a chance "your" data may need to change even though the entities the data represent in the real world may not. You need to decide if it is worth it to include a separate text file of some sort that can be updated without updating the entire app.

Examples:

Typographical error / misspelling.

Accidental omission.

Offer the data in another language.

Offer a way for the user to make their own changes.

Any other type of data structure change will probably need an update to the app, so that's no benefit.


问:
Design pattern for method to accept one of several static items in C#?
I want to illustrated my question by way of a (hopefully) representative example.

Lets say I have a situation where I am developing a class library in C# to be used in some simulations.  I want to define the planets (Earth, Mars, Saturn, etc.) and have each of them have some properties and methods that are common in interface (name, signature, etc.) but unique in implementation per-each. I.e. Earth.Mass is not equal to Mars.Mass.

So far no big deal.

I want to have some other classes/methods/algorithm that accept as an argument a planet and use its defined properties and method:

```<code>double MyApparentWeight(Planet someplanet, double MassInKG)
double DistanceFromInKM(Planet someplanet, Planet originplanet)
</code>```

Planets could be used all over the place by someone using this library.  All "Earth"s should be identical and all "Saturn"s should be identical.  Obviously the "Earth"s are distinct from the "Saturn"s.

I also want a user of the library to be able to easily create a new planet (e.g. Vulcan, Endor, Tralfamadore, Persephone, Rupert, etc.).  It should be forced to supply the properties and methods of the existing ones and hence be useable by the MyApparentWeight and DistanceFromInKM methods.

So the base level approach is that there is a Planet class and then the specific ones (Earth, Vulcan, etc.) simply inherit from that.  In this case though a user needs to either create an instance of Earth and carry it around or create a new one every time it is needed.  That could be unnecessarily clunky (especially in light of the expected users) and possibly a performance hit since some Planets could have initialization steps of reading date from files, etc.

The next idea was the above but with a singleton paradigm.  That's basically what I've done so far.  This seems to be dictating internal implementation to any new Planets that are created (and again some what of a concern given the potential level of some users).

This project is how I've been cutting my C#/.NET teeth.  My initial naive approach was to try to do static classes with interfaces or inheritance.  Obviously I learned quickly the folly of that path.  At a high level that is the kind of paradigm I would have wanted though.

Is there some other design pattern that I'm missing that could cover this type of situation?

Appreciate any suggestions.

Updates

I may not have made it clear that this Planet example was only meant to be illustrative structurally and not directly representative of the actual computations.  Some people seemed to get a little wrapped up in the implementations of what data is being represented within them and other peripheral aspects.

The suggestions of the individual planets (like Earth) merely being instances of the Planet class didn't catch my points about potentially significant different implementations for their internal mechanics supporting their methods and properties. I'm also at a loss as to how it helps with not wanting to manage carrying around those instances potentially anywhere you may want to use them or having to create new instances.

Glenn's extension of Stephen's suggestion I think actually works the best in the context of what I need here.  I can couple that with rsbarro's suggestion of having static properties for the built in Planet children.  (Actually more like interface IPlanet implementers).  That provides the easiest access for the users for the most commonly used items and offers a slight performance improvement of not having to retrieve from the dictionary by name each time.  It still offers the ability for the users to dynamically add more types of Planets.

I don't yet have the rep to up-vote all of the answers I mentioned above or I would.

Thank you all for your suggestions and feedback.

答: Specifically, it seems like this exactly fits the flyweight pattern. Many of the answers have implemented this in various ways. Knowing the pattern name may help you research other possible approaches. </p>

OwnerDisplayName: kcc


问:
PHP Code base design: Single "queries.php" file, or spread queries across different php files/classes?
When I create PHP projects, is it better to put all database (e.g. MySql) queries in a single file (i.e. "queries.php")? Or is it better to place the respective queries in any "model" classes (i.e. User.php) that I may be creating? Is it bad practice to put database queries anywhere in any PHP file?

In the queries.php I would be placing functions for calling the queries.

答:
I'll leave whats 'bad practice' to the bloggers to fight over.

I personally keep queries within the business-logic objects.  So yes, User, Order, Sale, etc.  I'd find it very inconvenient if they they were all in a separate file.  That would be unnecessary added complexity and frankly kind of annoying to have to keep referring back to the file.

If for some reason you are worried about finding queries across multiple files, grep can be very helpful.


问:
JavaScript: Bundle a required, but common, polyfill in my library?
First, here are a couple of related, but not-quite-the-same questions:

Should I include dependencies for which I have the source as projects in my solution?

https://softwareengineering.stackexchange.com/questions/35052

Now on to my particular question:

I'm building a small JavaScript library. If run within certain older browsers, part of its functionality will depend on a certain polyfill. For the purposes of an example, let's say this polyfill is the requestAnimationFrame polyfill.

This polyfill is:

Well-known: Most JavaScript developers are at least vaguely aware of it.

Available: Copy-pasteable code snippets of variants of it are all over the place.

Tiny: It's only a few lines of code, really.

Endemic: Libraries in the same problem space as mine may have it bundled already.

Obviously, if my library were the only library being used in someone's project, and if part of that code could fail without the polyfill in circumstances likely for the developer's audience, it would make sense to bundle the polyfill with the library.

But in the JavaScript world, particularly in this library's domain, it's possible that the developer already has the polyfill, and that by bundling it, I could be re-polyfilling requestAnimationFrame for the second, third, fourth time over. (This itself isn't really an issue, since most polyfills by their very nature include a pre-check of the namespace. But, I admit, the thought of the same polyfill appearing multiple times in someone's code bothers me like a painting hung slightly crooked.)

So what is the sensible thing to do? Include it? Or just leave a note in the documentation that says, "By the way, make sure you have the Polyfill X if you need to support Browser Y"?

答:
Your decision will be based on the following factors:

Is there a well-known, stable, reliable Javascript library that contains the polyfill function I need, available in its externally-published API?

Is it worth the costs* to require the users of my library to take a dependency on that other library to get the required polyfill function that my library needs?

If you can't answer yes to both of those questions, grit your teeth and copy/paste the small amount of code that you need (assuming there are no licensing restrictions).

*Requiring another library will cause some code that you won't even need to be loaded in every web page.  That's not the only cost.

Further Reading

The DRY Obsession


答:
Based on your requirements, do include it. Robert Harvey has given good reasons as to why. I am going to talk about how.

You said the polyfill is tiny. But if you include it again, and several other libraries your users are also including on their pages add it, you will be adding to the issue.

You can take a couple of approaches.

The first approach would be to do what most frameworks do, have a global instance of your framework with any associated child frameworks contained in your namespace (jsLite in AngularJS comes to mind). This will guarantee that the child framework is there, works, you know where it is, and that the version you need is loaded. But it fails DRY.

The next approach is to go the global availability route, where you load the child framework into the object prototype, checking to make certain that it isn't already loaded. With this approach, you run the risk of a different revision of the child framework being loaded. As often as not, this will break your functionality due to interface breaking.

Title: JavaScript: Bundle a required, but common, polyfill in my library?

Body:
First, here are a couple of related, but not-quite-the-same questions:

Should I include dependencies for which I have the source as projects in my solution?

https://softwareengineering.stackexchange.com/questions/35052

Now on to my particular question:

I'm building a small JavaScript library. If run within certain older browsers, part of its functionality will depend on a certain polyfill. For the purposes of an example, let's say this polyfill is the requestAnimationFrame polyfill.

This polyfill is:

Well-known: Most JavaScript developers are at least vaguely aware of it.

Available: Copy-pasteable code snippets of variants of it are all over the place.

Tiny: It's only a few lines of code, really.

Endemic: Libraries in the same problem space as mine may have it bundled already.

Obviously, if my library were the only library being used in someone's project, and if part of that code could fail without the polyfill in circumstances likely for the developer's audience, it would make sense to bundle the polyfill with the library.

But in the JavaScript world, particularly in this library's domain, it's possible that the developer already has the polyfill, and that by bundling it, I could be re-polyfilling requestAnimationFrame for the second, third, fourth time over. (This itself isn't really an issue, since most polyfills by their very nature include a pre-check of the namespace. But, I admit, the thought of the same polyfill appearing multiple times in someone's code bothers me like a painting hung slightly crooked.)

So what is the sensible thing to do? Include it? Or just leave a note in the documentation that says, "By the way, make sure you have the Polyfill X if you need to support Browser Y"?


问:
Is it legal to distribute a closed source X Window Manager?
I’m doing a thought experiment about making a product on top of Linux. I’m wondering: If you make a custom window manager (akin to KDE, for example) on top of X and you release it, do you have to release it under the GPL (Linux) or MIT (X.org)? Or can you keep it closed source?</p>

答:
X-Windows is licensed under the MIT License, which is a permissive license.  Its only requirement appears to be that you include a copy of the MIT license, and do not restrict others from using the X-Windows software in any way they see fit.

The MIT License doesn't require you to make your own software open-source, nor does it prevent you from closing the X-Windows source in the context of your Window manager.


问:
Pros and Cons of RESTful architecture
The most common discussion I've seen regarding the pros and cons of REST tends to frame that discussion relative to SOAP. I have no experience in either. I am currently faced with a decision which my lack of experience is making hard for me to evaluate.
I am beginning to develop an application that has several components - primarily an administrative aspect that allows the owner to administer several sites - and a public facing user interface that allows the user to interact with data held on the host.
I need to evaluate the implications of allowing the latter part to be hosted anywhere and communicate with the former via a RESTful architecture - or demanding that both components reside on the same host.
What are the key implications of developing RESTful architecture, particularly with regards to it's capacity in the following areas:

1: Security
2: Performance
3: Interface complexity

EDIT: Looking at some of the answers to this question - I should clarify. I'm not looking for a comparison to SOAP - rather an overview of REST applications vs applications where all components reside on one host. (thanks for those answers though!)

答:
Given those areas, I can give a rough overview, but I can't draw your conclusions for you.  There are two chief areas where the two protocols differ:

Message format

Service discovery

Message format is easiest to understand.  The SOAP packaging for both requests and responses is fairly heavy weight.  There's the SOAP envelope that contains both a header and a body section.  The header can be used by several filters in the request chain to perform some sort of identification, authorization, etc.  However, XML is expensive to parse, which yields a certain penalty to the scalability of your system.  Just how much depends on the SOAP processing layer in your stack.

Service discovery is where you probably will have the most contention.  REST by its very nature provides predictable end points, and the content of the request is a simple HTTP request.  The benefit is that there is no additional overhead, and end users can pretty much guess how to do what they need once they understand the URL structure of your site.  Of course, naive security conscious people will see that as a weakness.  Afterall, with SOAP, you have to consume a WSDL to know what the endpoints are.  Of course, with SOAP you were given the entire message format so you can make more targeted attacks.

Broken down by the categories you gave:

Security

Neither is inherently more secure than the other.  Use good security principles:

Encrypt communications

Make sure you authenticate and authorize users before processing

Good coding habits to avoid direct attacks

And that's just the short list.

Remember obscurity != security.

Performance

Both raw performance and scalability will go to REST due to the request following simple HTTP protocols.  Most SOAP stacks use SAX parsing (event based parsing) which greatly improves the scalability of SOAP stacks, but there is a measurable impact to the overhead.  SOAP has the normal HTTP processing overhead in addition to the XML parsing overhead.  REST just has the HTTP processing overhead.

Complexity

From the system's perspective, REST wins.  There's fewer moving parts, a leaner request chain, etc.  That means it's easier to make reliable.

From the programmer's perspective, SOAP can win if the IDE or framework you are using provides good support for it.  Essentially, with REST the onus is on you to perform the preprocessing work (authentication/authorization/etc) while with SOAP much of that can be accomplished with a pluggable processing chain.

My Preference

I'm very comfortable with HTTP requests, and I know how the web works.  As a result, the REST approach is more preferable for me.  However, I do know that some of my clients are uncomfortable with that.  They've read some industry article denouncing the security of REST vs. SOAP, etc.  Bottom line is that neither approach guarantees security.  It's on you to make sure the application is as secure as it needs to be.  Obviously, a social web application doesn't demand (or desire) as much security as a bank or government system.  Many SOAP stacks include processors that you can plug in to provide some semblance of security, but it is still your responsibility to search them out and put them in place.

ContentLicense: CC BY-SA 2.5

Title: Pros and Cons of RESTful architecture


答:
Similar to Stephen, but for a cleaner API, use an enum for the planets and inherit the PlanetManager from Dictionary. Like so:

```<code>public enum SolSystemPlanet { Earth }

public class PlanetManager : Dictionary<SolSystemPlanet, Planet>
{
    new public Planet this[SolSystemPlanet planet]
    {
        get
        {
            if (!this.ContainsKey(planet))
                this.Add(planet, Create(planet));

            return base[planet];
        }
    }

    private static Planet Create(SolSystemPlanet planet)
    {
        switch (planet)
        {
            case SolSystemPlanet.Earth:
                return new Earth();
            default:
                throw new ArgumentException("Planet Not Supported");
        }
    }
}
</code>```

The end result is that you get planets like so:

```<code>PlanetManager planets = new PlanetManager();
Console.WriteLine(planets[SolSystemPlanet.Earth].ToString());
</code>```

Title: Design pattern for method to accept one of several static items in C#?

Body:
I want to illustrated my question by way of a (hopefully) representative example.

Lets say I have a situation where I am developing a class library in C# to be used in some simulations.  I want to define the planets (Earth, Mars, Saturn, etc.) and have each of them have some properties and methods that are common in interface (name, signature, etc.) but unique in implementation per-each. I.e. Earth.Mass is not equal to Mars.Mass.

So far no big deal.

I want to have some other classes/methods/algorithm that accept as an argument a planet and use its defined properties and method:

```<code>double MyApparentWeight(Planet someplanet, double MassInKG)
double DistanceFromInKM(Planet someplanet, Planet originplanet)
</code>```

Planets could be used all over the place by someone using this library.  All "Earth"s should be identical and all "Saturn"s should be identical.  Obviously the "Earth"s are distinct from the "Saturn"s.

I also want a user of the library to be able to easily create a new planet (e.g. Vulcan, Endor, Tralfamadore, Persephone, Rupert, etc.).  It should be forced to supply the properties and methods of the existing ones and hence be useable by the MyApparentWeight and DistanceFromInKM methods.

So the base level approach is that there is a Planet class and then the specific ones (Earth, Vulcan, etc.) simply inherit from that.  In this case though a user needs to either create an instance of Earth and carry it around or create a new one every time it is needed.  That could be unnecessarily clunky (especially in light of the expected users) and possibly a performance hit since some Planets could have initialization steps of reading date from files, etc.

The next idea was the above but with a singleton paradigm.  That's basically what I've done so far.  This seems to be dictating internal implementation to any new Planets that are created (and again some what of a concern given the potential level of some users).

This project is how I've been cutting my C#/.NET teeth.  My initial naive approach was to try to do static classes with interfaces or inheritance.  Obviously I learned quickly the folly of that path.  At a high level that is the kind of paradigm I would have wanted though.

Is there some other design pattern that I'm missing that could cover this type of situation?

Appreciate any suggestions.

Updates

I may not have made it clear that this Planet example was only meant to be illustrative structurally and not directly representative of the actual computations.  Some people seemed to get a little wrapped up in the implementations of what data is being represented within them and other peripheral aspects.

The suggestions of the individual planets (like Earth) merely being instances of the Planet class didn't catch my points about potentially significant different implementations for their internal mechanics supporting their methods and properties. I'm also at a loss as to how it helps with not wanting to manage carrying around those instances potentially anywhere you may want to use them or having to create new instances.

Glenn's extension of Stephen's suggestion I think actually works the best in the context of what I need here.  I can couple that with rsbarro's suggestion of having static properties for the built in Planet children.  (Actually more like interface IPlanet implementers).  That provides the easiest access for the users for the most commonly used items and offers a slight performance improvement of not having to retrieve from the dictionary by name each time.  It still offers the ability for the users to dynamically add more types of Planets.

I don't yet have the rep to up-vote all of the answers I mentioned above or I would.

Thank you all for your suggestions and feedback.

Body:
Similar to Stephen, but for a cleaner API, use an enum for the planets and inherit the PlanetManager from Dictionary. Like so:

public enum SolSystemPlanet { Earth }

public class PlanetManager : Dictionary<SolSystemPlanet, Planet>
{
    new public Planet this[SolSystemPlanet planet]
    {
        get
        {
            if (!this.ContainsKey(planet))
                this.Add(planet, Create(planet));

            return base[planet];
        }
    }

    private static Planet Create(SolSystemPlanet planet)
    {
        switch (planet)
        {
            case SolSystemPlanet.Earth:
                return new Earth();
            default:
                throw new ArgumentException("Planet Not Supported");
        }
    }
}

The end result is that you get planets like so:

PlanetManager planets = new PlanetManager();
Console.WriteLine(planets[SolSystemPlanet.Earth].ToString());


问:
Should we test all our methods?
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

答:
When faced with a philosophical quesion, drop back to the driving requirements.

Is your goal to produce reasonably reliable software at a competitive cost?

Or is it to produce software of the highest possible reliability almost regardless of cost?

Up to a point, the two goals of quality and development speed/cost align: you spend less time writing tests than fixing defects.

But beyond that point, they don't. It's not that hard to get to, say, one reported bug per developer per month. Halving that to one per two months only releases a budget of perhaps a day or two, and that much extra testing probably won't halve your defect rate. So it is no longer a simple win/win; you have to justify it based on the defect cost to the customer.

This cost will vary (and, if you want to be evil, so will their ability to enforce those costs back to you, whether through the market or a lawsuit). You don't want to be evil, so you count those costs back in full; sometimes some tests still globally make the world poorer by their existence.

In short, if you try to blindly apply the same standards to an inhouse website as passenger airliner flight software, you will end up either out of business, or in jail.

Title: Should we test all our methods?


答:
There are few types of unit testing:

State based. You act and then assert against state of the object. E.g. I make a deposit. I then check to see if balance has increased.

Return value based. You act and assert against return value.

Interaction based. You verify that your object called another object. This seems to be what you are doing in your example.

If you were to write your test first, than it would make more sense - as you would expect to call a data access layer. Test would fail initially. You would then write production code to make the test pass.

Ideally you should be testing logical code, but interactions (objects calling other objects) are equally important. In your case, I would

Check that I called data access layer with exact parameter that has been passed in.

Check that it's been called only once.

Check that I return exactly what's been given to me by data access layer. Otherwise I might as well return null.

Currently there is no logic there, but it won't always be the case.

However, if you are confident that there will be no logic in this method and it's likely to stay the same, than I would consider calling data access layer directly from consumer. I would do this only if the rest of the team are on the same page. You don't want to send a wrong message to the team by saying "Hey guys, it's fine to ignore domain layer, just call the data access layer directly".

I would also concentrate on testing other components if there was an integration test for this method. I'm yet to see a company with solid integration tests though.

Having said all this - I wouldn't blindly test everything. I would establish the hot spots (components with high complexity and high risk of breaking). I would then concentrate on these components. There is no point in having a codebase where 90% of codebase is quite straightforward and it's covered by unit tests, when remaining 10% represent core logic of the system and they are not covered by unit tests due to their complexity.

Finally, what's the benefit of testing this method? What are the implications if this doesn't work? Are they catastrophic? Don't strive to gain high code coverage. Code coverage should be a by product of good suite of unit tests. For example you may write one test that will walk the tree and give you 100% coverage of this method, or you can write three unit tests that will also give you 100% coverage. Difference is that by writing three tests you test edge cases, as opposed to just walk the tree.

Title: Should we test all our methods?

Body:
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?


答:
The question to ask for any data is not whether it will change; you probably don't know, and even if you did, the answer would likely be misleading.

The question to ask is, when it changes, who should change it:

the software author: put it in code

the end user: have an option on the GUI

someone else (e.g. a system integrator, internationalisation service, etc.): database table, file or whatever makes sense (including sometimes an extension API).

Tuesday should generally be an enum not because it can never change. But because if an insane dictator did take charge and demand Tuesday be named after him, you as the software author will have to change it (or be fed to the sharks).

You wouldn't want all your users to have to go digging into config files or obscure database tables to avoid that fate...

Title: Should static data be stored in a database or somewhere else?

Body:
I'm working on some software at them moment and I'm not sure which route to take with this. I have some data to store somewhere on a mobile device. The data will never change, and has a hierarchical relationship, and will be used to populate the display. There is a reasonably amount of this data.

I have the following options:

A set of enums/objects

An XML file

The embedded SQLite database

In this particular case I think that the enums option is the least work, but I get a smell from the data being embedded in the code like that.

The XML file makes the most sense I think, but parsing it will be a resource hit that seems like a waste since it will 'never' change.

The database should provide less of a performance hit, but seems like overkill for static data.

Which is the correct design path here?

Note: By 'Never' change I mean that it will rarely change. The data in question is a model of a set of government standards, so they may well change at some point in the future but its not going to be regularly and its not going to automatically update our software either as a change in the standards could well trigger a change in our requirements.


答:
The problem its the question itself, you don't need to test all the "methdos" or all the "classes" you need to test all the features of your systems.

Its key thinking of terms of features/behaviors instead of thinking in terms of methods and classes. Of course a method its here for providing support for one or more features, at the end all your code its tested, at least all the code matters in your code base.

In your scenario, probably this "manager" class its redundant or unnecessary (like all the classes with a name that contains the word "manager"), or perhaps not, but seems like an implementation detail, probably this class do not deserve a unit test because this class has not any relevant business logic. Probably you need this class for some feature to work, the test for this feature covers this class, this way you can refactor this class and have test that verify that the thing that matters, your features, still works after the refactor.

Think in features/behaviors not in method classes, i cannot repeat this enough times.

Title: Should we test all our methods?


问:
What kind of webservice can be called with just a browser url?
Can a webservice be written in such a way that it can be called via just a browser url?

For eg. if the webservice is called GetStockQuote, then it should be callable by the following url on the browser

```<code>http://myserver.com/WebServices/GetStockQuote?sym=MSFT
</code>```

Likewise, if there are more params, they can be passed via the URL.

Unlike this one - http://www.webservicex.net/stockquote.asmx - where it doesn't look like the param can be passed via a URL. It seems to require either a program or a human to type in the param & click on invoke.

Or does it always require a client program? Is there a way from the wsdl to figure out whether it can be called from a browser or not.

How can I program a webservice which fulfils the above criteria?

答:
Of course a web service can be called directly by the browser! It's called a RESTful web service. Any RESTful API that uses the GET method (as opposed to POST, which is what your example uses), can be navigated to by typing in the URL. Here's an example:

http://rxnav.nlm.nih.gov/REST/rxcui?name=lipitor

This API, from the National Institutes of Health, gets a prescription identifier for a drug based off its name (here, "Lipitor").

In order to program a web service that acts in this way, you have to write a response to an HTTP GET request--however you want to approach that, in whatever language you want (if you provide more details, I'd be happy to help). The other thing about GET requests is that they are only supposed to retrieve data; they cannot have side effects of any kind. For those kinds of requests, you would need to use POST, DELETE, etc., which can't simply be typed into a browser.


答:
If you have a wsdl, you're probably coding to a C# wrapper that abstracts away all of the HTTP responses into a standard SOAP envelope.  Which I hear works fairly well if everyone speaks the same variety of SOAP any you don't really want emergent cross-platform mashups incorporating your service.

Assuming that you're using the afore presumed C#, you can write a "RESTful" service simply by leveraging the classic ASP roots of ASP.NET and making a page that returns a body of XML or JSON.  Bonus points for including an option for either, and either using an established schema or providing a human-friendly XSL.

(And if you're not using ASP.NET, much the same practice can serve in PHP, Node, JSP or what have you.  And you can probably find a pure C# library to do the same if you really look.)

Title: What kind of webservice can be called with just a browser url?

Body:
Can a webservice be written in such a way that it can be called via just a browser url?

For eg. if the webservice is called GetStockQuote, then it should be callable by the following url on the browser

```<code>http://myserver.com/WebServices/GetStockQuote?sym=MSFT
</code>```

Likewise, if there are more params, they can be passed via the URL.

Unlike this one - http://www.webservicex.net/stockquote.asmx - where it doesn't look like the param can be passed via a URL. It seems to require either a program or a human to type in the param & click on invoke.

Or does it always require a client program? Is there a way from the wsdl to figure out whether it can be called from a browser or not.

How can I program a webservice which fulfils the above criteria?


问:
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?

In other words, how to prevent a user from creating more than one user account in a site?

What's this problem called? Is there any specific name to this problem? What are the solutions? Thanks.

答: The task as stated is impossible.  You might be able to come acceptably close depending upon your ability to compel evidence (ssn, drivers license, birthdate, etc).  But unless you're a govermental site, most people will just go elsewhere.</p>


问:
Why should I use node.js as http server?
I know what node.js is & what it does.

What I really want to know is how does it work as an http server?

A server like apache gets a request, fork a process, allocate memory to process, handle the request & release the process after it is completed. If we get thousands of http requests at a time, then apache waits for the the process queue to release process.

How does node.js with a single threaded environment handles so many http requests. All the incoming requests are given their own event loop. All these event loops share same memory.

How does using node.js to handle millions of http requests more scalable than using apache?

答:
With non-blocking code, you can issue a request for file-system or database, then instead of waiting for the response, you go on and serve another user and then another. Later you come back to first user (whose request was pending) and you serve him.

In summary, this is something like this:

```
user1 makes a request -> Node issues a call to file-system or database.
user2 makes a request -> Node serves the request immediately as there is no waiting call.
user3 makes a request -> Node serves the request immediately as there is no waiting call.
                         call to filesystem or database completes and Node serves user1.
```

Body:
With non-blocking code, you can issue a request for file-system or database, then instead of waiting for the response, you go on and serve another user and then another. Later you come back to first user (whose request was pending) and you serve him.

In summary, this is something like this:

user1 makes a request -> Node issues a call to file-system or database.
user2 makes a request -> Node serves the request immediately as there is no waiting call.
user3 makes a request -> Node serves the request immediately as there is no waiting call.
                         call to filesystem or database completes and Node serves user1.


问:
How to choose data storage method for user generated data?
In a program I am writing, I have 3 different ways to store user generated data:

```<code>(a) XML Files for each object (.Net Serialization)
(b) SQL Database (MSSQL)
(c) Massive terrifying blob of data in 1 file (I'm against this one)
</code>```

There is absolutely no theoretical difference in performance or file size in this (hypothetical) scenario, but which would be best to use?

Is SQL overkill (Considering that there will be up to 2 million items in database), or the best option? Where does the line get drawn between BLOB, XML, and SQL?

The index would either link to the filename (a GUID) or a SQL item id (a GUID), so there is not difference in search functionality. The XML is stored in multiple files and file size is not much of a concern, so you would not need to parse the entire thing to access a specific item (Just open a file stream to {GUID}.xml)

Edit: I'm adding some more info to make it more clear what I'm asking.

I am working on a program for a client who is in the perfume design industry. In all cases, the search index will be separate (Someone else's code that I don't dare touch), and will be indexed in memory.

Random access of data isn't needed in this case, as people would be pulling up the full information for a single item.

In a much more clear way of saying: If you do not need to access random data in a database, and XML is easier, is it ok to use that instead of an SQL file?

Edit II: Either way, it will be installed on a large server, so, I am not concerned about the client having access to MSSQL or not having enough space for ~1KB extra per entry (If not using SQL).
Edit III: I am only doing single select all queries (E.g. SELECT * FROM (DB) WHERE ID = (GUID)) Or (Xml.deserialize((GUID).xml))

答:
Ultimately, it comes down to what the data will look like and how it will be used.

However, if there will be 2 million items, SQL is almost certainly the best choice of those three.

Text files have no random access, so if you want to access item 1,999,999, you will have to read through the entire file to get to it.  And there is no reason to roll your own storage format when this problem has been solved already.

The benefit of XML serialization is ease of use: you can transfer seamlessly from variables in memory to data in storage, without having to worry about it.  However, XML files are an inefficient way to store large amounts of data.  The XML syntax itself often takes up more space than the data.  And, again, there is no random access, because it is stored in a text file.  An XML file is actually worse for random access than a flat text file, because by definition you have parse the entire file to access any part of it--unlike a text file, where you can at least access the first line quickly.  Dividing the content into multiple files helps, but then you have a multi-level access strategy where you first have to locate the correct file, then parse the file to get to the content you want.

An SQL database is easy to set up and use, and if you are worried about "overkill", there are lightweight versions available, like SQLlite.  Also, an object relational mapper can handle some of the complexity of managing data in the database for you, if you are worried about that.


答:
The problem is called "identification". The token uniquely identifies a person and you want to prevent people from obtaining multiple identities.

The best solution we have for that are government passports and ID cards, or rather the methods used to distribute them, which mostly rely on cross-checking public records, especially birth records. But it's certainly not impossible to circumvent - criminals often obtain multiple (valid, non-forged) identities by exploiting loopholes in the system.

The closest you can come as a website operator is to depend on this system - some countries (e.g. Germany) have government ID cards that include a cryptographic ID which can be used for authentication by third parties, even over the internet (but usually require the website operator to register with the government as well). A low-tech version of this is to establish a physical presence and require people to show up in person and present their government ID.

If, as is most likely the case, you cannot do any of that (especially since none of it can easily be done internationally) - you just have to accept that it's impossible to prevent people from obtaining multiple identities, and plan your system around that fact.

Body:
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?

In other words, how to prevent a user from creating more than one user account in a site?

What's this problem called? Is there any specific name to this problem? What are the solutions? Thanks.


问:
Characterization in Testing: Unit test or Functional test
So I'm trying to push for more automated testing in my company, which focus a lot on prototype and proof of concept systems.

We currently use Google Test for unit testing. This tests specific test cases for correctness, but a lot of the stuff we do the metrics for how the code is performing follow more of a  "does it work better or worse than before, and if it works worse, is it an acceptable loss in performance" task than a boolean "yes no". These tests I call "Characterization" for lack of a better term (I've got a EE background, so sue me): it describes how the code behaves. We NEED to have the metric for all builds, and we NEED to be able to compare it between builds in order to see what direction we are heading. We can often make a general cuttoff to make a high-level pass fail, but these tests can be extensive: they take a long time to run and often require number crunching and plotting stuff. This seems to be out of scope for a Unit Test, more for a Functional Test in my mind (but I'm no test expert). How do people/companies handle this type of test? Is there any framework for this type of test out there?

答:
How do people/companies handle this type of test?

There are many kind of testing, but your interests are unit and functional :

unit tests - needs to be very fast, in order to be execute on every change in the code. Their purpose is to test modules.

functional tests - they are similar to unit tests, except they do not need to be fast. They are executed when working on them, when there are no changes in the trunk for few hours, or when doing nightly builds.

Is there any framework for this type of test out there?

To do nightly builds, and to execute them when there are no activity in the trunk for few hours,, people are using frameworks like jenkins.


问:
Dynamic git URL for Jenkins builds
We internally use GitHub Enterprise and Jenkins. If I push on the main repository it is automatically build without and the Commit is marked as correct (just as Travis does this).

However, I want to be able to fork a repository and let the Jenkins build run. Is it possible to say Jenkins that he also runs any fork of the project when opening a PR on the main repo?

答:
There's a mercurial plugin for Jenkins that does this, it works by polling on all branches for updates to the configured project, and building whichever branch changed. Makes sense to me, and I wish it was updated to work with git and subversion.

IIRC Bamboo (the JIRA CI server) does this out-of-the box.

However, if you want this to occur if you forked the repository, ie you take code from repoA and put into repoB, then no - how would any system recognise that your project is ancestrally related to a different repository?

Title: Dynamic git URL for Jenkins builds


问:
Forking GPL project: Do I have full rights on the new fork or still dependencies with the original owner(s)
I am considering the creation of a fork to a small project licensed under GPLv2, and I have some very specific questions I did not manage to answer in my research on various sites and forums.

When I fork the code, I am forced to release the new project under the same license (GPL) as I will do, but could I also decide to release it under a dual license, one of them commercial?

When forking the project, do I automatically own the copyright of the whole thing? This is relevant when, for example, deciding a future change in the license, or to be able to enforce the GPL license to a 3rd party

答:
Your forked project is a derivative of the original project's code.  In other words, your project is using the original project, and thus you are bound by its license.  If this were not true, a license would have no point at all.

So, no, you can't release code under a proprietary license if it is derived from code that doesn't allow that.


问:
Tight Coupling Between Javascript, HTML, and CSS: A More Modern Approach?
It's very common to see Javascript bound to certain selectors to find elements, store data, and listen for events. It's also common to see these same selectors used for styling.

jQuery (and its selector engine Sizzle) support and promote this by referencing elements with CSS-type syntax. As such, this technique is particularly difficult to 'unlearn' (or refactor) when building out projects.

I've come to understand that this is a result of the history of HTML and Javascript development, and that browsers have been built to efficiently consume / parse / and render this sort of coupling. But as websites become increasingly complex, this reality can introduce difficulties in organizing and maintaining these separate layers.

My question is: can and should this be avoided in modern websites?

If I'm new to front-end development, and I wish to learn things 'the right way,' is it worth learning to decouple and avoid such dependencies from the start? Does this mean avoiding jQuery in favor of a library that promotes a more decoupled structure?

答:
Martin Fowler describes one approach to this as the Segregated DOM, where you separate your DOM JavaScript from your page logic JavaScript.</p>

```<code>Application Logic <----> DOM Manipulation <----> DOM / HTML
</code>```

Body:
Martin Fowler describes one approach to this as the Segregated DOM, where you separate your DOM JavaScript from your page logic JavaScript.

Application Logic <----> DOM Manipulation <----> DOM / HTML


问:
Dependency Injection vs Mixing Levels of Abstraction
I've been reading Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. One point he makes:

G34 Functions should descend only one level of abstraction

However, I'm wondering about the functions that actually create the objects for an application. Say we have dependencies

```<code>App -> Book -> Database
</code>```

Then using dependency injection, App would need to create both a Book and Database instance, and inject the database instance into Book.

Is this an acceptable breaking of the mixing level of abstraction rule?

If yes / no, why?

答:
Let's start by defining what an abstraction is. In Agile Principles, Patterns, and Practices, Robert C. Martin defines an abstraction like this:

Abstraction is the elimination of the irrelevant and the amplification of the essential

What is essential, and what is irrelevant, changes with the client's perspective. From the perspective of the Composition Root, the relevant abstractions are types (classes, primitives, etc.) and the graph(s) composed from objects.

The purpose of the Composition Root is to construct a valid object graph. In that perspective, all types have the same level of abstraction. They're just types being composed together; the Composition Root doesn't invoke any of the object members, so it's irrelevant whether the object originates from a UI package, a Data Access package, a Domain Model package, etc. The abstraction is Composition.


答:
The short answer: When you fork an existing project, you generally do not have permission to change the license nor do you get copyright on the code you copied over.

You do have the copyright on any (nontrivial) modifications or additions that you make.

The long answer:

The only ways to get copyright on a piece of code is by writing it yourself or by contractually getting the copyright assigned to you.
This means that forking an existing project doesn't change the copyrights on the code of either the original project or the fork.

The only people who can change a copyright license are the holders of that copyright. If there are multiple copyright holders to the code of a project, then all copyright holders must agree to a change in the copyright license. This means that you don't have permission to change the license of your fork (not even to dual license it), unless the existing copyright license explicitly gives you the right to sublicense the code.

Title: Forking GPL project: Do I have full rights on the new fork or still dependencies with the original owner(s)

Body:
I am considering the creation of a fork to a small project licensed under GPLv2, and I have some very specific questions I did not manage to answer in my research on various sites and forums.

When I fork the code, I am forced to release the new project under the same license (GPL) as I will do, but could I also decide to release it under a dual license, one of them commercial?

When forking the project, do I automatically own the copyright of the whole thing? This is relevant when, for example, deciding a future change in the license, or to be able to enforce the GPL license to a 3rd party


答:
You are talking about performance, which is essentially an Non Functional Requirement.

My view is that most of these are for the whole system.

A user is never going to say "I want the WidgetListCollection class to return a widget within 20 nanoseconds" -- he might say "I want a list of all products on my screen within 1.5 seconds".

The only way to really test these is to test the complete system. If the users screen is refreshed within .25 of a second exceeding the NFR by 600% than it does not really matter if the WdigetListCollection class is sub-optimal. Any effort spent optimizing it could be best spent elsewhere doing something that matters to the user.

Worse if you test this stuff at unit test level not only does it encourage you to waste time on micro-optimizations, your test may raise false alarms:

Say I may make a change to the class so it is now 5 times slower, however, it now also caches the widget usage history thus making the entire system run twice as fast. But I get nagged at the weekly meeting for poor performance anyway.

Unit testing is good. But it has its limits, in the end its the system as a whole that must work to spec. Be aware that the system can still fail miserably even though all the individual components are excellent.

Title: Characterization in Testing: Unit test or Functional test

Body:
So I'm trying to push for more automated testing in my company, which focus a lot on prototype and proof of concept systems.

We currently use Google Test for unit testing. This tests specific test cases for correctness, but a lot of the stuff we do the metrics for how the code is performing follow more of a  "does it work better or worse than before, and if it works worse, is it an acceptable loss in performance" task than a boolean "yes no". These tests I call "Characterization" for lack of a better term (I've got a EE background, so sue me): it describes how the code behaves. We NEED to have the metric for all builds, and we NEED to be able to compare it between builds in order to see what direction we are heading. We can often make a general cuttoff to make a high-level pass fail, but these tests can be extensive: they take a long time to run and often require number crunching and plotting stuff. This seems to be out of scope for a Unit Test, more for a Functional Test in my mind (but I'm no test expert). How do people/companies handle this type of test? Is there any framework for this type of test out there?


问:
What is the meaning of MODULE_LICENSE_BSD_LIKE in Android source code?
In Android source code, we see files like MODULE_LICENSE_APACHE2, MODULE_LICENSE_BSD_LIKE, MODULE_LICENSE_W3C. An outside observer would think that these specify the intended license that applies to the source code tree where this file resides.

Take the JSON module, for instance. It has an empty file MODULE_LICENSE_BSD_LIKE, which might indicate that the JSON module is licensed under one of BSD licenses. However, sources themselves say that they are licensed under Apache License 2.0, as seen in JSON.java.

Packagers of this library for Fedora, as well as other operating systems like Debian, consider the library to be licensed as Apache License 2.0. This seems reasonable, as an empty file bears no legal weight.

However, MODULE_LICENSE_BSD_LIKE is apparently there for a purpose. What is that purpose?

答:
DejaCode* appears to have wondered this same question.  This is what they found:

Empty marker files named MODULE_LICENSE_xxx (where xxx is a license "key") are stored in the codebase side-by-side or close to the code they document.

  Typically, the presence of such a file indicates that the code in a current directory has a given license identified by xxx in the MODULE_LICENSE_xxx file name

As to why this is being done, this is what they said:

The Android Open Source Project re-uses a large number of third-party software components under several different licenses (typically Open Source Initiative-approved licenses). ... Internally, the Android team uses specific conventions and techniques to document the origin and license of third-party components within the codebase itself.

So the empty files are there to help the android development team keep track of the original license of the code that they incorporated into the project.

The rest of the DejaCode article is worth reading as it describes the use of the NOTICE and property (.prop) files.

* The DejaCode website does not exist anymore. Archived version.

ContentLicense: CC BY-SA 4.0


答:
Here is a different way of looking at the problem.  You have a site membership list and a new applicant. How do you know if this applicant already has an account on your website?

The short answer is that you can never be certain...  ...but there are things that can be tested.  Can you validate any of the personal information they provided? A common one is sending an email that they have to click on the link to confirm that the email address is theirs.  but what about their home address?  send a letter with a code there that they have enter on the website (or a QL code they can scan).  What about another website that can vouch for their identity - facebook login etc...? Are their details on the electoral register?

Some sites have used approaches such as requiring photos of driving license or passport where there are legal reasons for knowing your customer.

Title: How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?


问:
Alternatives to inheritance on complex structures?
I'm working on an ASP.NET Webforms project, using the MVP Pattern (which the presenters as you may know use a Page Controller pattern). I'm given a rather complex inheritance chain for my controllers. Below I depict a small example of the structure I'm facing (it is way bigger structure in my app):

A lot of code among these controllers is duplicated (i.e. creating cookies in RegisterPageController and LoginPageController, access Customer data in ProfilePage and BuyProductPage...), so I decided to systematically apply Template pattern and create an inheritance structure that would allow me to reuse as much of the code as possible (i.e. Creating an AuthenticatedPageController that checks that the user is authenticated and then BuyProductPage and ProfilePageController inherits from this class, reusing the authentication part of the code).

However, as I progress refactoring my code and apply more Template pattern, the inheritance chain starts to become more and more complex, and sometimes trying to create a new hierarchy among all my other classes becomes too tedious.

I was wondering if there was a better approach to tackle my issues. I've been reading about composition (I read this post Alternative to "inheritance versus composition?") but I'm not sure about how to implement it nor if this would be the best approach for my case.

Can anyone enlighten me?

Thank you.

答:
If several controllers need cookie control then let them hold a CookieController that will handle that.

There is no need for the BuyProductController to also be a AccountController just because it needs the billing address.


答: You might also want to take a look at the C# Decorator Pattern, which may be useful for sharing functionality between classes without complex inheritance.</p>

Title: Alternatives to inheritance on complex structures?

Body:
I'm working on an ASP.NET Webforms project, using the MVP Pattern (which the presenters as you may know use a Page Controller pattern). I'm given a rather complex inheritance chain for my controllers. Below I depict a small example of the structure I'm facing (it is way bigger structure in my app):

A lot of code among these controllers is duplicated (i.e. creating cookies in RegisterPageController and LoginPageController, access Customer data in ProfilePage and BuyProductPage...), so I decided to systematically apply Template pattern and create an inheritance structure that would allow me to reuse as much of the code as possible (i.e. Creating an AuthenticatedPageController that checks that the user is authenticated and then BuyProductPage and ProfilePageController inherits from this class, reusing the authentication part of the code).

However, as I progress refactoring my code and apply more Template pattern, the inheritance chain starts to become more and more complex, and sometimes trying to create a new hierarchy among all my other classes becomes too tedious.

I was wondering if there was a better approach to tackle my issues. I've been reading about composition (I read this post Alternative to "inheritance versus composition?") but I'm not sure about how to implement it nor if this would be the best approach for my case.

Can anyone enlighten me?

Thank you.


问:
What are the advantages of strictly maintaining separate data | algorithm | interface layers?
I always separate the user interface from other functionality in my programs - its the way I have been taught, and it has obvious advantages since you can change the interface but keep the same functionality.

However, I've come across some programmers who strictly separate data, algorithms and interface.  So the data objects which hold the data in volatile memory have only fields/properties and their getters and setters.  Any algorithms are kept in a separate class.

In my view the main disadvantage of this is that the algorithm classes usually need full access to the data in the data classes. You might want to have a more functional class which you create with lots of data but then objects from other classes can only get at that data in specialised ways.

答:
When you encapsulate data, you're limiting yourself to only being able to perform a limited number of operations on it. But often there's an unbounded number of things you want to do with data.

Suppose we're writing a simple role-playing game. Let's write a Weapon class and examine what happens if we hide all its data.

```<code>public class Weapon {
    private int damage;
    private int accuracy;

    public Weapon(int damage, int accuracy) {
        this.damage = damage;
        this.accuracy = accuracy;
    }
}
</code>```

Naturally, we want to be able to hit people with the weapon. So we need a function that calculates the damage we'll do to the enemy. But all the weapon's variables are private, so we'll have to turn that function into a method.

```<code>public int hitEnemy(Enemy theEnemy) {
    return theEnemy.getDefense() - this.damage;
}
</code>```

We'll also need a way to determine if we succeeded in our attack. Again, this'll become a method.

```<code>public boolean tryToHit(Enemy theEnemy) {
    return random() > (theEnemy.getEvasion() - this.accuracy);
}
</code>```

Later on we find that we want to compare two weapons to see which one has more damage. Another method.

```<code>public Order compareDamage(Weapon other) {
    if (this.damage > other.damage) {
        return Order.GREATER;
    } else if (this.damage < other.damage) {
        return Order.LESS;
    } else {
        return Order.EQUAL;
    }
}
</code>```

A few days later we decide that a weapon's price should be determined based on its damage and accuracy...

```<code>public int getPrice() {
    return 10 * this.damage + 0.5 * this.accuracy;
}
</code>```

The following week we want to give weapons ratings from C to A based on their stats...

```<code>public Rating getRating() {
    if (accuracy/10 + damage > 10) {
        return Rating.A;
    } else if (accuracy/10 + damage > 5) {
        return Rating.B;
    } else {
        return Rating.C;
 }
</code>```

As you can see, every time we need to do anything new with the weapon, we need to throw that into the weapon's class to get at its variables. That's bad - it violates the Open/Closed Principle, which states that code should be open to extension and close to modification. If we had turned Weapon into a plain old data object - a simple record with nothing but public data - we'd be able to add functions to use weapons in new ways without having to modify the Weapon class.

When you design an abstraction X, you must distinguish between things X does and things I can do with X. Our weapons don't do anything, so there's no implementation details to hide. Hiding all their data behind private variables is about as useful as a list that doesn't let you access its elements. Our game will definitely need some encapsulation and abstraction, but it should be implemented at a higher layer, in the game logic proper.

Body:
When you encapsulate data, you're limiting yourself to only being able to perform a limited number of operations on it. But often there's an unbounded number of things you want to do with data.

Suppose we're writing a simple role-playing game. Let's write a Weapon class and examine what happens if we hide all its data.

public class Weapon {
    private int damage;
    private int accuracy;

    public Weapon(int damage, int accuracy) {
        this.damage = damage;
        this.accuracy = accuracy;
    }
}

Naturally, we want to be able to hit people with the weapon. So we need a function that calculates the damage we'll do to the enemy. But all the weapon's variables are private, so we'll have to turn that function into a method.

public int hitEnemy(Enemy theEnemy) {
    return theEnemy.getDefense() - this.damage;
}

We'll also need a way to determine if we succeeded in our attack. Again, this'll become a method.

public boolean tryToHit(Enemy theEnemy) {
    return random() > (theEnemy.getEvasion() - this.accuracy);
}

Later on we find that we want to compare two weapons to see which one has more damage. Another method.

public Order compareDamage(Weapon other) {
    if (this.damage > other.damage) {
        return Order.GREATER;
    } else if (this.damage < other.damage) {
        return Order.LESS;
    } else {
        return Order.EQUAL;
    }
}

A few days later we decide that a weapon's price should be determined based on its damage and accuracy...

public int getPrice() {
    return 10 * this.damage + 0.5 * this.accuracy;
}

The following week we want to give weapons ratings from C to A based on their stats...

public Rating getRating() {
    if (accuracy/10 + damage > 10) {
        return Rating.A;
    } else if (accuracy/10 + damage > 5) {
        return Rating.B;
    } else {
        return Rating.C;
 }

As you can see, every time we need to do anything new with the weapon, we need to throw that into the weapon's class to get at its variables. That's bad - it violates the Open/Closed Principle, which states that code should be open to extension and close to modification. If we had turned Weapon into a plain old data object - a simple record with nothing but public data - we'd be able to add functions to use weapons in new ways without having to modify the Weapon class.

When you design an abstraction X, you must distinguish between things X does and things I can do with X. Our weapons don't do anything, so there's no implementation details to hide. Hiding all their data behind private variables is about as useful as a list that doesn't let you access its elements. Our game will definitely need some encapsulation and abstraction, but it should be implemented at a higher layer, in the game logic proper.


问:
Solutions to problems that .NET can solve better than Java (or vice-versa)
To me it seems these are two different platforms that address similar enterprise(but not only) problems. I'm interested however in problems that Java can solve better than C#/.NET or C#/.NET can solve better than Java. Leaving aside the 'cost' factor, since that is somehow not an issue for big enterprise companies (the developers probably cost more than the licenses from Microsoft - it's just a thought) and even for small projects there are free/open-source tools for .NET so the cost can be zero for the .NET world as well. With Mono, you can port .NET to Linux and MacOS as well so the benefit that Java had(cross platform) isn't THE decision factor to use Java nowadays..

What real world problems can you think of where .NET would be a much better solution than Java, and vice-versa? I'm only interested in solutions to problems.

答:
I don't think there is any class of problem domain that begs for one or the other. Some platforms can't run .NET, such as certain smart phones and so J2ME has some more portability.

In the enterprise space, I usually see this decision based on the experience of the team, or if its a new group/project then the experience of its initial managers.

In my team, we have a lot of both .NET and J2EE. This is mostly for the reason that there are different strengths in terms of the existing open source projects we can use; and we have vendor runtime platforms that require one or the other. We do all our UI work in .NET; most of our integration and search platform is hosted on Java. Our middleware is a mixed bag. I'm sure this horrifies some people but it really gives us a lot of flexibility and saves us a lot of time in the end because we can leverage the best products in their problem domain, not just on our platform.


答:
It's called a Plain Old Data Structure (PODS).  They are fairly common in places where data first enters a system from an external source, like a database.  In effect their single responsibility is to abstract that external data into a form that's easier for higher layers to consume.

In other words, it allows programmers of higher layers to work with familiar native objects rather than having to sprinkle accesses to the external source throughout the code.  That data is read into the system in one place, and only that one place must change if the interface to the external source changes.

Like any principle, it can be taken too far.  If they're commonly using a PODS on internal-only data, it's probably misguided in OOP.  Note however that passing around a PODS is a fairly common pattern in functional programming, for better or worse.

Title: What are the advantages of strictly maintaining separate data | algorithm | interface layers?

Body:
I always separate the user interface from other functionality in my programs - its the way I have been taught, and it has obvious advantages since you can change the interface but keep the same functionality.

However, I've come across some programmers who strictly separate data, algorithms and interface.  So the data objects which hold the data in volatile memory have only fields/properties and their getters and setters.  Any algorithms are kept in a separate class.

In my view the main disadvantage of this is that the algorithm classes usually need full access to the data in the data classes. You might want to have a more functional class which you create with lots of data but then objects from other classes can only get at that data in specialised ways.


问:
Is there a way to not use the Observer pattern when creating GUI systems?
In Java, the Swing library implements the Observer/Subscriber-Publisher design pattern to design the way the program responds to events on the GUI (button clicks, etc).

The programmer registers ActionListener objects (the observers) to a GUI element (the subject/observable/publisher), and these objects get notified by the GUI element when it's state is changed, and do something accordingly.  This seems a reasonable way to design a GUI system, and I can't think of any other way a framework could do this.

Is there any other way to design an event-response system in a GUI?  Are there any imperative-language frameworks or libraries with a GUI event-response system not designed this way? Does the event-response system in the most common C# GUI library implement event-response issues using Observer, or something else? What about libraries for Python, etc.

答:
Swing also allows you to inherit the panels and override the Process*Event methods from the core Container class , you need to enable the events first though.

This is only a good idea if you are creating a new complex widget though


答:
There's functional reactive programming. The idea is to turn time-varying entities into first-class objects. Suppose we're dealing with a mouse cursor, and we want to draw an icon 10 pixels to the right of the cursor. Imagine that there was a type TimeVarying<T> that represents a value that changes over time. TimeVarying always magically contains the current value of that quantity. So instead of registering a callback and doing a bunch of imperative things to grab the current mouse position and update the position of the icon, imagine the mouse position was a TimeVarying<Point>. Then, we could write something like...

```<code>iconX = mousePosition.x + 10;
</code>```

And the iconX variable would also be a time-varying quantity. Whenever the mousePosition changes, iconX would change, much like cells in a spreadsheet. Naturally, there needs to be something that's keeping all these values current and propagating the changes in a safe and efficient way.

For more details, see the paper Deprecating the Observer Pattern.

I know functional reactive programming frameworks exist, but I don't know if there's any mature frameworks for Java.

Title: Is there a way to not use the Observer pattern when creating GUI systems?

Body:
In Java, the Swing library implements the Observer/Subscriber-Publisher design pattern to design the way the program responds to events on the GUI (button clicks, etc).

The programmer registers ActionListener objects (the observers) to a GUI element (the subject/observable/publisher), and these objects get notified by the GUI element when it's state is changed, and do something accordingly.  This seems a reasonable way to design a GUI system, and I can't think of any other way a framework could do this.

Is there any other way to design an event-response system in a GUI?  Are there any imperative-language frameworks or libraries with a GUI event-response system not designed this way? Does the event-response system in the most common C# GUI library implement event-response issues using Observer, or something else? What about libraries for Python, etc.

Body:
There's functional reactive programming. The idea is to turn time-varying entities into first-class objects. Suppose we're dealing with a mouse cursor, and we want to draw an icon 10 pixels to the right of the cursor. Imagine that there was a type TimeVarying<T> that represents a value that changes over time. TimeVarying always magically contains the current value of that quantity. So instead of registering a callback and doing a bunch of imperative things to grab the current mouse position and update the position of the icon, imagine the mouse position was a TimeVarying<Point>. Then, we could write something like...

iconX = mousePosition.x + 10;

And the iconX variable would also be a time-varying quantity. Whenever the mousePosition changes, iconX would change, much like cells in a spreadsheet. Naturally, there needs to be something that's keeping all these values current and propagating the changes in a safe and efficient way.

For more details, see the paper Deprecating the Observer Pattern.

I know functional reactive programming frameworks exist, but I don't know if there's any mature frameworks for Java.


问:
Help understanding server-side scripting
As far as I understand, there are basically 3 options for doing server-side scripting these days:

Using scripting languages that can be directly interpreted/executed by the web server (e.g., PHP and ASP), where the scripts are interpreted/executed on the fly (i.e., as HTTP requests come), the output is embed into HTML pages is then sent back to the client.

Using any language (e.g., C, C++, PERL, Python) the operating system of the server is capable of executing (either using an interpreter or using the executable file already compiled) and then using CGI to communicate between the web server and the OS. Output of the scripts comes via CGI to the server in the form of complete HTML pages, and is then sent back to the client.

Using Java on a server that can handle servlets/JSPs, which is pretty much the same idea as option 1 above, except using Java instead of PHP/ASP.

Questions:

Is my understanding so far on track, or did I get something wrong?

Are ASP and PHP the only languages that can be interpreted and executed directly by a web server?

Where does Ruby fall in the classification above? Can it be interpreted/executed by servers like PHP? Or does it communicate via CGI?

Is server-side scripting via CGI becoming obsolete or not at all?

答:
There is a 4th option, that's used in the most 'serious;' web sites like banks or other financial services: the n-tier approach which is a little like CGI, except the CGI process runs on a different server, the webserver code is very thin (just enough to reformat data into html) and calls the 'cgi' services via network protocols such as RPC or SOAP.

Its still the same basic approach that uses a webserver as a gateway between the http request made by the client browser and a 'code engine' that hosts business logic. Note that in this case the webserver will pass the request to a scripting engine in one language (eg PHP or XSLT) that in turn calls another service that provides it with raw data, the web script is used solely to format that data into the html page that is delivered to the browser.


问:
How to apply IoC (or something similar) to a constant?
I have the following class with the following members:

```<code>public class RegistrationPresenter : EPiPresenter<IRegistrationView, LoginPage>, IDisposable
{
    private readonly static string[] DefaultUserRoles = { AppRoles.RegisteredRole, AppRoles.EveryoneRole, AppRoles.ManagerUserRole };

    private readonly INavigator navigator;
    private readonly ISpanishProvincesHelper spanishProvincesHelper;
    private readonly IContentHelper contentHelper;
    private readonly IUserDataHelper userDataHelper;

    public RegistrationPresenter(IRegistrationView view, LoginPage page, INavigator navigator,
        ISpanishProvincesHelper spanishProvincesHelper, IContentHelper contentHelper, IUserDataHelper userDataHelper)
        : base(view, page)
    {
....
 }
</code>```

I'm successfully able to Bind all the readonly members with an IoC container (Ninject in my case), except for the static string[], which I don't know how to do it. Which approach should I choose or how could I apply IoC to the DefaultUserRoles values, so I'm able to mock it when Unit testing?

答:
1) are you sure you need to mock your constant?

2) Use Microsoft Fakes, which will happily replace your string with a different one at test-time (an approach that works beautifully when testing more real-world problems, such as mocking the current date/time)

(of course, if you use Fakes, you wouldn't have needed to bother with ninject :) )


问:
Should I pass array or pointer?
I am writing a C++ library (but prefer C style interface functions) and one of the function returns array of floats. I am not sure if I should pass pointer or fixed array to get this data?

```<code>// in the library header file
#define MAX_ITEMS_SIZE   1000

int getData(float * data, int &size );
</code>```

or

```<code>int getData(float (&data)[MAX_ITEMS_SIZE], int & size )
</code>```

If I am passing the pointer, the client should allocate MAX_ITEMS_SIZE for it. Is that a reasonable and fair expectations? Passing it as array forces the client to pass the max memory required. Which one is better?

Some more background, the MAX_ITEMS_SIZE is the maximum number of floats that can be returned. In reality the array will contain less items which is filled in the size parameter. The function returns int which is error code where zero means no error.

My overall goal is how to return the data which is array of floats in easy to understand and reliable way. Even though I am using C++, I would like to stick with C interface functions so the library can be used more widely.

答:
Typically you would see

```<code>size_t getDate(float* buffer, size_t bufferSize);
</code>```

The return value is the amount of data returned and you pass in how large your buffer actually is.

EDIT: In your comments to want to have an error return code and remain C compatible, if so I suggest doing like Doc brown suggested:

```<code>int getDate(float* buffer, size_t bufferSize, size_t &dataSizeReturned);
</code>```

Title: Should I pass array or pointer?

Body:
Typically you would see

size_t getDate(float* buffer, size_t bufferSize);

The return value is the amount of data returned and you pass in how large your buffer actually is.

EDIT: In your comments to want to have an error return code and remain C compatible, if so I suggest doing like Doc brown suggested:

int getDate(float* buffer, size_t bufferSize, size_t &dataSizeReturned);


答:
I am writing a C++ library

So why don't you use C++ instead of C?

```<code>   getData(std::vector<float> &data);
</code>```

is most probably what you want. And even when programming in C, do yourself a favor and avoid to use fixed limits like MAX_ITEMS_SIZE, that number will almost be too big (wasting resources) or too small (which means your program might not work as intended).

Title: Should I pass array or pointer?

Body:
I am writing a C++ library (but prefer C style interface functions) and one of the function returns array of floats. I am not sure if I should pass pointer or fixed array to get this data?

```<code>// in the library header file
#define MAX_ITEMS_SIZE   1000

int getData(float * data, int &size );
</code>```

or

```<code>int getData(float (&data)[MAX_ITEMS_SIZE], int & size )
</code>```

If I am passing the pointer, the client should allocate MAX_ITEMS_SIZE for it. Is that a reasonable and fair expectations? Passing it as array forces the client to pass the max memory required. Which one is better?

Some more background, the MAX_ITEMS_SIZE is the maximum number of floats that can be returned. In reality the array will contain less items which is filled in the size parameter. The function returns int which is error code where zero means no error.

My overall goal is how to return the data which is array of floats in easy to understand and reliable way. Even though I am using C++, I would like to stick with C interface functions so the library can be used more widely.

Body:
I am writing a C++ library

So why don't you use C++ instead of C?

   getData(std::vector<float> &data);

is most probably what you want. And even when programming in C, do yourself a favor and avoid to use fixed limits like MAX_ITEMS_SIZE, that number will almost be too big (wasting resources) or too small (which means your program might not work as intended).


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Take it down 1

It's your work and it's unpaid. What happens if you take a car off the lot and fail to pay? They take it back. Better do it now while you can then regret it later. Why would it not be ethical to take back something that is yours?

Hopefully a down site will motivate them to pay you. Otherwise you are in a bit of a bind. No matter who you work for get a contract or something in writing. Friends, family, the only exclusion would be your mother because honestly you probably won't be charging her anyways.

I'm opposed to warning him only because that will prompt him to remove your access, and prevent you from taking any action. What good is the warning if you can't follow through?

1: Please be aware of the possible legal consequences that may present themselves in following this course of action. This information is provided "as-is". The author cannot not be held liable for the results of following any part of the above stated recommendation. By reading this you are affixing an assumed electronic signature that you agree to all terms, as stated, without reservation. If any part of this agreement is found unlawful, I don't really care. Just adding fine print for fine prints sake.

Title: How to get money from reluctant client?


问:
Pull Frequency Parameters in MVC architecture
Assume a simple SPA (Single-page application), maybe a dashboard and these basic conditions:

The Model contains methods for accessing and displaying data;

The View contains methods to load templates and apply model.data to  template;

The Controller manages the user commands;

The Router handles the navigation;

In our example, we will make sure that the user can configure the dashboard to update itself every N seconds pulling new data from back-end (pullFrequency).

In which component is proper set up the pullFrequency parameter:

Model?

View?

Controller?

Router?

Somewhere else?

答:
Presumably the pullFrequency parameter is used client-side to set up the polling; if you're happy to restrict yourself to browsers that support HTML5 then the cleanest solution may be to have a sensible default in your page and if the user wants to update it, pop it in Local Storage ( see http://diveintohtml5.info/storage.html ). That way your main application can be completely oblivious to the setting - after all it's not relevant to anything server-side.

The downside of this approach is that it needs to be set separately on each device the user uses - but that's not necessarily bad, a user may want rapid refresh on his desktop with super-fast line, but much less on his tablet / phone when out on the move.


问:
Where to put variables needed across classes?
I have 3 classes: a JButton extension, FButton; a JTextField; and a JPanel extension, FPanel, that would contain one instance of both.

The FButton is supposed to open a file, and make the file name and directory for the file available.

The JTextField is meant to display the file name and directory provided by FButton.

I figured FPanel should be the one containing the file name and directory.  If I make FButton and JTextField private classes of FPanel, problem solved with public variables.  How about if I want to separate them into a public FPanel class, a package visible FButton class, and a package visible JTextField class, within the same package?  How can I make the file variables available to all classes in the package?

Should I be doing it that way?

答:
I think the difficulty arises because you have view (Swing) objects storing application state. In a desktop application I know the controller and view sometimes are merged partially or entirely, but the model should still be separate.

When developing such applications, I like to use the following approach:

Some code (could be main, an event listener, whatever) triggers a new view into existence.

A factory of some sort constructs the MVC elements:

View: prefer to use standard Swing classes and assemble them together.

Model: create an object to handle one of two types of data. One, persistent state which was likely passed on from the enclosing controller. Two, state which is used by this new view (temporary objects that may be shared).

Controller: construct more listeners and attach them to the view objects. They will also typically have references to the model objects so they can act on them.

Next, wire everything up. Add listeners to the view. Use common objects between them when appropriate so they can see the same data and all update the view as necessary.

I believe you are asking the wrong question: using the above approach may be able to solve your dilemma (I cannot say for sure, I do not see your code).

I also highly recommend avoiding global variables, static state, etc. I like to create Context objects which contain state applicable to the entire application or portion thereof which would normally be a "global variable" to a less experienced developer. This context contains only those variables which are truly needed to be shared across objects, such as the current file (or file abstraction), logged in user, or other state that can legitimately affect all objects in an application or module.

Reducing coupling like that makes individual elements more reusable. While the code may be more verbose and (at first) difficult to follow, it really does streamline it and make it easier in the end. Remember your SOLID principles.


问:
What are the hardest parts of the C++/C#/Java programming languages?
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)

答:
The hardest thing for me to grasp in C# were delegates and lambdas. I use to write all my LINQ queries using the SQL query format. Since I've been learning F#, the C# lambdas have become much, much easier and I really enjoy them. All it took for delegates was a little concentrated effort (which required me to not be lazy) and then they made sense.

Overall, I don't think the C# libraries are that big of an issue (unless you talk about 3rd party ones) since Microsoft has thorough documentation (IMO).

OwnerDisplayName: tom


答:
Forget about the GPL for a moment, and look at copyright. When you fork a project, all code that was present in the original project is copyright of whoever wrote that code in the original project. All code that you write afterwards is your copyright. So unless you re-write all the code from the original project, that code isn't yours and you have no legal rights.

Next you look at the GPL license, and check what rights it gives you beyond the rights of copyright law. It allows you to create derivative works which makes the whole forking business legal in the first place - with plain copyright law, you wouldn't be allowed to create a derivative work. Next, it allows you to use the code as long as you don't distribute it. So as long as nobody else can lay their hands on the forked code, GPL allows you to do what you want with it.

However, if you distribute the forked code, including someone else's copyrighted code, you only have the permission of the copyright holder if you follow their rules. One rule is that you must license the whole code under the GPL (including your own). Another rule is that you must give the source code to others; check the GPL for details.

Changing the license would be difficult, as long as any of the original code is still there. You cannot license your code in a way that prevents the next guy from using the code in the way that GPL allowed, you also can't allow them to do things with the code that GPL doesn't allow.