答:
SVN's branching is as free as Git's. It's just a bit of housekeeping data that says where the branch starts, no changes to the stored files whatsoever. A 'copy' in SVN is like adding a symlink to a Unix directory. Note that the SVN branch will not require a network trip until you commit your working copy changes (but there's not much point having a SCM if you don't commit off-local at some point).

Note that a Git branch will also involve some housekeeping - like adding that tag internally - that will have to be stored somewhere when you commit. It's not a big deal at all, which is why it's called 'free'.


问:
Best practices for sharing tiny snippets of code across projects
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.

答:
i have run into issue a lot, and my prefered solution is to post the code in a github/pubic web-enabled repository. it solves a lot of problems -

easy access and easy to share. cvs/svn/enterprise-repos mean checking out project into multiple IDE workspaces, and sometimes having to switch workspaces or computers just to refer to a small code snippet.

assuming these snippets of code are not proprietary/classified pieces of code and are variations of publicly available knowledge, posting them on a public repo like github means others will look at it, and might even contribute.

posting something in the public domain under your name has the added pressure of reputation. you will double check and update things, since it reflects on your abilities as a programmer.

updates. the thing about maintaining code snippets in a repo is, if a snippet hasn't been used in a long time, it might go stale (contain outdated apis/libs). example - java code snippet to read a file. you might have figured out the best way to do this in 2009, but in 2014 a new file api comes out that changes everything. your snippet? still stuck in 2009. in a public repo, things will get updated, either by you (because bullet 3), your teammates, or some member of the general programmer population, and in the process, you might even get suggestions to fix something that you might have been doing wrong for a long time.

One thing i would recommend- no matter where you keep your snippets, always google stuff up before you use it. things change all the time. saved snippets save time, but also breed complacency.

ContentLicense: CC BY-SA 3.0


问:
user's requirements verification, howto?
My question is: How can you verify the users' requirements early in the software creation process?

I show the user specifications, prototypes, demos... but still users forget to share some "insignificant details" about the process or business rules and data. Which pops up after the final test as some "really small and rare exceptions" - which are turned into change request and accumulate a lot of work.

So how do you prototype (or verify) users requirements early in the project?

答:
You need to let users know that the later a 'requirement' is identified in the project, the more it will cost. They may decide that they don't really need the change after all. If they insist on the changes, but refuse the extra costs/time delay, you have a problem that needs to be negotiated. That is not going to be solved through technology or planning but by sales and client relationship management.

Continuously getting working software in front of them AND requiring them to make the effort to use/test/evaluate is your best bet. They won't fully comprehend contracts, specs, diagrams, and user stories.

This is part of the Joel Test. Grab anyone you can find to test the software as much as possible throughout the entire development process.

ContentLicense: CC BY-SA 2.5


问:
Best practices for versioning project after dependency upgrade
Say, my project have dependency N with version 1.0.0.
Then something have changed, and I should depend on newer version - let it be 1.0.1.

OK, I'm incrementing dependency version, nothing else changes in my code.
It looks like I should increment my own projects' version, but how exactly I should increment?

Should I increment only third number (so-called revision), or best practices here are more complicated. For example, may be, if we are changing projects' dependency minor value, we should do the same thing in the project itself?

答:
Semantic Versioning is an attempt to codify the way version numbers ought to work.

In a nutshell:

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,

MINOR version when you add functionality in a backwards-compatible manner, and

PATCH version when you make backwards-compatible bug fixes.

According to this, you shouldn't care about whether the change in the final product was due to changes in your code or changes in a dependency. If it adds functionality, change the minor version, if it doesn't, change the patch version, if it makes no difference at all (maybe you're not using the part of the dependency that changed), I think you don't need to update the version number at all.


问:
Should we design programs to randomly kill themselves?
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.

答: You might want to search for "proactive recovery" and "rejuvenation" in the context of fault-tolerant distributed systems, to deal with arbitrary faults (i.e., not only crashed processes, but corrupted data and potentially malicious behavior too). There has been a lot of research on how often and in what conditions should a process (in an abstract sense, may actually be a VM or a host) be restarted. Intuitively, you can understand the advantages of the approach as preferring to deal with a dead process than with a traitor process...


答: I've recently thought about this and what occurred to me was a large library of common methods as has been mentioned thus far, but with a twist. The library project would allow you to configure at compile time which pieces are included kind of like the BusyBox project. With that approach, you can have a kitchen sink style library repo, but only grab the tools you need when compiling.</p>

Title: Best practices for sharing tiny snippets of code across projects

Body:
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.


问:
What does "branching is free" mean in Git?
What does "branching is free" mean in Git?

I hear this a lot whenever Git is mentioned in comparison to other version control systems.

I haven't had the opportunity (?) to deal with others (SVN, etc.), so how is branching "expensive" in others?

答:
It is 'free' (in this context 'free' really means quick and easy and not taking up space) because in some older version control systems a branch was a complete copy of the code at that point, so branches took up a lot of space and it was easy to end up with a lot of different completely full versions of the software lying around, which then took management.  In others it wasn't a complete copy of the code but every file still needed to be modified for a tag so was slow and painful ('costly').

git's branches are essentially labels pointing at a commit and thus avoid the above issues.


问:
Go with an object-oriented perspective
My OOP JavaScript question is at the very bottom if you want to skip my introduction.

In an answer to  the question Accessing variables from other functions without using global variables, there's a comment about OOP that says:

If there's a chance that you will reuse this code, then I would
  probably make the effort to go with an object-oriented perspective.
  Using the global namespace can be dangerous -- you run the risk of
  hard to find bugs due to variable names that get reused. Typically I
  start by using an object-oriented approach for anything more than a
  simple callback so that I don't have to do the re-write thing. Any
  time that you have a group of related functions in javascript, I
  think, it's a candidate for an object-oriented approach.

That rings true to me from what I've seen some of my old OOP colleague.  There are lots of different approaches and different voices leading in different directions. Since I am a front end developer and UI designer, I am a little confused.

Building up to the question
I've heard from a variety of places that global variables are inherently nasty and evil, when doing some non-object oriented Javascript, and that there are three choices available to make a variable from one function, visible and usable by another function, e.g., function A to be visible to function B; or, a variable of Function A to be passed and usable within function B.

make it a global

make it an object property, or

pass it as a parameter when calling B from A.

I've read about namespaces, currying, and other approaches...

Question:
With that all said, I was wondering what's the best OOP structure or best code practice in JavaScript that keeps things encapsulated and adds greatest security from having your variables exposed to manipulation?

答:
You can only do so much with JavaScript

No matter what framework you use, JavaScript simply does not have a method to mark properties of a user-defined object as protected or hidden.  If a function can get a reference to your object, that function can change any part of that object.

So do the best with what you have.

If you want to protect against cross-function manipulation, either pass lightweight objects as parameters or spool one up before you release your exclusive lock.

If you want to have anything in JS be secure, put it on the other side of the HTTP call.  (And if you're making a client-side-only app, put your secure code outside of your javascript object.)

If you want to protect against accidental over-use (which is why globals are evil), pick a framework or write your own, and follow it religiously.

Some advice on doing that

Write anything not trivial as an object.  That is, if it's more than two lines of code, it should be an method of some custom object on the global namespace (or a child thereof.)

Non-trivial event handlers should call methods of objects instead of doing the work themselves. (More than two statements is likely "non-trivial.")

Methods should ONLY affect their own object's properties and their parameters.

When possible, avoid having the methods of an Objects do more than call that object's other methods, that object's parent's methods, or that object's children's methods.

Seriously, pick a framework.  jQuery is just one answer, and for OOP isn't as snazzy as either prototype or enyo

OOP's real benefit to JS isn't encapsulation.  It's testability.  When picking a framework, lean towards one that includes a good test harness for your new code.  (Or, heck, write one yourself.  They're not THAT hard.)

Title: Go with an object-oriented perspective


答:
Take a look at Douglas Crockford's article on private members in JavaScript. To hide variables, your only real option is to create a closure in which they're scoped. For example, in a browser:

```<code>;(function() {

    // secret is only visible to definitions inside this function
    var secret = "secret";

    // secretWrapper's functions "close over" secret so they retain
    // access even after this enclosing function executes.
    window.secretWrapper = {
        getSecret: function() {
            return secret;
        },
        setSecret: function(val) {
            secret = val;
        }
    };

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

Avoiding global namespace pollution is a noble goal, but ultimately your code needs to be attached to something, either the global object (window in the browser) or a DOM object (which is attached to the global object).

Remember that this doesn't make your code more secure or free from manipulation. In the browser, anyone can overwrite your implementations whenever they feel like it. It can make your code more maintainable, however. It allows you to break a problem into pieces that only need be aware of their smaller responsibility.

Title: Go with an object-oriented perspective

Body:
My OOP JavaScript question is at the very bottom if you want to skip my introduction.

In an answer to  the question Accessing variables from other functions without using global variables, there's a comment about OOP that says:

If there's a chance that you will reuse this code, then I would
  probably make the effort to go with an object-oriented perspective.
  Using the global namespace can be dangerous -- you run the risk of
  hard to find bugs due to variable names that get reused. Typically I
  start by using an object-oriented approach for anything more than a
  simple callback so that I don't have to do the re-write thing. Any
  time that you have a group of related functions in javascript, I
  think, it's a candidate for an object-oriented approach.

That rings true to me from what I've seen some of my old OOP colleague.  There are lots of different approaches and different voices leading in different directions. Since I am a front end developer and UI designer, I am a little confused.

Building up to the question
I've heard from a variety of places that global variables are inherently nasty and evil, when doing some non-object oriented Javascript, and that there are three choices available to make a variable from one function, visible and usable by another function, e.g., function A to be visible to function B; or, a variable of Function A to be passed and usable within function B.

make it a global

make it an object property, or

pass it as a parameter when calling B from A.

I've read about namespaces, currying, and other approaches...

Question:
With that all said, I was wondering what's the best OOP structure or best code practice in JavaScript that keeps things encapsulated and adds greatest security from having your variables exposed to manipulation?

Body:
Take a look at Douglas Crockford's article on private members in JavaScript. To hide variables, your only real option is to create a closure in which they're scoped. For example, in a browser:

;(function() {

    // secret is only visible to definitions inside this function
    var secret = "secret";

    // secretWrapper's functions "close over" secret so they retain
    // access even after this enclosing function executes.
    window.secretWrapper = {
        getSecret: function() {
            return secret;
        },
        setSecret: function(val) {
            secret = val;
        }
    };

})();

Avoiding global namespace pollution is a noble goal, but ultimately your code needs to be attached to something, either the global object (window in the browser) or a DOM object (which is attached to the global object).

Remember that this doesn't make your code more secure or free from manipulation. In the browser, anyone can overwrite your implementations whenever they feel like it. It can make your code more maintainable, however. It allows you to break a problem into pieces that only need be aware of their smaller responsibility.


问:
How to get different resources in a single endpoint in RESTful?
I have a REST webservice that have a couple of resources, like Company and User. But now I need to make a modification to the API to return a special list combining company, user and maybe other type of resource. Like a list of recommendations with various type of resources.

Which is the best approach to solve this?

I need to make a new endpoint (resource), something like: /recommendations? I already have the /company endpoint, and the /user endpoint returning the corresponding objects. This is fine. But now I need some way to return an array with a combination of users and companies.

Also I'm thinking that the json will look like an array of objects, but how the client can know which type of object is parsing if every object in the array is a different resource?

EDIT

I want that my client could show a recomendations screen in the app. The problem is that this list can combine multiple types of data (users, companies). It doesn't matter if this resources have a relationship or not.
The client shoud recive a json like that:

```<code>"recomendations": [
    {
        "id_user": 1
        "name": "Jean"
        ...
    },
    {
        "id_company": 2
        "name": "Starbucks"
        ...
    },
    ...
]
</code>```

答:
Map your Recommendation resources to /recommendations and then use this structure:

```<code>{
   "users" : [
           { .. },
           { .. }, ..
    ],
   "companies" : [
           { .. },
           { .. }, ..
    ]
}
</code>```

It allows the consumer to parse it properly based on the name (users or companies for instance).

Body:
Map your Recommendation resources to /recommendations and then use this structure:

{
   "users" : [
           { .. },
           { .. }, ..
    ],
   "companies" : [
           { .. },
           { .. }, ..
    ]
}

It allows the consumer to parse it properly based on the name (users or companies for instance).


答:
I disagree with the accepted answer for many reasons.

In my experience, when I see "miscellaneous" libraries like the accepted answer, they're an excuse to reinvent the wheel (or not invented here(NIH)) - a far greater sin than violating Dont Repeat Yourself (DRY).

Sometimes violating DRY can be a reasonable compromise, it is better than introducing tight coupling. Reuse is a secondary concern compared to good object oriented design. A bit (I mean small amount, apply the Rule of Three) of duplication is easier to understand than a spaghetti code base.

The approach of numerous general purpose libraries sets a bad example. It leads to a fine granularity of assembly and too many assemblies is bad. I recently reduced an in-house from 24 libraries to 6 libraries. It improved the compile time from several minutes to ~20 seconds. Visual studio is also slower to load and less responsive with more assemblies. Having too many libraries also leads to confusion as to where code should live; prefer fewer, simpler rules.

Why is the stuff in the .Net Framework not good enough? The Framework is pretty big; many times I've seen code that re-implements stuff that already exists there. Really make sure that your frameworks are filling gaps in the .Net framework and dont just exist for aesthetic reasons (for example "I don't like the .Net framework here" or perhaps some premature optimization)

Introducing another layer into your architecture has a significant complexity cost. Why does the layer exist? I've seen false reuse, by that I mean that, the code is built on top of an in-house framework. It would have been far more efficient to implement it directly on top of standard libraries.

Using standardized technologies (like the .Net framework and popular 3rd party/open source libraries) have benefits that often outweigh the comparative technological gains of building it yourself. It is easier to find talent that knows these technologies and your existing developers will invest more in learning it.

My recommendations:

Do not to share this code.

Create a new library if it has a cohesive purpose do not use the ball of mud design pattern.

Reuse existing 3rd party libraries where possible.

Prefer fewer assemblies, with simpler rules as to where code should live.


答:
Start by not getting rid of intermediates like business analysts, because they are actually trained in this. If you don't have such people, accept that at least one of your developers is going to need to develop this skill.

Next, over time, accumulate a set of instincts about the sorts of things people often ask for late in projects, and bring them up in conversation early in the project. "Will the discount always be the same for all orders, or does it vary by customer?" "Can every user see every report, or are some just for supervisors?" "Is the sales tax always the same, or does it depend where the customer is?" and so on.

In addition, try to write your code so it's insulated from these kinds of changes coming late, because some will still come in late no matter what. If you have business logic in the click handlers for your buttons, these changes really hurt. If you have business logic in a specific class whose name makes it easy for you to find it, and you can leverage polymorphism to, say, have regular orders and rush orders and each order calculates its own shipping charge, then the change they've asked for is much less painful.

You cannot prevent late changes. Laws change, business drivers (customers, what sales is promising, the great idea the CEO has while reading something on the plane) change. Prevent what you can and embrace the rest by designing your code to be changeable.

Title: user's requirements verification, howto?

Body:
My question is: How can you verify the users' requirements early in the software creation process?

I show the user specifications, prototypes, demos... but still users forget to share some "insignificant details" about the process or business rules and data. Which pops up after the final test as some "really small and rare exceptions" - which are turned into change request and accumulate a lot of work.

So how do you prototype (or verify) users requirements early in the project?


问:
Can too much abstraction be bad?
As programmers I feel that our goal is to provide good abstractions on the given domain model and business logic. But where should this abstraction stop? How to make the trade-off between abstraction and all it's benefits (flexibility, ease of changing etc.) and ease of understanding the code and all it's benefits.

I believe I tend to write code overly abstracted and I don't know how good is it; I often tend to write it like it is some kind of a micro-framework, which consists of two parts:

Micro-Modules which are hooked up in the micro-framework: these modules are easy to be understood, developed and maintained as single units. This code basically represents the code that actually does the functional stuff, described in requirements.

Connecting code; now here I believe stands the problem. This code tends to be complicated because it is sometimes very abstracted and is hard to be understood at the beginning; this arises due to the fact that it is only pure abstraction, the base in reality and business logic being performed in the code presented 1; from this reason this code is not expected to be changed once tested.

Is this a good approach at programming? That it, having changing code very fragmented in many modules and very easy to be understood and non-changing code very complex from the abstraction POV? Should all the code be uniformly complex (that is code 1 more complex and interlinked and code 2 more simple) so that anybody looking through it can understand it in a reasonable amount of time but change is expensive or the solution presented above is good, where "changing code" is very easy to be understood, debugged, changed and "linking code" is kind of difficult.

Note: this is not about code readability! Both code at 1 and 2 is readable, but code at 2 comes with more complex abstractions while code 1 comes with simple abstractions.

答:
Yes, definitely.  The thing is, no abstraction is perfect.  All of the details of the layer that abstractions sit atop are there for a reason, and it can simplify a lot of things, but if that complexity wasn't necessary at some point, it probably wouldn't be there in the first place.  And that means that at some point, every abstraction is going to leak in some way.

And that's where the real problem lies.  When abstractions fail, the more of them you have layered in between the code you wrote and what's actually going on, the harder it is to figure out the problem and fix it, because there are more places where the problem might be.  And the more layers there are, the more you have to know in order to track it down.

Title: Can too much abstraction be bad?


问:
Javadoc for a static "overloaded" method
My problem is the following:

I have an interface that requires its implementations to implement a static method, namely void load(). However, until Java 8, it seems we won't get static methods in interfaces. I trust my users to still implement it correctly, but my problem is how to write a proper doc.

There are up to 50 implementations of this interface and not being able to inherit the javadoc is a bother.

What is the best way to proceed in my case? Should I document a random implementation and add @see annotations in the others? It seems dirty to me.

Any suggestion is welcome.

答:
As you stated, there isn't a way (until Java 8) for an interface to require a static method.  There also isn't a way to override a static method, so which documentation could actually be inherited?

I see a few options:

If the documentation on the interface describes the method (which I would expect - how are implementers supposed to know about the load() method?), have the docs of all implementations link to it:

/** required static method as expected by {@link Loadable} */

If there is a sane default implementation for the load() method, put it in an abstract class implementing the interface and have the docs for all implementations link to it (rather than just a random implementation):

/** @see AbstractLoadable#load() */

Extract the polymorphic functionality in the load() method to a non-static method.  The interface can then explicitly require the new method, and javadoc will automatically inherit the documentation from the interface.  (I realize this might not be a viable option)


答:
The very first words of The C++ Programming Language, 4th edition:

All problems in computer science
can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler

(David Wheeler was my thesis advisor. The quote without the important last line is sometimes called "The first law of Computer Science.")

Title: Can too much abstraction be bad?

Body:
As programmers I feel that our goal is to provide good abstractions on the given domain model and business logic. But where should this abstraction stop? How to make the trade-off between abstraction and all it's benefits (flexibility, ease of changing etc.) and ease of understanding the code and all it's benefits.

I believe I tend to write code overly abstracted and I don't know how good is it; I often tend to write it like it is some kind of a micro-framework, which consists of two parts:

Micro-Modules which are hooked up in the micro-framework: these modules are easy to be understood, developed and maintained as single units. This code basically represents the code that actually does the functional stuff, described in requirements.

Connecting code; now here I believe stands the problem. This code tends to be complicated because it is sometimes very abstracted and is hard to be understood at the beginning; this arises due to the fact that it is only pure abstraction, the base in reality and business logic being performed in the code presented 1; from this reason this code is not expected to be changed once tested.

Is this a good approach at programming? That it, having changing code very fragmented in many modules and very easy to be understood and non-changing code very complex from the abstraction POV? Should all the code be uniformly complex (that is code 1 more complex and interlinked and code 2 more simple) so that anybody looking through it can understand it in a reasonable amount of time but change is expensive or the solution presented above is good, where "changing code" is very easy to be understood, debugged, changed and "linking code" is kind of difficult.

Note: this is not about code readability! Both code at 1 and 2 is readable, but code at 2 comes with more complex abstractions while code 1 comes with simple abstractions.

ContentLicense: CC BY-SA 4.0


问:
What is a license and how may I use code under a license?
(Let me edit this question to try to better get across what I am asking.)

I don't understand what a license is and how I may "use" it. From the little that I do understand, there are two situations:

One writes a program/source code and puts a license on it. The license says how other people may (are allowed) to use the program/source code.

I find a program/source code and would like to use it. The program comes with a license and the license tells me how I am allowed to use the program/source code.

It is this second point that I am confused about. I have no experience with "using" licenses. I see some previous questions about licenses being closed, so just to make it clear: I am not asking for legal advice. I just want to make sure that I am doing it "right". I just want to know how one can use a license.

To given a concrete real world example of what I am asking:

I want to use the library CryptoJS 3.1 to make a web page (to put online for the whole world to see) using this library, but I am uncertain about how I may do this.

From what I understand: according to the page about the library, the the library is offered under a license called the New BSD License.

But I don't understand what this license is telling me about how I am allowed to use the source code. Specifically, I would appreciate if someone could explain (as if I was a 12 year old):

What do I need to do to use this library on my web page?

For example: Do I need to give tribute with a link or something like that?

One specific thing that is confusing me is that on the page of CryptoJS 3.1 it actually doesn't tell me what the license is verbatim. It says that the license is the New BSD license. There is a link to this page. And one that page is a template for a license.

So how do I make sense of this?

In summary: I would like to use CryptoJS 3.1, but I don't know how I may do that.

(I have figured out the export regulations requirement, so that isn't an issue for me.)

答: You just have to post the source code if you make any changes, but it is free to use.</p>

OwnerDisplayName: Thomas

OwnerDisplayName: dakillakan


答:
In order to use CryptoJS, you must follow the terms of its license.  Which means that you can either use the js files directly from http://crypto-js.googlecode.com as shown in their examples, save those files locally and distribute them yourself from your own server, save those files locally and make any sort of adjustment you want to them, or even compile your JavaScript to an executable or obfuscate your entire project to your heart's content.

What you CANNOT do, however, is remove the copyright license from the start of each JS file, or violate any of the rest of the terms at the license URL linked therein.

http://code.google.com/p/crypto-js/wiki/License

Assuming that you just want to make a website and include direct links as shown in the cryto-js examples, you don't need to do ANYTHING else.

(Whether or not you could use someone's js file via direct linking without their permission is an entirely different question, and not what you're asking here.)

Again, YOU DO NOT NEED TO RE-LICENSE YOUR CODE.  Either your website in part or in whole or any modifications that you make to Crypto-JS.  So long as you preserve their copyright notice and liability disclaimer, you can do whatever you want with it.

Title: What is a license and how may I use code under a license?

Body:
(Let me edit this question to try to better get across what I am asking.)

I don't understand what a license is and how I may "use" it. From the little that I do understand, there are two situations:

One writes a program/source code and puts a license on it. The license says how other people may (are allowed) to use the program/source code.

I find a program/source code and would like to use it. The program comes with a license and the license tells me how I am allowed to use the program/source code.

It is this second point that I am confused about. I have no experience with "using" licenses. I see some previous questions about licenses being closed, so just to make it clear: I am not asking for legal advice. I just want to make sure that I am doing it "right". I just want to know how one can use a license.

To given a concrete real world example of what I am asking:

I want to use the library CryptoJS 3.1 to make a web page (to put online for the whole world to see) using this library, but I am uncertain about how I may do this.

From what I understand: according to the page about the library, the the library is offered under a license called the New BSD License.

But I don't understand what this license is telling me about how I am allowed to use the source code. Specifically, I would appreciate if someone could explain (as if I was a 12 year old):

What do I need to do to use this library on my web page?

For example: Do I need to give tribute with a link or something like that?

One specific thing that is confusing me is that on the page of CryptoJS 3.1 it actually doesn't tell me what the license is verbatim. It says that the license is the New BSD license. There is a link to this page. And one that page is a template for a license.

So how do I make sense of this?

In summary: I would like to use CryptoJS 3.1, but I don't know how I may do that.

(I have figured out the export regulations requirement, so that isn't an issue for me.)


问:
Are there mainstream general-purpose non-Turing complete languages available today?
Non-Turing complete languages offer a great advantage over Turing-complete languages as they are much more analyzable and, thus, offer much broader optimization possibilities. Yet they are barely used and Turing-completeness is actually sold as a good feature.

Are there any mainstream non-Turing-complete languages available today that are made for general-purpose programming?

答:
There are no mainstream multi-purpose non Turing complete languages today. There are, however, several non Turing complete domain specific languages. ANSI SQL, regular expressions, data languages (HTML, CSS, JSON, etc), and s-expressions are some notable examples.

There isn't really a benefit for multi-purpose non Turing complete languages. The "much more analyzable" aspect, which I'm assuming is a nod to Rice's theorem, does apply but it doesn't make much sense for languages that target several different application domains, other requirements take precedence. The flexibility of Turing completeness is a lot more important than its complexity. Programming languages, as every other piece of software, are all about trade offs.

For domain specific languages, on the other hand, it might just be the other way around. If you aren't building "one language to rule them all", you are free to implement only the features that make sense for the very specific purpose of your language. And more often than not, Turing completeness is not one of them.


问:
Would you re-design completely under .Net?
A very extensive application began as an Access-based system (for database storage). Forms were written in VB5 and/or VB6. As .Net became a fixture in the development community, certain modules have been rewritten. This seems very awkward and potentially costly just to maintain because of the cross-technologies and extra work to keep the two technologies happy with each other. Of course, the application uses a mix of ODBC OleDb and MySql.

Would you think spending the time and resources to completely re-develop the application under .Net would be more cost effective? In an effort to develop a more stable application, wouldn't it make sense to use .Net? Or continue chasing Access bugs, adding new features in .Net (which may or may not create new bugs between .Net and Access), and rewriting old Access modules into .Net modules under time constraints that prevent proper design and development?

Update
The application uses OleDb and MySql - I corrected my previous statement.

Also, to lend further support to rewriting: I have since found out that when the "porting" to .Net began, the VBA/VB6 code that existed was basically translated to the .Net equivalent. From my understanding, nothing was done to improve performance, or take advantage of new libraries or technologies.

In my opinion, this creates a very fragile and unstable application. With every new update, this becomes more and more visible. As a help desk technician, I have noticed an increase in problems reported. The customers using the software have noticed an increase in problems and are commenting on it.

答:
It is generally a discouraged practice to "rewrite" an application from scratch (which is a normal urge most programmers felt at least a few times in their lifetime) because you will go from an app with known feature set (and known bugs too!) to an app with most likely lesser set of features and more importantly - unknown bugs. Users could get frustrated, etc.

You would probably be better off if you slowly refactored your app over a period of time, thereby evolving it's architecture over a longer period of time.


问:
Except garbage collector, what else makes Java a non real time programming language
Except the garbage collector, what are some other features in Java that make it unsuitable for real time programming? On the net, whenever Java vs C++ is discussed with regards to real time programming, it is always the garbage collector that is mentioned. Is there anything else?</p>

答:
There are two additional items I can remember off-hand:

JIT compilation

Threading implementation

In term of real-time, predictability of performance is probably the most important factor; That's why an unpredictable GC cycle makes Java unsuitable for real-time.

JIT offers improved performances, but kicks in at some point after the program is running, taking some resources, and changing the execution speeds of the system. It can also happen again at a later stage, if the VM believes it can do a "better" job at that time.

As far as threading: I don't quite remember at this point if this is part of the language design, or just a very common implementation, but Java usually provides no tools to precisely control thread execution; For example, while there are 10 "priorities" specified for threads, there's no requirement that the VM actually considers these priorities. Operators for stopping and switching threads are also either not defined, or not rigidly adhered to by the system.

There are several implementations of JSR 1: Real-time Specification for Java - a spec that has been approved in 1998.
This spec addresses as much as possible of the issues that makes standard Java unsuitable for real-time.

As of maybe 5 years ago, Sun (Now Oracle) had a RTSJ VM (That never had a name, AFAIK); IBM had WebSphere Real Time; And JamaicaVM was a free(?), platform-independent solution. Googling those today doesn't bring much.


答:
The operating system

As long as Java runs on top of Unix or Windows or any other "regular" OS, realtime is not guaranteed.

A real time OS is mandatory for running realtime applications.

Title: Except garbage collector, what else makes Java a non real time programming language

Body: Except the garbage collector, what are some other features in Java that make it unsuitable for real time programming? On the net, whenever Java vs C++ is discussed with regards to real time programming, it is always the garbage collector that is mentioned. Is there anything else?</p>


问:
How do you get a client to understand the importance of a project lifecycle?
Situation is I have a number of in-house clients who continue to have trouble grasping the concept of defining clear requirements for a project and committing to them. Unfortunately my job situation is that I can't decline such projects, and I am often forced into situations that I can tell are doomed to scope creep (or worse) from the very start. Telling them that detailed requirements are vital and why we need them (using examples of past troubled projects due to this) have not helped.

I am looking for techniques, tips, words, etc that you might use to motivate or illuminate clients in such situations to the necessity of requirements,setting milestones, etc.

I am only a developer, and not a manager.

答:
Throw the entire business-buzzword-gauntlet at them. They need to see the big picture by being proactive in order to leverage inter-department synergy and improve the bottom-line. How could they not be on board?

Seriously, when they request a change, you need to mention the following:

In order to implement the change at the time they need it, what feature(s) should be delayed? Can they afford to delay the entire project?

Get them to commit to an increased testing/approval schedule. You may have to repeat the tests on completed areas of the project.

As a profession, we need to get over this. It's going to happen, be prepared. You'd be surprised at the reactions of users when you present your concerns calmly and professionally. Often times, the reaction I get is, "Oh, if it's that much of a problem, forget it." If they accept the delay and extra work on their end, so what. But if you have a reputation of whining after every request, you've lost credibility and won't be taken seriously.


问:
Provide multiple SendCompleted callbacks to SmtpClient
I have an Email class that has a Send method that optionally takes an SmtpClient and sends an email asynchronously using SendAsync. If no SmtpClient is supplied to this method, it instantiates a default SmtpClient and uses that to send the email. Inside the Send function, I provide a SendCompleted callback which disposes of the MailMessage and the default SmtpClient if one was not supplied to the method.

So when I am supplying the SmtpClient, how do I go about disposing it?

I can't dispose of it inside Send because it may be used for sending other emails, plus I figure it's the responsibility of the thing that instantiated the passed in SmtpClient to dispose of it again. Is it possible to add multiple SendCompleted callbacks to the SmtpClient that run after each other?

答:
There are two major ways of going about destroying your SmtpClient objects.

The SmtpClient manages its own lifetime (i.e. destroys itself when the time comes). This is easiest if each SmtpClient is used for only one email, but it can be made to work for multiple, if SmtpClient knows how many emails it sent and it can be guaranteed that the SendCompleted callback is invoked a corresponding number of times.

An outside component manages the lifetime of SmtpClient (this can be the object that created SmtpClient or some other object). In this case, the SmtpClient needs to inform the object responsible for managing its lifetime about the SendCompleted callback being invoked. This is usually done by invoking a callback on that object from within SendCompleted.


问:
When do code hacks become bad?
When you begin a new project/function/object you mostly have an idea of the model you want to build. It can be based on the clients' wish, on your ideas for the app or whatever. In the middle you often realise that your model will not work. There may be new requirements, you didn't think of something etc. Then you have two options. Either you rewrite your code to work with the new specifications, or you "hack" the current code to do what you want. A rewrite is time consuming, and you may need to do it several times, but in the long run it often pays. Hacks are fast and often effective for the moment, but many hacks will make the code really bad, and after a while they may come back and bite you in the behind...

How do you determine when to do what?

(Pardon my very non-academic way of explaining this, but I hope you understand what I'm getting at.)

答:
Hacks are always a bad idea. BUT if you're not the project manager, then it is not your concern whether or not the hack will need to be turned into a re-write down the line. The only thing you should have to do is explain why you need to hack something given the time/budget constraints and that you are concerned about the ramifications. Keep this correspondence on record. The PM would then have enough information to make a good decision and if he insists on the hack, HE is to  blame, not you.

That's how the game works, like it or not.

Title: When do code hacks become bad?


问:
Complex Mutual Exclusion Validation Logic
I need to validate some form inputs in complex way. E.g.

```<code><select id="options" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</code>```

For example, if user selects A and B, user should be given an error if user also selects D.

Note, I'm trying to keep this business rule in a separate layer from this UI code, which could be an entirely different form, e.g. checkboxes, drag-and-drop, add/delete options with possibly accompanying fields.

I'm looking for a framework, design pattern, or other elegant way to code this logic, preferably ultimately through validation attributes in a model.

答:
Most frameworks can validate at the model level. So that should be sufficient. So you validate at the lowest possible level.

Example: https://stackoverflow.com/questions/14217442/cakephp-validation-depending-on-other-field

If you want to show this in the interface (with ajax for example) you just call the model to validate (via the controller probably). Create a method in the controller like: validateOptions() and send an ajax call to it so you can modify the user interface.

When really saving the validation will be done again to ensure it's right.


答:
A big challenge that I experienced with a rewrite of that scale is having to maintain two codebases at the same time. If you fix a bug in the legacy system, you have to make sure the functionality works correctly in the new system, and vice versa. Upgrading one module at a time minimizes that maintenance headache.

A full regression test suite that runs on both the legacy and replacement systems would also be helpful.

Title: Would you re-design completely under .Net?

Body:
A very extensive application began as an Access-based system (for database storage). Forms were written in VB5 and/or VB6. As .Net became a fixture in the development community, certain modules have been rewritten. This seems very awkward and potentially costly just to maintain because of the cross-technologies and extra work to keep the two technologies happy with each other. Of course, the application uses a mix of ODBC OleDb and MySql.

Would you think spending the time and resources to completely re-develop the application under .Net would be more cost effective? In an effort to develop a more stable application, wouldn't it make sense to use .Net? Or continue chasing Access bugs, adding new features in .Net (which may or may not create new bugs between .Net and Access), and rewriting old Access modules into .Net modules under time constraints that prevent proper design and development?

Update
The application uses OleDb and MySql - I corrected my previous statement.

Also, to lend further support to rewriting: I have since found out that when the "porting" to .Net began, the VBA/VB6 code that existed was basically translated to the .Net equivalent. From my understanding, nothing was done to improve performance, or take advantage of new libraries or technologies.

In my opinion, this creates a very fragile and unstable application. With every new update, this becomes more and more visible. As a help desk technician, I have noticed an increase in problems reported. The customers using the software have noticed an increase in problems and are commenting on it.


问:
Offline version of dynamic pages
Researching archiving systems like archive.org, found out main issue of such is the dynamic content.

Initial analysis shows that content 'dynamicity' can be assigned to one of the following levels:

Static html content - plain old web page which is represented only by html markup with auxiliary css-referred resources (usually images).

Static html powered by javascirpt – same as Level 1, but has javascript code, which only manipulates existing markup (such as expand/collapse).

“Onload” page construction – web page with javascript code, which makes a certain additional requests during page load phase. After loads phase page content is fully constructed.

Dynamic client-side content – UI elements are modified by javascript code on-the-go, as user traverses through interface. Usually these are modern SPA (single-page-applications, like gmail.com), “endless” lists (list tail is loaded when user scrolls down to the list bottom) , loading content on demand (smart expanders) and so on.

So I assume that Levels 1 and 2 can be archived pretty easily. Could you please suggest how to handle Levels 3 and 4? Looks like it should involve page rendering, but some details would be helpful.

Update: To clarify the question: ideally offline version should be fully-functional, at least within the site level (ignoring external domains content). Also, if Level4 is too hard to automate fully - is there an approach involving human operator who makes hints to the system about content?

答:
It is doable, integrate in your crawler a webkit browser. Then get all static pages first. Log down the requests made by the page (you can now because the browser in your crawler actually renders the page).

That will give you an overview of the responses done.

The onloads are easy because they are done directly. The harder part is clickable elements which load additional content. To get them find everything with a custom event attached and execute the event to see what happens. If content changes you will know.

The responses could be cache so you could create a full working version.

Considerations are mostly processing time and browser issues. It is much slower to crawl this way then textual parsing since you actually need to load and render the page.

Title: Offline version of dynamic pages


答:
Yes absolutely.

The analogy I like to use to explain programming is that of a Tailor. When making a suit, a good Tailor will always leave a small amount of fabric at strategic locations within the garment to allow the garment to be taken in, or out, without changing its overall shape or structure.

Good Tailor's don't leave reams of fabric at each seam just incase you happen to grow a third arm, or become pregnant. Too much material in the wrong places will make for an ill fitting, and ill wearing garment, the extra fabric simply gets in the way of normal use. To little fabric and the garment is prone to tears and will not be able to be altered to cope with minor changes to the physique of its wearer, effecting the way garment sits.

Perhaps one day, our Good Tailor will be tasked to make a dress so tight he has to sew its wearing into it. And perhaps our Good Tailor is asked to make maternity wear, where style and fit are second to comfort and expand-ability. But before undertaking either of those special jobs a good Tailor would be wise enough to make everyone aware of the compromises that are being made to achieve those goals.

Sometimes these compromises are the correct route to take, and people are willing to accept their consequences. But in most cases, the approach of leave a little where it counts the most will outweigh any perceived benefits.

So, relating this back to abstraction. Its absolutely possibly to have way too many layers of abstraction, just like its possible to have way to little. The true art of the programmer, like the our tailor friends, is to leave a little where it counts the most.

Getting back on topic.

The problem with code is usually not abstraction, but dependencies. As you've pointed out, its the code which connects discrete objects that's an issue, because there's an implicit dependency between them. At some point communication between things just needs to be concrete, but judging where that point is usually requires some guesswork.

That being said "Micro" anything is usually an indication that you've overgranulized your object layout, and are probably using Type as a synonym for what should be Data. Having less things also means less dependencies needed to communicate between them.

I'm a big fan of asynchronous messaging between systems for this reason. You end up with two systems dependent on the message, rather than each other. Giving you less tight coupling between communicating systems. At that point, if you need to have a dependency between systems you need to consider whether you've got the bits that are dependent in the right place(s). And its often the case that you dont.

Finally, complicated code is going to be complicated. There's often no way around that. But code which has less dependencies is far easier to understand than one which relies on various external states.

Title: Can too much abstraction be bad?


Title: Complex Mutual Exclusion Validation Logic

Body:
I need to validate some form inputs in complex way. E.g.

```<code><select id="options" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</code>```

For example, if user selects A and B, user should be given an error if user also selects D.

Note, I'm trying to keep this business rule in a separate layer from this UI code, which could be an entirely different form, e.g. checkboxes, drag-and-drop, add/delete options with possibly accompanying fields.

I'm looking for a framework, design pattern, or other elegant way to code this logic, preferably ultimately through validation attributes in a model.

Body:
For representing the validation logic of your inputs, you can use a Karnaugh map, in which inputs are the selection state of A, B, C, D and E, and the outcome is the validation status of each input combination.

  AB-CDE | 000 | 001 | 011 | 010 | 110 | 111 | 101 | 100 |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  00     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  01     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  11     |     |     |  0  |  0  |  0  |  0  |     |     | -> Error if (A.B).D
 --------+-----+-----+-----+-----+-----+-----+-----+-----+
  10     |     |     |     |     |     |     |     |     |
 --------+-----+-----+-----+-----+-----+-----+-----+-----+

From that map, you can find the minimal logic expression validating your check boxes.


问:
What concepts/technologies should an ASP.NET developer be familiar with
I am in the process of filing in the gaps in my knowledge so that I can become a better developer. I am an ASP.NET developer and I sometimes need to do pure back-end stuff too. I ahve compiled a list of things I deem as necessary to know. Please feel free to fill in any gaps:

WebForms

MVC

jQuery

HTML5

WPF

WCF

The Repository pattern

Dependency injection (Castle.Windsor)

NHibernate

Entity Framework

Asynchronous programming

SQL. As in: hardcore SQL with temp tables and groupings and variables and stuff.

Unit Tests

答:
I would add

ALM for continuous delivery & source control

MVVM

MEF

CSS3

Not sure what your knowledge is on general programming skills; but I advice every developer to go trough some of the basic design patterns.


答:
I agree with Jas, don't rewrite apps just for rewrite sake. They may never need to be debugged or improved, so why waste time? However, if you feel there is a moving shift in the expertise of your new developer hires away from Access to .NET, you may have to migrate before it's too late. That seems unlikely, but a possible consideration.

Although it may not be profitable from a development standpoint, how is having different applications spread around affecting users? Does it require more user training? Are they making more mistakes. Does it increase the number of support calls because they can't find something?


问:
GPL code allowing non-GPL local copies of nondistributed code
I have come across a book that claims that alterations
and augmentations to GPL works can be kept close-source
as long as these are not redistributed into the wild.
Therefore, customizations of websites deriving from
GPL packages need not be released under the GPL and
developers can earn profit on them by offering their
services to their clients while keeping their
GPL-based code closed source at the same time.

(cf. Chapter 17 of WordPress Plugin Development by Wrox Press).

I've never realized this, but essentially, by putting
restrictions on redistributable code the GPL says nothing
about what can and cannot be done with code which is kept private
in terms of the licensing model.

Have I understood this correctly?

答:
Copyright law questions are by definition off topic, and the answers you can get here are by definition untrustworthy.

However, you are basically right: the purpose of copyright is to restrict redistributing things. The author is allowed to do it, others, by default, aren't. Therefore, the author can't restrict your freedom to act if you don't redistribute anything that he has copyright on.

Note that the precise extent of what "redistributing" means ('give' it to your backup system? to a friend? to the employees of your company?) would have to be tested in court, like anything related to civil or criminal law, and AFAICT it hasn't been. (For perspective: where I live, even the fundamental question of whether EULAs are legally binding or not has never been been clearly decided.)


答: Yes, you have understood that correctly. To address this loophole in the GPL license, the Affero GPL licence has been created, which considers using the software as part of a website as being a distribution of that software.</p>

Title: GPL code allowing non-GPL local copies of nondistributed code

Body:
I have come across a book that claims that alterations
and augmentations to GPL works can be kept close-source
as long as these are not redistributed into the wild.
Therefore, customizations of websites deriving from
GPL packages need not be released under the GPL and
developers can earn profit on them by offering their
services to their clients while keeping their
GPL-based code closed source at the same time.

(cf. Chapter 17 of WordPress Plugin Development by Wrox Press).

I've never realized this, but essentially, by putting
restrictions on redistributable code the GPL says nothing
about what can and cannot be done with code which is kept private
in terms of the licensing model.

Have I understood this correctly?


问:
APIs that deal with logins
I have been asked to make a mobile app for a friends website. The website is a Multi level marketing site that sells products and franchises. A client logs in in to the website and can view his or her dashboard ( user can view team members, business volume, commissions, invoices, etc.) The app is supposed to bring the dashboard to user's mobile devices (w/ some added features).

The company does not have any APIs that deal with interaction or authentication, and I am new to the whole secure login side of app development.  My questions is this, how do I let the users gain access to their information via my app from the secure website when there is no API?

答:
If you would consider using MS technology you can use ASP.Net forms authentication with SQL server.
ASP will build a data structure to persist your account information. Also there will be generated content for account login or registration.

a good starting point would be MSDN: How to implement simple forms authentication

Title: APIs that deal with logins


答:
GPL up to version 2 is distribution license, so if GPLv2 is the one used you understand that correctly. Basic idea of GPL is that you have to provide the source code to everyone that you provide with binaries. In your case you don't provide binaries to anyone but yourself.

However, starting with GPL version 3, there are more restrictions. One of them is optional Affero clause, which closes what they call a "SaaS loophole". GPLv3 with Affero clause is often referred to as AGPL.

Other restrictions relate to software patents (most likely not your case), tivoization (i.e. distributuion of hardware with unmodificable GPL code, so not your case either), and DRM implementation.

This is exactly the reason why for example Linux kernel is GPLv2 and will never switch to GPLv3.


答:
I agree with the refactoring approach.  It is quite likely that this will be a slow process that may take many months to complete, but by moving one feature / section at a time has major advantages including:

Product features are maintained.

ability to deliver a new release is maintained.

Time pressure is removed.

Good luck


问:
Programming against a protocol in Objective-C
I stumbled accross the SOLID principles. There is one burning question. Should I always use protocols? I never saw someone using them in the way that a Java developer would use them.

I tried it in a demo project and ended up with a .h file for the protocol, another .h for the header. A .m file for the implementation and sometimes a .xib for the UI.

Is there a reason why an ObjC developer would only use protocols for delegates? I never saw ObjC code with a test first approach. Does SOLID programming apply for ObjC?

答:
SOLID principles don't necessarily apply in any context, regardless of technology or programming language. Many developers choose to abide by them though, and it's certainly possible to do in Objective-C.

If you're interested in seeing test-first Objective-C, then take a look at BrowseOverflow: it's a completely test-driven app that makes use of UIKit and network services. I actually wrote it as the sample code for Test-Driven iOS Development, but if you're comfortable with the principles you can just look at the code. You can see there that even though the code was test-driven, it isn't brimming with protocols.

One reason for that is "duck typing". Objective-C, like Smalltalk before it and Ruby after it, doesn't actually care what type an object is, it just sends messages. The type safety system is entirely restricted to the compiler checking. You can therefore type a variable as specifically as you want and still (sometimes with some casting) supply a different type at runtime. As long as both types respond to the messages passed in your code, everything works. You can see that the tests in BrowseOverflow use this to pass in test fakes, even for variables that aren't typed using protocols.

In fact in historical Objective-C and Smalltalk (and in modern Ruby) many collaborating objects aren't typed at all: in Objective-C the id type means "any object". That's less common now in ObjC, but a lot of Apple's framework code is old enough to have been around when this was the norm. You'll notice that newer frameworks, and newer API on existing frameworks, uses stricter typing and protocol types for non-delegate collaborators.

Is there a reason why an ObjC developer would only use protocols for delegates?

Personal choice. There's no underlying technical reason to follow that approach.

Does SOLID programming apply for ObjC?

Yes. Or rather, it can do, and many developers choose to follow SOLID principles.


问:
Question regarding Readability vs Processing Time
I am creating a flowchart for a program with multiple sequential steps.
Every step should be performed if the previous step is succesful. I use a c-based programming language so the lay-out would be something like this:

METHOD 1:

```<code>if(step_one_succeeded())
{
    if(step_two_succeeded())
    {
        if(step_three_succeeded())
        {
            //etc. etc.
        }
    }
}
</code>```

If my program would have 15+ steps, the resulting code would be terribly unfriendly to read. So I changed my design and implemented a global errorcode that I keep passing by reference, make everything more readable. The resulting code would be something like this:

METHOD 2:

```<code>int _no_error = 0;

step_one(_no_error);
if(_no_error == 0) step_two(_no_error);
if(_no_error == 0) step_three(_no_error);
if(_no_error == 0) step_two(_no_error);
</code>```

The cyclomatic complexibility stays the same. Now let's say there are N number of steps. And let's assume that checking a condition is 1 clock long and performing a step doesn't take up time.

The processing speed of Method1 can be anywhere between 1 and N.

The processing speed of Method2 however is always equal to N-1.

So Method1 will be faster most of the time. Which brings me to my question, is it bad practice to sacrifice time in order to make the code more readable? And why (not)?

答:
Sacrificing code readability to save a few clock cycles is a clear sign of premature optimisation.

Your first aim should always be to write the best readable/maintainable code that gives a reasonable performance. Only after measurements have indicated that your N condition tests actually form a bottleneck for the overall performance and there are no optimisation possible that would yield a larger effect (such as using a different algorithm), then you could consider sacrificing readability to get the required performance.

Even if you are in the extremely rare situation that you are writing a library that must always give the very highest performance, you should consider carefully if the loss of readability is worth those few instructions and if a good optimising compiler would not generate the same code for both anyway.


答:
And let's assume that checking a condition is 1 clock long and performing a step doesn't take up time.

No.

Let's not make assumptions that completely skew the discussion. In reality, the steps take up time, most likely much, much more time than all the condition checking.

Which means that the performance considerations are irrelevant.

And that is the reason why premature optimization is, in fact, bad even when performance is very important.

Title: Question regarding Readability vs Processing Time

Body:
I am creating a flowchart for a program with multiple sequential steps.
Every step should be performed if the previous step is succesful. I use a c-based programming language so the lay-out would be something like this:

METHOD 1:

```<code>if(step_one_succeeded())
{
    if(step_two_succeeded())
    {
        if(step_three_succeeded())
        {
            //etc. etc.
        }
    }
}
</code>```

If my program would have 15+ steps, the resulting code would be terribly unfriendly to read. So I changed my design and implemented a global errorcode that I keep passing by reference, make everything more readable. The resulting code would be something like this:

METHOD 2:

```<code>int _no_error = 0;

step_one(_no_error);
if(_no_error == 0) step_two(_no_error);
if(_no_error == 0) step_three(_no_error);
if(_no_error == 0) step_two(_no_error);
</code>```

The cyclomatic complexibility stays the same. Now let's say there are N number of steps. And let's assume that checking a condition is 1 clock long and performing a step doesn't take up time.

The processing speed of Method1 can be anywhere between 1 and N.

The processing speed of Method2 however is always equal to N-1.

So Method1 will be faster most of the time. Which brings me to my question, is it bad practice to sacrifice time in order to make the code more readable? And why (not)?


答:
Technically it's possible to have real time java (as SK-logic's comments suggest).
however it is not common for a number of non-technical reasons:

Old standards

Having trouble finding a reference for this but I'm certain I've seen safety standards, or safety standard conformance advice, put a blanket ban on Java. Rightly or wrongly if you have to conform to something that says Java is verboten then Java is Verboten.

Old safety engineers

Even if the standards you need to work to don't ban Java, working with Safety/Quality auditors without experience of Java will very much mean you are not following the path of least resistance. Anything that is out of the ordinary for the auditor will likely attract a lot of questions which in turn means lots of work for you justifying your choices.

The community

i.e. there is a lot of path dependency, most of the current real time experts will know C++, C or ADA inside out so it is a natural choice to do new work in.

(note: I've somewhat conflated real-time and safety in the above, which is sort of an another issue, in that even safety standards often conflate the two)


答:
Compilers usually slice and dice and completely rebuild any code they compile. Since readable code is more common, the optimizations are usually tuned for that, so readable code actually stands better chance being optimized well by the compiler.

On a side note, avoid returning by reference. It is both more difficult to read and more difficult for compiler to optimize. The variable should always be set like _no_error = _no_error && step_one() (which, accidentally, acts as condition, so you don't need them than; but it's not idiomatic in C++).

Last, I don't consider the _no_error (besides the bad name of that variable; symbols starting with _ are reserved for library extensions) version much more readable. A readable code in any language that supports RAII (C++, D, Rust) or equivalent (finally) (C#, Java) is:

```<code>if(!step_one())
    return;
if(!step_two())
    return;
...
</code>```

In plain old C, using goto is preferable—if you need some clean-up there, that is, otherwise you can of course use return directly too:

```<code>if(!step_one())
    goto failed;
if(!step_two())
    goto failed;
...
failed:
clean_up();
</code>```

Body:
Compilers usually slice and dice and completely rebuild any code they compile. Since readable code is more common, the optimizations are usually tuned for that, so readable code actually stands better chance being optimized well by the compiler.

On a side note, avoid returning by reference. It is both more difficult to read and more difficult for compiler to optimize. The variable should always be set like _no_error = _no_error && step_one() (which, accidentally, acts as condition, so you don't need them than; but it's not idiomatic in C++).

Last, I don't consider the _no_error (besides the bad name of that variable; symbols starting with _ are reserved for library extensions) version much more readable. A readable code in any language that supports RAII (C++, D, Rust) or equivalent (finally) (C#, Java) is:

if(!step_one())
    return;
if(!step_two())
    return;
...

In plain old C, using goto is preferable—if you need some clean-up there, that is, otherwise you can of course use return directly too:

if(!step_one())
    goto failed;
if(!step_two())
    goto failed;
...
failed:
clean_up();


答:
A lot of people discourage rewriting an application from scratch and sometimes I agree with the reasoning.  But most of the times I find rewrting the app the least painful solution and anything written in Access needs to be ported to .NET - PERIOD.  Don't get me wrong, Access has its place and can provide alot of functionality to an organization, but if it turns into a full-fledged app that people rely on then it has out grown Access.

It would probably not take much time to port the extisting VBA to .NET in a one for one conversion.  But that may not be a great solution if the VBA is not very good to begin with.  A redesign/rewrite will take longer to write but will in the long run be much easier to maintain.

I am almost always in the camp of rewriting it from scratch where Access is concerned and have not regretted it once.


问:
pcre case insensitivity: handle escape sequences as raw bytes?
Consider the following regex (no unicode):

```<code>Example:\x04\x05\x41
</code>```

Suppose you search this regex case-insensitively. Would you expect it to search the final \x41 in case-sensitive manner? People whom I ask actually expect such behavior. And such expectations are wrong.

Perldoc says:

Note that a character expressed as one of these escapes is considered
  a character without special meaning by the regex engine, and will
  match "as is".

Which basically means that if the character escaped is printable non special character it's equivalent to just typing that character. And that's how it actually behaves. However if regex is case insensitive alphabetic characters do have a special meaning of "this character or same character in opposite case" and such special meaning is not ignored in \x sequences.

Escape sequences have "raw byte" semantics, but not always. Does it seem to you like a design awkwardness?

Is there a way to cause pcre to treat \x sequences as raw bytes that ignore case sensitivity? Perhaps as a flag? As non standard patch? If no how if at all pcre engine code can be modified to provide such functionality?

答:
However if regex is case insensitive alphabetic characters do have a
  special meaning of "this character or same character in opposite case"
  and such special meaning is not ignored in \x sequences.

You're reading too much into what constitutes "special meaning."  In this case, it refers to single characters that direct interpretation of the input such as . and *.  Escaping those characters in any form treats them as literals.  In other words, . means match any character but \. or \x2e means match a period.  (There are exceptions, such as \d, which is fine because there's never a need to escape a lowercase d.)

Special meaning does not include behavior brought on by using modifiers.  Using i tells the engine to use a different algorithm for comparing single characters, which happens long after the expression itself has been parsed.  The \x escape will have been applied when the expression itself was processed, meaning that \x41 will already have been interpreted as A.

Escape sequences have "raw byte" semantics, but not always. Does it seem to you like a design awkwardness?

Escapes originally came to exist as a way to embed characters in files that could not otherwise be represented using printable characters.  If embedded as-is, these characters might be interpreted as control sequences or would simply be invisible when looking at them in an editor or on a printed page.  Regular expressions co-opted this concept and added all sorts of additional escapes that had semantic rather than literal meaning, such as the \(...\) construct with which you're probably familiar.

How awkward that is would be a matter of opinion, but there really isn't any way to denote special meaning in strings without selecting one of the otherwise-valid characters to do it.

Is there a way to cause pcre to treat \x sequences as raw bytes that ignore case sensitivity?

No, there isn't.  Perl doesn't allow it, so PCRE won't, either.

Perl regular expressions do have a way to enable or disable modifiers within spans of characters (see the Extended Patters section of perlre):

```<code>/(?i:case-insensitive)case-sensitive/
/(?-i:case-sensitive)case-insensitive/i
</code>```

If you have your regular expression available as a string, you could develop a function that does the equivalent of s/((?<!\\)\\x[[:xdigit:]]{2})/(?-i:$1)/g, which would spare you having to modify PCRE.

As non standard patch? If no how if at all pcre engine code can be
  modified to provide such functionality?

Anything's possible, but I'm not going to tear into PCRE and figure it out for you.  You'd have to alter RE parser so that it stores literals specified with \x as a case-sensitive span instead of a literal.  You would run the risk of breaking expressions that depend on the standard behavior, so you'd also have to add a modifier that explicitly enables it.

By the way, if you're simply searching for one string inside another, using m// is overkill.  Calling index() would be simpler and much more efficient.

Body:
However if regex is case insensitive alphabetic characters do have a
  special meaning of "this character or same character in opposite case"
  and such special meaning is not ignored in \x sequences.

You're reading too much into what constitutes "special meaning."  In this case, it refers to single characters that direct interpretation of the input such as . and *.  Escaping those characters in any form treats them as literals.  In other words, . means match any character but \. or \x2e means match a period.  (There are exceptions, such as \d, which is fine because there's never a need to escape a lowercase d.)

Special meaning does not include behavior brought on by using modifiers.  Using i tells the engine to use a different algorithm for comparing single characters, which happens long after the expression itself has been parsed.  The \x escape will have been applied when the expression itself was processed, meaning that \x41 will already have been interpreted as A.

Escape sequences have "raw byte" semantics, but not always. Does it seem to you like a design awkwardness?

Escapes originally came to exist as a way to embed characters in files that could not otherwise be represented using printable characters.  If embedded as-is, these characters might be interpreted as control sequences or would simply be invisible when looking at them in an editor or on a printed page.  Regular expressions co-opted this concept and added all sorts of additional escapes that had semantic rather than literal meaning, such as the \(...\) construct with which you're probably familiar.

How awkward that is would be a matter of opinion, but there really isn't any way to denote special meaning in strings without selecting one of the otherwise-valid characters to do it.

Is there a way to cause pcre to treat \x sequences as raw bytes that ignore case sensitivity?

No, there isn't.  Perl doesn't allow it, so PCRE won't, either.

Perl regular expressions do have a way to enable or disable modifiers within spans of characters (see the Extended Patters section of perlre):

/(?i:case-insensitive)case-sensitive/
/(?-i:case-sensitive)case-insensitive/i

If you have your regular expression available as a string, you could develop a function that does the equivalent of s/((?<!\\)\\x[[:xdigit:]]{2})/(?-i:$1)/g, which would spare you having to modify PCRE.

As non standard patch? If no how if at all pcre engine code can be
  modified to provide such functionality?

Anything's possible, but I'm not going to tear into PCRE and figure it out for you.  You'd have to alter RE parser so that it stores literals specified with \x as a case-sensitive span instead of a literal.  You would run the risk of breaking expressions that depend on the standard behavior, so you'd also have to add a modifier that explicitly enables it.

By the way, if you're simply searching for one string inside another, using m// is overkill.  Calling index() would be simpler and much more efficient.


问:
Achieving Zero Downtime Deployment
I am trying to achieve zero downtime deployments so I can deploy less during off hours and more during "slower" hours - or anytime, in theory.

My current setup, somewhat simplified:

Web Server A (.NET App)

Web Server B (.NET App)

Database Server (SQL Server)

My current deployment process:

"Stop" the sites on both Web Server A and B

Upgrade the database schema for the version of the app being deployed

Update Web Server A

Update Web Server B

Bring everything back online

Current Problem

This leads to a small amount of downtime each month - about 30 mins.  I do this during off hours, so it isn't a huge problem - but it is something I'd like to get away from.

Also - there is no way to really go 'back'.  I don't generally make rollback DB scripts - only upgrade scripts.

Leveraging The Load Balancer

I'd love to be able to upgrade one Web Server at a time.  Take Web Server A out of the load balancer, upgrade it, put it back online, then repeat for Web Server B.

The problem is the database.  Each version of my software will need to execute against a different version of the database - so I am sort of "stuck".

Possible Solution

A current solution I am considering is adopting the following rules:

Never delete a database table.

Never delete a database column.

Never rename a database column.

Never reorder a column.

Every stored procedure must be versioned.

Meaning - 'spFindAllThings' will become 'spFindAllThings_2' when it is edited.

Then it becomes 'spFindAllThings_3' when edited again.

Same rule applies to views.

While, this seems a bit extreme - I think it solves the problem.  Each version of the application will be hitting the DB in a non breaking way.  The code expects certain results from the views/stored procedures - and this keeps that 'contract' valid.  The problem is - it just seeps sloppy.  I know I can clean up old stored procedures after the app is deployed for awhile, but it just feels dirty.  Also - it depends on all of the developers following these rule, which will mostly happen, but I imagine someone will make a mistake.

Finally - My Question

Is this sloppy or hacky?

Is anybody else doing it this way?

How are other people solving this problem?

答:
This is a very pragmatic approach to database-backed software upgrades. It was described by Martin Fowler and Pramod Sadalage in 2003 and subsequently written up in Refactoring Databases : Evolutionary Database Design.

I can see what you mean when you say that it seems sloppy, but when done intentionally and with forethought, and taking the time to refactor unused structures out of the codebase and database when they're demonstrably no longer used, it's much more robust than simpler solutions based on upgrade and rollback scripts.

Title: Achieving Zero Downtime Deployment


问:
Can too much abstraction be bad?
As programmers I feel that our goal is to provide good abstractions on the given domain model and business logic. But where should this abstraction stop? How to make the trade-off between abstraction and all it's benefits (flexibility, ease of changing etc.) and ease of understanding the code and all it's benefits.

I believe I tend to write code overly abstracted and I don't know how good is it; I often tend to write it like it is some kind of a micro-framework, which consists of two parts:

Micro-Modules which are hooked up in the micro-framework: these modules are easy to be understood, developed and maintained as single units. This code basically represents the code that actually does the functional stuff, described in requirements.

Connecting code; now here I believe stands the problem. This code tends to be complicated because it is sometimes very abstracted and is hard to be understood at the beginning; this arises due to the fact that it is only pure abstraction, the base in reality and business logic being performed in the code presented 1; from this reason this code is not expected to be changed once tested.

Is this a good approach at programming? That it, having changing code very fragmented in many modules and very easy to be understood and non-changing code very complex from the abstraction POV? Should all the code be uniformly complex (that is code 1 more complex and interlinked and code 2 more simple) so that anybody looking through it can understand it in a reasonable amount of time but change is expensive or the solution presented above is good, where "changing code" is very easy to be understood, debugged, changed and "linking code" is kind of difficult.

Note: this is not about code readability! Both code at 1 and 2 is readable, but code at 2 comes with more complex abstractions while code 1 comes with simple abstractions.

答:
I feel that our goal is to provide good abstractions on the given domain model and business logic.

I have a different view: our goal is to solve a business problem. Abstractions are just a technique to organize a solution. Another answer uses the analogy of a tailor making clothes. I have another analogy I like to think of: a skeleton. The code is like a skeleton, and abstractions are the joints between bones. If you have no joints, then you just wind up with a single bone that cannot move at all and is useless. But if you have too many joints, you wind up with a pile of sloppy jelly that can't stand up on its own. The trick is to find the right balance -- enough joints to allow for movement, but not so much that there's no actual defined shape or structure.

Title: Can too much abstraction be bad?


答:
"Zero downtime" is just one of many possible reasons for this kind of approach. Keeping a datamodel backwards compatible this way helps you to deal with a lot of different problems:

if you have a lot of software packages accessing your database, you won't have to check them all if a schema change affects them (in bigger organizations with multiple teams writing programs all accesssing the same database, schema changes may become very hard)

if you must, you can check out an older version of one of your programs and it will most probably run agains a newer database (as long as you don't expect the old program to handle any newer columns correctly)

import / export of archived data into the current database version is much easier

Here is an additional rule for your list

each new column should be either NULLable or provide a meaningful default value

(this makes sure even older programs which don't know the new columns won't break anything when they create new records in your database).

Of course, this approach has one real drawback: your datamodel quality may degrade over time. And if you have complete control over all applications accessing your database, and you can refactor all those applications easily when you, for example, are going to rename a column, then you might consider to refactor things in a cleaner way.

Title: Achieving Zero Downtime Deployment

Body:
I am trying to achieve zero downtime deployments so I can deploy less during off hours and more during "slower" hours - or anytime, in theory.

My current setup, somewhat simplified:

Web Server A (.NET App)

Web Server B (.NET App)

Database Server (SQL Server)

My current deployment process:

"Stop" the sites on both Web Server A and B

Upgrade the database schema for the version of the app being deployed

Update Web Server A

Update Web Server B

Bring everything back online

Current Problem

This leads to a small amount of downtime each month - about 30 mins.  I do this during off hours, so it isn't a huge problem - but it is something I'd like to get away from.

Also - there is no way to really go 'back'.  I don't generally make rollback DB scripts - only upgrade scripts.

Leveraging The Load Balancer

I'd love to be able to upgrade one Web Server at a time.  Take Web Server A out of the load balancer, upgrade it, put it back online, then repeat for Web Server B.

The problem is the database.  Each version of my software will need to execute against a different version of the database - so I am sort of "stuck".

Possible Solution

A current solution I am considering is adopting the following rules:

Never delete a database table.

Never delete a database column.

Never rename a database column.

Never reorder a column.

Every stored procedure must be versioned.

Meaning - 'spFindAllThings' will become 'spFindAllThings_2' when it is edited.

Then it becomes 'spFindAllThings_3' when edited again.

Same rule applies to views.

While, this seems a bit extreme - I think it solves the problem.  Each version of the application will be hitting the DB in a non breaking way.  The code expects certain results from the views/stored procedures - and this keeps that 'contract' valid.  The problem is - it just seeps sloppy.  I know I can clean up old stored procedures after the app is deployed for awhile, but it just feels dirty.  Also - it depends on all of the developers following these rule, which will mostly happen, but I imagine someone will make a mistake.

Finally - My Question

Is this sloppy or hacky?

Is anybody else doing it this way?

How are other people solving this problem?


问:
Functional or non-functional requirement?
I'm wondering about functional or non-functional requirements. I have found lot of different definitions for those terms and I can't assign some of my requirement to proper category.

I'm wondering about requirements that aren't connected with some action or have some additional conditions, for example:

On the list of selected devices, device can be repeated.

Database must contain at least 100 items

Currency of some value must be in USD dollar.

Device must have a name and power consumption value in Watts.

are those requirements functional or non-functional ?

答:
These comments are all very good but they are way over-cooked and do not offer a clear template to work with. Wouldn't it be clear to specify it as:

In my opinion, a functional requirement is what the user experiences when using the application. It is requirement that need to be met when a developer tries to implement this from scratch, make enhancements or modifications. For example: the user should log in. Let's say if you also add a new way to run the application via a command prompt then the user still has to log in.

A non-functional requirement happens under the bonnet. The user is not aware of it, but it has to be there however it is implemented. For example: The application should be developed in C#. If it is developed in any other language the user will not notice. But that may be a requirement because it is based on existing code. Another example would be that it must be installed on certain server. Moving servers would not be noticed by the user.


答:
If you have lots of steps and need to exit as soon as one fails, consider putting function pointers in an array and execute all of them, like this:

```<code>// The array
int (*steps[2]) ();

// Assign functions
steps[0] = step_one;
steps[1] = step_two;

// Call them
for (int i = 0; i < 2; i++) {
     if (!(*steps[i])())
         break;
}
</code>```

This approach lets you configure during run-time in what order you which to run them as well.

Body:
If you have lots of steps and need to exit as soon as one fails, consider putting function pointers in an array and execute all of them, like this:

// The array
int (*steps[2]) ();

// Assign functions
steps[0] = step_one;
steps[1] = step_two;

// Call them
for (int i = 0; i < 2; i++) {
     if (!(*steps[i])())
         break;
}

This approach lets you configure during run-time in what order you which to run them as well.


问:
What is the best PHP ORM library?
I want to build a PHP web application, but always faces the problem that I need to connect to database and deal with related objects. So I tried codeigniter and it uses a special way to connect to database named Active Record and I've known that its an ORM technique and there are lot of ORM libraries out there.

What is the best, the easiest and the fastest of them?

答:
RedBean is what I use for such purpose: http://redbeanphp.com/

RedBean eases the development phase with automatic schema modifications, on the fly. it works very well with MySQL and SQLite but other databases supported by PDO should work too.

Title: What is the best PHP ORM library?

OwnerDisplayName: desfrenes


答:
If you say precisely and concisely what is desired, the compiler can produce the most efficient code.  Almost all the simple optimizations we used to do by hand are now done automatically by compilers.

You have no need for a state variable.  Have each function return true on success and false on failure, then write:

```<code>if (step_one()
    && step_two()
    && step_three()
    && ...) {
  /* success */
  ...
} else {
  /* failure */
  ...
}
...
</code>```

In most imperative programming languages, (C, Java, C#, Python, Perl, Ruby, LISP, et. al.) the and operator (&& or and) evaluates clauses left to right and stops as soon as one is false.

Body:
If you say precisely and concisely what is desired, the compiler can produce the most efficient code.  Almost all the simple optimizations we used to do by hand are now done automatically by compilers.

You have no need for a state variable.  Have each function return true on success and false on failure, then write:

if (step_one()
    && step_two()
    && step_three()
    && ...) {
  /* success */
  ...
} else {
  /* failure */
  ...
}
...

In most imperative programming languages, (C, Java, C#, Python, Perl, Ruby, LISP, et. al.) the and operator (&& or and) evaluates clauses left to right and stops as soon as one is false.


问:
How to refactor to cleaner version of maintaing states of the widget
Backstory

I inherited a bunch of code that I'd like to refactor. It is a UI application written in javascript.

Current state:

We have main application which consist of several UI components. And each component  has entry fields, textboxes, menus, etc), like "ticket", "customer information", etc. Based on input, where the application was called from, who is the user, we enable/disable, hide, show, change titles.

Unfortunately, the app grew to the point where it is really hard to scale, add new features. Main the driver (application code) calls set/unset functions of the respective components. So a lot of the stuff look like this

Main app unit

```<code>function1() {
   **call_function2()**
   component1.setX(true);
   component1.setY(true);
   component2.setX(false);
}

call_function2() {
       // it may repeat some of the code function1 called
}
</code>```

and we have a lot of this in the main union.

I am cleaning this mess. What is the best way to maintain the state of widgets?
Please let me know if you need me to clarify.

答:
Your issue sounds like a classic candidate for an MVC pattern.

If you continue, you'll likely end up implementing most of an MVC library, eventually. Probably your best bet is to switch to an existing one - http://javascriptmvc.com/ seems decent.