问:
Help identify the pattern for reacting on updates
There's an entity that gets updated from external sources. Update events are at random intervals. And the entity has to be processed once updated. Multiple updates may be multiplexed. In other words there's a need for the most current state of entity to be processed.

There's a point of no-return during processing where the current state (and the state is consistent i.e. no partial update is made) of entity is saved somewhere else and processing goes on independently of any arriving updates.

Every consequent set of updates has to trigger processing i.e. system should not forget about updates. And for each entity there should be no more than one running processing (before the point of no-return) i.e. the entity state should not be processed more than once.

So what I'm looking for is a pattern to cancel current processing before the point of no return or abandon processing results if an update arrives. The main challenge is to minimize race conditions and maintain integrity.

The entity sits mainly in database with some files on disk. And the system is in .NET with web-services and message queues.

What comes to my mind is a database queue-like table. An arriving update inserts row in that table and the processing is launched. The processing gathers necessary data before the point of no-return and once it reaches this barrier it looks into the queue table and checks whether there're more recent updates for the entity. If there are new updates the processing simply shuts down and its data is discarded. Otherwise the processing data is persisted and it goes beyond the point of no-return.

Though it looks like a solution to me it is not quite elegant and I believe this scenario may be supported by some sort of middleware.

If I would use message queues for this then there's a need to access the queue API in the point of no-return to check for the existence of new messages. And this approach also lacks elegance.

Is there a name for this pattern and an existing solution?

答: I would separate the "point-of-no-return" processor from the pre-setup piece. One service picks up the updates and does whatever setup to get ready for offline processing, and then before handing it over to the offline processor just checks either the database or if it's on a single machine you could use signals, in .NET EventWaitHandles named for the entity ID to see if any new updates came in. If so, the pre-processor just goes back to start with the new updates pulled in as it gets everything ready again for the offline processor. Each time it gets to offline processing point it does this check.</p>


问:
What does "Human Readable" mean? Is it a misnomer?
Two examples spring to mind:

One of the reasons that .Net programmers are encouraged to use .config files instead of the Windows Registry is that .config files are XML and therefore human-readable.

Similarly, JSON is sometimes considered human-readable compared with a proprietary format.

Are human-readable formats actually readable by humans? In the example of configuration data:

The format doesn't change the underlying meaning of the information - in both cases, the data represents the same thing.

Both registry and .config file are stored internally as a series 0s and 1s. To that extent, the underlying representaion is equally unreadable by humans.

Both registry and .config file require a tool to read, format and display those 0s and 1s and convert them into a format that humans can read. In the case of configuration stored in the Windows Registry, this is a Registry Editor. In the case of XML it could be a text editor or XML reader. Either way, the tool makes the data readable, not the data format.

So, what is the difference between human-readable data formats and non-human-readable formats?

答:
I think you may be asking whether "human-readable" as a term is sometimes incorrectly applied, and no-doubt it is.  In the example of registry entries vs .config files, I think it helps that you can arrange the XML in different ways depending on the data, intersperse comments and so on.

Collections in .config files are generally handled as multiple elements, while it's more difficult in the registry, often as as a MULTI_SZ.

You can also see more of the configuration data for an application at once - with regedit, to see something that is in a different key you need to navigate to that key, which means you can no longer see the entries you were previously looking at.  With .config files, you can see the entire file at once, even though that file may contain hierarchical data.

ContentLicense: CC BY-SA 2.5


问:
Should one generally develop a client library for REST services to help prevent API breakages?
We have a project where UI code will be developed by the same team but in a different language (Python/Django) from the services layer (REST/Java). The code for each layer exits in different code repositories and which can follow different release cycles. I'm trying to come up with a process that will prevent/reduce breaking changes in the services layer from the perspective of the UI layer.

I've thought to write integration tests at the UI layer level that we'll run whenever we build the UI or the services layer (we're using Jenkins as our CI tool to build the code which is in two Git repos) and if there are failures then something in the services layer broke and the commit is not accepted.

Would it also be a good idea (is it a best practice?) to have the developer of the services layer create and maintain a client library for the REST service that exists in the UI layer that they will update whenever there is a breaking change in their Service API? Conceivably, we would then have the advantage of a statically-typed API that the UI code builds against. If the client library API changes, then the UI code won't compile (so we'll know sooner that there was a breaking change). I'd also still run the integration tests upon building the UI or services layer to further validate that the integration between UI and the service(s) still works.

答:
In general, for methods of the API that are going away, pick a convention and 'deprecate' them, especially as soon as a full, replacement API is available and tested.  Leave the old API in place (essentially), but tag the method signature metadata or insert a logging event so usage can be clearly identified.

Logging within the service API is one thing, but alerting consuming clients is another.  For REST, I dont think there is a solid, standard practice.  FourSquare API clients can discover deprecated methods even if the called method is successful (HTTP 200 code, however errorType will be set to 'deprecated').  Possibly a reasonable strategy for providing consuming clients with the opportunity for knowledge of a deprecated method within the API without causing breakeage.

https://developer.foursquare.com/overview/responses

Within your API guidance, suggest a date or build release number where the deprecated API will be removed completely.  As you flesh our your strategy for deprecation, you will want to alert consumers of the API on what the proposed strategy is (how can they discover deprecated methods, how to transition to the replacement API, and when deprecated API will no longer be available if purged during an API cleanup), and solicit feedback from them to ensure the process is benificial to everyone.

ContentLicense: CC BY-SA 3.0


答: Versioning your API is another possibility. When a new version is deployed, leave the old version active as well and allow negotiation via the request. If you maintain the most recent 2 or 3 versions, then the UI code can upgrade at it's own pace.</p>

Title: Should one generally develop a client library for REST services to help prevent API breakages?

Body:
We have a project where UI code will be developed by the same team but in a different language (Python/Django) from the services layer (REST/Java). The code for each layer exits in different code repositories and which can follow different release cycles. I'm trying to come up with a process that will prevent/reduce breaking changes in the services layer from the perspective of the UI layer.

I've thought to write integration tests at the UI layer level that we'll run whenever we build the UI or the services layer (we're using Jenkins as our CI tool to build the code which is in two Git repos) and if there are failures then something in the services layer broke and the commit is not accepted.

Would it also be a good idea (is it a best practice?) to have the developer of the services layer create and maintain a client library for the REST service that exists in the UI layer that they will update whenever there is a breaking change in their Service API? Conceivably, we would then have the advantage of a statically-typed API that the UI code builds against. If the client library API changes, then the UI code won't compile (so we'll know sooner that there was a breaking change). I'd also still run the integration tests upon building the UI or services layer to further validate that the integration between UI and the service(s) still works.


答:
There are at least three questions at once, let's do them one-by-one

"is it a good idea to have a client library for the REST service?"

Most probably yes, as long as you don't want arbitrary REST calls directly scattered through all your UI code.

"is it a good idea to let the developer of the services layer create and maintain the lib?"

That depends on the persons in your team. The maintainer of the API should know both, the things available in the services layer as well as the requirements of the UI layer. So it may be either a person from the services layer or one from the UI layer, or (depending on the size and other tasks) a person independently from both teams.

[will we get an advantage from the fact that] "if the client library API changes, then the UI code won't compile"

Didn't you say the UI will be written in Python? That's not a statically-typed language, so I would not expect an immediate build break from an API change. I assume I got you wrong at this point and you have a statically typed API here - then you may get some advantages here as long as the build does not break when just adding some new features (like new optional parameters) to the API. Otherwise you will produce a lot of unneccessary overhead to your team.


问:
Execute code every hour
I need to create a web service that executes every hour.  It will be used to review data in a database and add alerts to a table in the same database if certain conditions are met/not met.    What we currently have is:

We have end devices that use Python to report to an Amazon Web Services (AWS) virtual server.  The AWS server takes that information and stores it in a MySQL database.  The AWS server is Linux running Django and Apache.  I need to be able to have some python code run every hour that verifies the data that has been stored by the end devices.  If certain conditions are not met then a record will be added to the alerts table in the database.

We originally contracted to have the above setup created.  I am new to Python, Django, and Apache.  However, I have already made several changes to the Python code that sends and also receives the data from the end devices.  I am a coder that is breaking into web programming.

Does anyone have any recommendations on how I can do this?

答:
You may want to look into APScheduler.  This is a quartz-like scheduler (although not as extensive) for Python.

This can be a far better alternative to externally run cron scripts for long-running applications (e.g. web applications), as it is platform neutral and can directly access your application’s variables and functions.

You can find a description for the most recent release here:
http://pypi.python.org/pypi/APScheduler/2.0.3

There is some documentation for installation/implementation here:
https://apscheduler.readthedocs.org/en/latest/

Here are some of the features:

No (hard) external dependencies

Thread-safe API

Excellent test coverage (tested on CPython 2.5 - 2.7, 3.3, Jython 2.5.3, PyPy 1.9)

Configurable scheduling mechanisms (triggers):

Cron-like scheduling

Delayed scheduling of single run jobs (like the UNIX “at” command)

Interval-based (run a job at specified time intervals)

Multiple, simultaneously active job stores:

RAM

File-based simple database (shelve)

SQLAlchemy (any supported RDBMS works)

MongoDB

Redis

Title: Execute code every hour


问:
Are injectable classes allowed to have constructor parameters in DI?
Given the following code:

```<code>class ClientClass{

    public function print(){
        //some code to calculate $inputString
        $parser= new Parser($inputString);
        $result= $parser->parse();
    }
}

class Parser{
    private $inputString;

    public __construct($inputString){
        $this->inputString=$inputString;
    }
    public function parse(){
        //some code
    }
}
</code>```

Now the ClientClass has dependency on class Parser. However, if I wanted to use Dependency Injection for unit testing it would cause a problem because now I can't send the input string to the parser constructor like before as its calculated inside ClientCalss itself:

```<code>class ClientClass{
        private $parser;
        public __construct(Parser $parser){
            $this->parser=$parser;
        }
        public function print(){
            //some code to calculate $inputString
            $result= $this->parser->parse(); //--> will throw an exception since no string was provided

        }
}
</code>```

The only solution I found was to modify all my classes that took parameters in their constructors to utilize Setters instead (example: setInputString()).

However, I think there might be a better solution than this because sometimes modifying existing classes can cause much harm than benefit.

So,

Are injectable classes not allowed to have input parameters?

If a class must take input parameters in its constructor, what would be the way to inject it properly?

UPDATE

Just for clarification, the problem happens when in my production code I decide to do this:

```<code>$clientClass= new ClientClass(new Parser($inputString));//--->I have no way to predict $inputString as it is calculated inside `ClientClass` itself.
</code>```

UPDATE 2

Again for clarification, I'm trying to find a general solution to the problem not for this example code only because some of my classes have 2, 3 or 4 parameters in their constructors not only one.

答:
Simple answer: Yes, they can have input parameters.  That is how I usually use DI and IoC.

The injection is done as soon as you can in your program.  As for testing, in your case, just inject a known string.  For other classes, you would have to actually make the parameter an Interface and either inject a mock class that does something known, or a mock object created from a mocking framework, which there are numerous open source and paid frameworks.

There is a wealth of information here.  Most of the code is in C#, but the ideas and theories behind it are well written


答:
```<code> > Are injectable classes allowed to have constructor parameters in DI?
</code>```

In java/spring it is possible to have classes that require paramaters in the constructor as stated by @Jeff Vanzella.

However in you example it is more difficuilt to use di because the creation of the parser is not fixed- it depends on a non static context ($inputString).

One possible general soultion to this is: the parser class constructor gets a contextlocator parameter that knows how to get the context.

```<code>class Parser{
    private $contextLocator;

    public __construct($contextLocator){
        $this->contextLocator=$contextLocator;
    }
    public function parse(){
        $inputString = $contextLocator->getContext()
        //some code
    }
}
</code>```

But this aproach adds unneccessary complexity to your soulotion. The use of a init-method that defines the context (or functionlly equivalent the use of a property to set the context as you suggested) is much easier.

in you special example this is not necessary. Move the parameter from the constructor to the parse method.

```<code>class Parser{
    private $inputString;

    public __construct(){
    }
    public function parse($inputString){
        $this->inputString=$inputString;
        //some code
    }
}
</code>```

Body:
Given the following code:

```<code>class ClientClass{

    public function print(){
        //some code to calculate $inputString
        $parser= new Parser($inputString);
        $result= $parser->parse();
    }
}

class Parser{
    private $inputString;

    public __construct($inputString){
        $this->inputString=$inputString;
    }
    public function parse(){
        //some code
    }
}
</code>```

Now the ClientClass has dependency on class Parser. However, if I wanted to use Dependency Injection for unit testing it would cause a problem because now I can't send the input string to the parser constructor like before as its calculated inside ClientCalss itself:

```<code>class ClientClass{
        private $parser;
        public __construct(Parser $parser){
            $this->parser=$parser;
        }
        public function print(){
            //some code to calculate $inputString
            $result= $this->parser->parse(); //--> will throw an exception since no string was provided

        }
}
</code>```

The only solution I found was to modify all my classes that took parameters in their constructors to utilize Setters instead (example: setInputString()).

However, I think there might be a better solution than this because sometimes modifying existing classes can cause much harm than benefit.

So,

Are injectable classes not allowed to have input parameters?

If a class must take input parameters in its constructor, what would be the way to inject it properly?

UPDATE

Just for clarification, the problem happens when in my production code I decide to do this:

```<code>$clientClass= new ClientClass(new Parser($inputString));//--->I have no way to predict $inputString as it is calculated inside `ClientClass` itself.
</code>```

UPDATE 2

Again for clarification, I'm trying to find a general solution to the problem not for this example code only because some of my classes have 2, 3 or 4 parameters in their constructors not only one.

Body:
 > Are injectable classes allowed to have constructor parameters in DI?

In java/spring it is possible to have classes that require paramaters in the constructor as stated by @Jeff Vanzella.

However in you example it is more difficuilt to use di because the creation of the parser is not fixed- it depends on a non static context ($inputString).

One possible general soultion to this is: the parser class constructor gets a contextlocator parameter that knows how to get the context.

class Parser{
    private $contextLocator;

    public __construct($contextLocator){
        $this->contextLocator=$contextLocator;
    }
    public function parse(){
        $inputString = $contextLocator->getContext()
        //some code
    }
}

But this aproach adds unneccessary complexity to your soulotion. The use of a init-method that defines the context (or functionlly equivalent the use of a property to set the context as you suggested) is much easier.

in you special example this is not necessary. Move the parameter from the constructor to the parse method.

class Parser{
    private $inputString;

    public __construct(){
    }
    public function parse($inputString){
        $this->inputString=$inputString;
        //some code
    }
}


问:
How effectively "sell" a good design in large meetings
Many times I have witnessed a sad tragedy.  Here's what happens:

A team design review for a new project.

I see a simple design that has quite a few holes.

I casually mention the holes and ways to avoid them.

The warnings are ignored with comments like "that 'never' happen in real life"

Eventually the things that "will 'never' happen" happen

An emergency team design review for a broken project.

So what do I do?  Copping the "I told you so" attitude is not going to win friends and influence people.  Sometimes years go by and the comments from step 3 are forgotten anyway.  I definitely don't want to be the annoying pest reminding the world of the gotchas.  I often sit back and watch the Titanic sail off to Europe.

It's frustrating to see bad designs move forward.  It's also frustrating that I can't seem to convince others of the pending peril of the current path.  I do worst on team meetings where everyone has different ways of understanding different terms.  Also, egos tend to win of reason and thought.  I'm looking for good tactics to convince groups people to use some new and complicated ideas.

答: Sounds like your best bet is to work to get yourself to a Team Lead Position. Use these opportunities to point out to the powers that be that you saw this coming and it could have been avoided. You shouldn't need to sell your current team short in doing so.</p>


问:
How to manage many mobile device users at server side?
I built a social Android application in which users can see other users around them by GPS location.  At the beginning thing went well as I had low number of users, but now that I have increasing number of users (about 1500 +100 every day) it has revealed a major problem in my design.

In my Google App Engine servlet I have static HashMap that holds all the users profiles objects, currently 1500 and this number will increase as more users register.

Why I'm doing it?

Every user that requests for the users around him compares his GPS with other users and checks if they are in his 10km radius.  This happens every five minutes on average.
Consequently, I can't get the users from db every time because GAE read/write operation quota will tear me apart.

The problem with this design is?

As the number of users increases, the Hashmap turns to null every 4-6 hours, I think that this time is getting shorter, but I'm not sure.
I'm fixing this by reloading the users from the db every time I detect that it becomes null, but this causes DOS to my users for 30 sec, so I'm looking for better solution.

I'm guessing that it happens because the size of the hashmap.  Am I right?

I have been advised to use a spatial database, but that means that I can't work with GAE any more and it means that I need to build my big server all over again and lose my existing DB.

Is there something I can do with the existing tools?

Thanks.

答:
There are a couple things I might suggest, without knowing much more about the specifics of your situation.  In many ways, the problem as stated is analogous to a common collision detection problem.

Reduce the Resolution.  In a way you have already taken steps to reduce the resolution by limited the update rate (to five minutes).  A second way would be to use a 'bounding box' concept over a specific point to identify closeness, or nearby users within an area.  In your case, each user would be assigned a surrounding rectangle.  If the rectangles of two users meet or interserct, then they are close enough to render/display in the same spot, and simply annotate each marker with more exact coordinates.

The data structure you are using might be ok, but it may need tuning.  Its hard to say without seeing some degree of implementation.  A possible alternative that generally works well with the bounding box concept is a quadtree; especially one that considers and handles periodic movement of contained objects.

Caching strategy.  If you aren't partitioning your cache into areas, or higher level quads, you may want to consider it.  This way, when updates do occur at your set interval, you only have to update the cache for the partial/selected areas where you a) have users and b) the users have moved.


问:
How can I improve the workflow between developer and designer with Expression Blend?
We use WPF and Expression Blend 4. I'm trying to improve our workflow by tutoring one of our designers to use it for styling and animation.

Slowly but surely I get the impression Blend in itself is to technical for the designer in question. I myself use it only occasionally (it's great for Visual States for instance) because a lot of things are easier done in code or not possible at all in Blend alone. It seems a developer with design experience is a lot more productive with it than a sole designer.

Are there any good resources or advice as to how I can improve this workflow?

答:
The answer to your question is likely going to require quite a bit more information, as advice on how to improve a workflow largely requires more knowledge about the current workflow, and what's wrong with it. Hopefully, the following can get you started in solving your problem.

First, ask yourself a few questions.

What is it that's leading you to believe that EB is too technical for your designer? Is s/he genuinely trying to learn it, but is somehow getting confused? Is s/he resistant to learning it because it's not Photoshop/Dreamweaver? Is s/he actually getting lost on the coding part, and not EB itself? Can s/he handle some coding in a different editor (SublimeText, Notepad++, vanilla Notepad)? It may not be EB that's the problem, or even the code, but the combination of both, if s/he is new to both EB and coding.

Additionally, what, exactly, is wrong with your current workflow? What are the problems you're running into, and how would teaching your designer Expression Blend fix these problems?

Then, ask yourself what, exactly, you want your designer (and your developer) to do.

Should the designer be responsible for actually writing out the styling and animation, or should that be left to the developer? How much styling/animation should the designer do before "escalating" it to the developer? What are the developer's responsibilities (the ones given solely to the developer)?

Finally, ask yourself if there's really anything to gain from having the designer learn Expression Blend, learn to code, or if there's a better way.

Is your developer experienced with front-end development? Is your designer? If your designer is not experienced, and your developer is, then why move the responsibilities? Are you actually gaining enough from that to compensate for the extra time required for the designer to learn and overcome the nuances that are involved in front-end coding and produce good code? HTML, CSS, and JavaScript are a lot more powerful than meets the eye, and all three tend to give you enough rope that it makes it very easy to hang yourself. Will the gains of having the designer write the front-end code compensate for the longer development time and more difficult to maintain code that will likely be a result?

If you do feel that the benefits outweigh the costs, then I recommend taking a step back and starting your designer out with learning to code. As I said, a new coder can easily write themselves into a corner with the front-end languages. Literally, start them out in a more basic text editor, with little more than syntax highlighting (Notepad++ might be a good starting place). That way, they need only focus on the code and not the code plus the editor. Once s/he is comfortable with and reasonably proficient at coding, then introduce Expression Blend. That way s/he isn't "drinking from the firehose" and getting overwhelmed.

The "learning to code" process can be broken down further, too, if necessary. Start him/her out with just some HTML, so s/he can see how the elements themselves lend to the design. Then add the basic CSS on top of it, and build up the CSS. After a while, you can then start to phase the JavaScript over, as well, the same way you did the CSS.

If your designer is already experienced in coding (and I mean actual coding, not using Dreamweaver's WYSIWYG editor), what advantages are gained by making him/her use EB?

In either situation, are you looking to use EB's WYSIWYG tools to do this stuff? If so, again ask "why?". What is your designer using now? Would teaching your designer to code (or letting him/her code if s/he already knows how), if you don't want your developers doing the styling and animations, be a better option?


问:
How can I create my own software license?
I have seen numerous licenses for any kind of software such as the GNU GPL, BSD License, MIT License, and LGPL. What is the process for creating a new software license, such as "John Doe's generic license"?</p>

答:
Answer the following questions for the user of your software:

Is your product open-source, i.e. can I get a copy of the source code?

How can I use your source code?  Can I freely copy it into my own applications, or do I have to link to your binary?  If I use your code in my own application, is there a limit to how much of your code I can use?  Do I have to include your license or attribution header at the top of any source files I redistribute that contain your code, or in the Help/About box of my binary?

What can I do with your product?  Can I use it one one computer?  Can I use it on more than one computer?  Can I redistribute it or resell it?

If I use your product as part of another application I write, do I have to be open-source also?

How do you warranty your product?  Are you legally liable if I have problems?

What are your redistribution terms?  Can I redistribute your product as part of a product I write?  If you provide source, can I modify your library and redistribute the modifications, and if so, what conditions do I have to meet?

Study other licenses, and see how they have answered these questions.


答:
It is actually surprisingly similar to what developers do:

You give a lawyer (or the legal department in a large corp) a list of requirements for what the license permits and what it does not permit (e.g. the license is for one user only, it's temporary, you cannot use the software for some purposes, etc.) and they "translate" this into lawyer-speak, pretty much like we translate requirements into code.

For example, "the license is for one user only" is usually translated into the something similar to this: "FooCorp Inc. grants you a single, non-exclusive, non-transferable license to  install and use FooSoftware for ...".

You might think this doesn't apply to F/OSS licenses, but it's more or less the same, except the requirements are different: you can find the simplest version of these requirements at http://opensource.org/docs/OSD.

But the lawyer part is essential and there's no point in trying to write a license by yourself (unless you're a lawyer with a lot of experience in IP-related and international law). Someone will just find a convenient loophole, which will allow him to use your product in a way he pleases (I'd go as far to compare this to exploits).

Of course I do not claim this explanation to be complete or even correct, but it's a rough sketch of the process, as far as software developers are involved (therefore I compare it to a programmer's work).

Title: How can I create my own software license?

Body: I have seen numerous licenses for any kind of software such as the GNU GPL, BSD License, MIT License, and LGPL. What is the process for creating a new software license, such as "John Doe's generic license"?</p>


问:
Is there an established convention for separating Windows file names in a string?
I have a function which needs to output a string containing a list of file paths. I can choose the separation character but I cannot change the data type (e.g. I cannot return a List<string> or something like that).

Wanting to use some well-established convention, my first intuition was to use the semicolon, similar to what Windows's PATH and Java's CLASSPATH (on Windows) environment variables do:

```<code>C:\somedir\somefile.txt;C:\someotherdir\someotherfile.txt
</code>```

However, I was surprised to notice that ; is a valid character in an NTFS file name.

So, is the established best practice to

just ignore this fact (i.e. "no sane person should use ; in a file name and if they do, it's their own fault") or

is there some other established character for separating Windows paths or files? (The pipe (|) might be a good choice, but I have not seen it used anywhere yet for this purpose.)

答: The windows PATH setting uses semicolons (;). Seems like that might be a good standard to follow.


答:
Open an editor.

Write terms of license.

Save file.

Include in project.

Generally speaking, that's all there is to it. Seriously.

Don't believe me? Check out Phil Sturgeon's Don't Be A Dick license (as well as the WTFPL that inspired it).

That said, it's hit or miss whether software licenses are legally enforceable, even if a lawyer wrote them (at least in the US, and it depends almost entirely on the whim of the judge or ruling copyright authority). More generally, though, as the software author, you are already covered by your country's copyright laws (assuming you've taken the steps for your work to be copyrighted; in the US, that's simply actually making the work).

It boils down to what you want to accomplish with your license, above and beyond (or in lieu of) copyright laws. In the case of such licenses like Phil's DBaD license, it's largely a matter of the honor principle and mutual respect of one another.

If you want it to be legally enforceable (or at least have a chance of doing so), such as releasing a closed-sourced product, then you'll very likely want to talk to a lawyer. That way, you can make sure there aren't any glaring loopholes and can have it written in such a way that a judge/ruling party is more likely to rule in your favor in the event that someone does violate it.

EllisLab (the company behind CodeIgniter) has a great explanation of software licensing (and entire week of blogs on the matter, in fact), both from a legal standpoint, and from the standpoint of a FLOSS developer and the honor principle I mentioned above.

(Disclaimer: I'm not a lawyer, this isn't legally binding advice, blah, blah, blah. I'm just a developer who's had to tip-toe around the legal minefield that is software development and licensing. When in doubt, talk to someone who actually is a lawyer, ideally with a copyright, patent, and/or licensing focus.)


答:
The easiest checks I can think of that qualify as "human readable" is:

in a location/file that can be easily accessed by external editors (this would make the registry not "human readable")

doesn't use non-displayable characters in the data structure.  If I make an Office 2000 Word doc with the text "test" inside, I might be able to open that in notepad and find the 4 characters "test" somewhere inside, but there will be a whole lot of other stuff around it.

While not required, formats that contain descriptive metadata are a plus.  A file that contains JohnSmith|34|T|F is less friendly than <User><Name>JohnSmith</Name><id>34</id><isActive>T</isActive><isAdmin>F</isAdmin></User>, as know what the fields are (at least generally) in the 2nd.

Title: What does "Human Readable" mean? Is it a misnomer?

Body:
Two examples spring to mind:

One of the reasons that .Net programmers are encouraged to use .config files instead of the Windows Registry is that .config files are XML and therefore human-readable.

Similarly, JSON is sometimes considered human-readable compared with a proprietary format.

Are human-readable formats actually readable by humans? In the example of configuration data:

The format doesn't change the underlying meaning of the information - in both cases, the data represents the same thing.

Both registry and .config file are stored internally as a series 0s and 1s. To that extent, the underlying representaion is equally unreadable by humans.

Both registry and .config file require a tool to read, format and display those 0s and 1s and convert them into a format that humans can read. In the case of configuration stored in the Windows Registry, this is a Registry Editor. In the case of XML it could be a text editor or XML reader. Either way, the tool makes the data readable, not the data format.

So, what is the difference between human-readable data formats and non-human-readable formats?


答:
Write down the terms, publish it with your software.  That's it.

One question, however, is why do you want to?  It is not unlikely that whatever conditions you wish to add are already present in another commonly-used licence.

This adds a preliminary step - check whether you actually have to create a licence.

It is also likely that some of the conditions you wish to enforce are flawed in some way;  adding another preliminary step - read around about the "unique" terms you want to apply.  Someone else is likely to have tried such terms, and found them unenforceable, or counterproductive in some way.


问:
Does immutability entirely eliminate the need for locks in multi-processor programming?

Part 1

Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough?  It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something (update a data store, produce a report, throw an exception, etc.).  Can such actions always be done without locks?  Does the mere action of throwing out each object and creating a new one instead of changing the original (a crude view of immutability) provide absolute protection from inter-process contention, or are there corner cases which still require locking?

I know a lot of functional programmers and mathematicians like to talk about "no side effects" but in the "real world" everything has a side effect, even if it's the time it takes to execute a machine instruction.  I'm interested in both the theoretical/academic answer and the practical/real-world answer.

If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly.  Some examples of possible boundaries:

I/O

Exceptions/errors

Interactions with programs written in other languages

Interactions with other machines (physical, virtual, or theoretical)

Special thanks to @JimmaHoffa for his comment which started this question!

Part 2

Multi-processor programming is often used as an optimization technique - to make some code run faster.  When is it faster to use locks vs. immutable objects?

Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones?

Summary

I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.

答:
I'm unsure if I understood your questions.

IMHO the answer is yes. If all your objects are immutable, then you don't need any locks. But if you need to preserve a state (e.g. you implement a database or you need to aggregate the results from multiple threads) then you need to use mutability and therefore also locks. Immutability eliminates the need for locks, but usually you cannot afford to have completely immutable applications.

Answer to part 2 - locks should be always slower than no locks.


答:
To answer your question, anyone can write a license - and it shows!

Those of us who use software to build things and actually try to respect each license are ready to gouge our own eyeballs out with a hot poker every time someone talks about making new one.  There are already an uncountable number of software licenses in the world.  99% of them are a near duplicates of existing, more popular licenses, except not as well thought out.

One site I contribute to has a home-grown creative-commons non-commercial attribution type license, except it says nothing about derivative works.  Are they allowed?  Can they be distributed under the same license?  Beats me!

If other people contribute to a project and you ever want or need to change the license, you need to get them all to agree to change the license, or you are more-or-less stuck with it forever.  Some of them might become unreachable or even die.  I am not a lawyer, but if you don't have a signed contributor agreement from everyone that lets you make decisions about your license, I think you are SOL.

It's really hard to write a good license.  Even the best software licenses are full of holes.  There are new versions of the Apache and GPL licenses periodically.  Please, see if you can find a license which meets 90% of your needs and use it.  The GPL Linking Exception or "Classpath Exception" is a great example of this.  I'm a little worried about the statement the Hibernate people had on their site a few years, basically publicly mis-interpreting the GPLv2 to make it sound like it included the Classpath Exception.  Is that the classpath exception?  We won't know unless someone sues them.

It seems to me that getting sued is the most painful way to debug your license.  If you use a license that people have sued-over already, there is a certain assurance that it works, and also a sense of how it works.  Better yet, pick a license that has been to court in different countries.  Did you think about how your license would be interpreted in other parts of the world?

If you base your license off an existing one, then people who care about fulfilling the terms of your license might not have to study it for years to figure out exactly what it means.

If at all possible, I would encourage you to devote your energies and talents to improving an existing license rather than writing a new one.

Sorry to be such a kill-joy.  If I'm bitter, it's because I really read and try to respect people's licenses before I use their works.


问:
A list of the most important areas to examine when moving a project from x86 to x64?
I know to check for/use asserts and carefully examine any assembly components, but I didn't know if anyone out there has a fairly comprehensive or industry standard check-list of specific things at which to look?  I am looking more at C and C++.

note: There are some really helpful answers, I'm just leaving the question open for a couple days in case some folks only check questions that don't have accepted answers.

答:
Testing is one of the most important things to consider. Most software testing is based on "grandfathering" - functionality that used to work and has not changed will be OK for this release. What you will find with moving to 64 bit (unless your code is particularly good) is issues that have not had symptoms previously will come up - sometimes in weird and unexplained ways. Things like buffer overflows previously "contained", assumptions about data sizes causing new buffer overflows, dodgy pointer math etc. </p>

<p>The amount will largely depend on the quality of the code base - in one case it took a very long time to get from "finished" to "customer acceptance". </p>

Body:
Testing is one of the most important things to consider. Most software testing is based on "grandfathering" - functionality that used to work and has not changed will be OK for this release. What you will find with moving to 64 bit (unless your code is particularly good) is issues that have not had symptoms previously will come up - sometimes in weird and unexplained ways. Things like buffer overflows previously "contained", assumptions about data sizes causing new buffer overflows, dodgy pointer math etc.

The amount will largely depend on the quality of the code base - in one case it took a very long time to get from "finished" to "customer acceptance".


问:
What can I do in order to inform users of potential errors in my software in order to minimize liability?
I'm an independent software developer that's spent the last few months creating software for viewing and searching map data. The software has some navigation functionality as well (mapping, directions,etc). The eventual goal is to sell it in mobile app markets. I use OpenStreetMap as my data source.

I'm concerned about liability for erroneous map data / routing instructions, etc that might result when someone uses the application. There are a lot of stories on the internet where someone gets into an accident or gets stuck or gets lost because of their GPS unit/Google Maps/mapping app... I myself have come across incorrect map data as well in a GPS unit I have in my car.

While I try to make my own software as bug free as possible, no software is truly bug free. And moving beyond what I can control, OpenStreetMap data (and street map data in general) is prone to errors as well.

What steps can I take to clearly inform the user that results from the software aren't always perfect, and to minimize my liability?

答:
Fairly straightforward steps:

Include boilerplate generic warnings, as you might see in many other pieces of software, and include them as part of a license agreement for users to agree to before they use your software

Add a specific clause to the license agreement, informing users that you are not responsible for the map data that you're providing, and that it should not be used for emergency or other uses that require high availability and correctness

Form a limited liability or other corporation, and publish the software as that entity rather than under your own name.


问:
Recent programming language for AI?
For a few decades the programming language of choice for AI was either Prolog or LISP, and a few more others that are not so well known. Most of them were designed before the 70's.

Changes happens a lot on many other domains specific languages, but in the AI domain it hadn't surfaced so much as in the web specific languages or scripting etc.

Are there recent programming languages that were intended to change the game in the AI and learn from the insufficiencies of former languages?

答:
You may find answers to your questions in a recent special issue “Sprachen der KI” (“Languages of AI”) of the German AI journal KI - Künstliche Intelligenz, Volume 26, Number 1 / February 2012, published by Springer. I am the co-author of one part of a discussion paper included in it: “What Language Do You Use To Create Your AI Programs and Why?” Here is a preprint of it: http://ai.cs.unibas.ch/papers/schmid-et-al-kijournal2012.pdf

In summary, some AI researchers still swear by the classic AI languages Lisp and Prolog. Others use mainstream languages like C++, Java, or Python. Still others like to explore new esoteric programming languages.

I believe there is nothing special about AI that would require special programming languages. What researchers in general want is programming languages that allow rapid prototyping. This is something old AI languages (Lisp, Prolog) and newer “scripting” languages (Perl, Python, Ruby, or recent JVM languages such as Clojure) are great for.

Some researchers want to go beyond prototyping, or they have special requirements (e.g. big data) and need to re-implement their algorithms in compiled or strongly typed languages such as C, C++ or Java once the exploratory programming phase is over and they have a better grip of the problem. Some would say that at that point (when the problem is well-understood), you are no longer dealing with AI.

Coming back to your last question, all the significant developments in new AI languages I am aware of are inspired by constraint-based programming. Some have entered Prolog implementations such as SICStus and SWI, others have spawned Prolog-like languages such as Mercury and Mozart/Oz. Of course there are likely to be significant new developments I am not aware of.

Title: Recent programming language for AI?


答:
This is an oddly phrased question that is really, really broad if answered fully. I'm going to focus on clearing up some of the specifics that you're asking about.

Immutability is a design trade off. It makes some operations harder (modifying state in large objects quickly, building objects piecemeal, keeping a running state, etc.) in favor of others (easier debugging, easier reasoning about program behavior, not having to worry about things changing underneath you when working concurrently, etc.). It's this last one we care about with this question, but I want to emphasize that it is a tool. A good tool that often solves more problems than it causes (in most modern programs), but not a silver bullet... Not something that changes the intrinsic behavior of programs.

Now, what does it get you? Immutability gets you one thing: you can read the immutable object freely, without worrying about its state changing underneath you (assuming it is truly deeply immutable... Having an immutable object with mutable members is usually a deal breaker). That's it. It frees you from having to manage concurrency (via locks, snapshots, data partitioning or other mechanisms; the original question's focus on locks is... Incorrect given the scope of the question).

It turns out though that lots of things read objects. IO does, but IO itself tends to not handle concurrent use itself well. Almost all processing does, but other objects may be mutable, or the processing itself might use state that is not friendly to concurrency. Copying an object is a big hidden trouble point in some languages since a full copy is (almost) never an atomic operation. This is where immutable objects help you.

As for performance, it depends on your app. Locks are (usually) heavy. Other concurrency management mechanisms are faster but have a high impact on your design. In general, a highly concurrent design that makes use of immutable objects (and avoids their weaknesses) will perform better than a highly concurrent design that locks mutable objects. If your program is lightly concurrent then it depends and/or doesn't matter.

But performance should not be your highest concern. Writing concurrent programs is hard. Debugging concurrent programs is hard. Immutable objects help improve your program's quality by eliminating opportunities for error implementing concurrency management manually. They make debugging easier because you're not trying to track state in a concurrent program. They make your design simpler and thus remove bugs there.

So to sum up: immutability helps but will not eliminate challenges needed to handle concurrency properly. That help tends to be pervasive, but the biggest gains are from a quality perspective rather than performance. And no, immutability does not magically excuse you from managing concurrency in your app, sorry.

Title: Does immutability entirely eliminate the need for locks in multi-processor programming?

Body:
Part 1

Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough?  It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something (update a data store, produce a report, throw an exception, etc.).  Can such actions always be done without locks?  Does the mere action of throwing out each object and creating a new one instead of changing the original (a crude view of immutability) provide absolute protection from inter-process contention, or are there corner cases which still require locking?

I know a lot of functional programmers and mathematicians like to talk about "no side effects" but in the "real world" everything has a side effect, even if it's the time it takes to execute a machine instruction.  I'm interested in both the theoretical/academic answer and the practical/real-world answer.

If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly.  Some examples of possible boundaries:

I/O

Exceptions/errors

Interactions with programs written in other languages

Interactions with other machines (physical, virtual, or theoretical)

Special thanks to @JimmaHoffa for his comment which started this question!

Part 2

Multi-processor programming is often used as an optimization technique - to make some code run faster.  When is it faster to use locks vs. immutable objects?

Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones?

Summary

I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.


问:
What methods of requirements elicitation are suitable when I do not have direct access to the user base?
I am working on an application to create invoices. There are some features that are required based on the type of the application and are common to all invoice applications. However, we still need to determine what unique needs the user base might have. We do not have direct access to the users to obtain requirements or user stories. What techniques are most suitable for eliciting high-quality requirements from users when direct or frequent access is not possible?</p>

答:
When you don't have frequent two-way communication with potential users, getting requirements done right becomes more difficult. The first thing that I would do is to find some kind of domain expert to use to help refine and clarify any requirements that you have and to answer domain-specific questions that might come up in requirements and design activities. This person might not be representative of your user base at all, but at least they have knowledge that you can use to make informed decisions in the absence of user contact.

Following this, there are a number of requirements elicitation techniques that you can use to actually gather requirements:

Documentation. If this system is replacing an existing system, you can find out what that system does. If you made that system, use that entire requirements specification, if you can find it. If there are competing systems out there, find out what they do. This is probably best to determine functional requirements, and you can use some data elements (like frequency of occurrence over multiple systems) to start to prioritize functionality in your system.

Defect or Enhancement Requests. If you have access to an existing system's defect or enhancement tracker, find out what people are asking for. This will let you find out what problems might exist, develop an understanding of what your system might do, and find a niche in the market for your application if you can deliver features your competitors don't have.

Laws and Regulations. If the system is intended for deployment in an environment that must conform to various laws or regulations, determine what those laws and regulations are. Those must be captured as part of your business requirements.

Surveys and Questionnaires. Contact as many potential users as you can. Find out what they need and what they want in this type of system. Analyze this for commonalities. Be aware of conflicting requirements, however.

Something to keep in mind is that there might be a number of different classes of potential user, each with different expectations. It might not be possible to fully satisfy the requirements of each one. In fact, some requirements generated by people of different user classes might even be in conflict, meaning you can't actually satisfy all of them in a given application.

You also tagged this question with the agile tag. One of the tenants of the agile methods is to be able to release quickly. If you can build a system and find early adopters to use it, you can then build up your own set of customer requirements through your defect and enhancement tracking system.

The two oft-cited resources for requirements engineering are Software Requirements and More About Software Requirements: Thorny Issues and Practical Advice, both written by Karl Wiegers. Although I've never read them, I also understand that Agile Software Requirements: Lean Requirements Practices for Teams, Programs, and the Enterprise by Dean Leffingwell and Writing Effective Use Cases by Alistair Cockburn are highly recommended in the agile community.


问:
Being productive during downtime
Lets say you are somewhere where coding and getting online isn't possible (On a busy flight, for example)what do you do to stay productive?

Things I would do are read whatever tech book I am currently slogging through and maybe doodle some UI stuff or workflows.  What else could I be doing?

答:
I'd break up the available time:

1/4 Rest

1/4 do something fun

1/4 do something creative

1/4 read something technical.

Title: Being productive during downtime


问:
"Never do in code what you can get the SQL server to do well for you" - Is this a recipe for a bad design?
It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.

答:
There are a few things to remember:

A relational database should ensure referential integrity through foreign keys

Scaling one database can be difficult and expensive. Scaling a web server is a lot easier simply by adding more web servers. Have fun trying to add more SQL server power.

With C# and LINQ, you can do your "joins" and whatnot through code so you kind of get the best of both worlds in many cases


答: If you're really worried - talk to an insurance agent about an 'errors and omissions' policy - I didn't say buy one, just talk to them - you'll probably learn a lot and its cheaper than a lawyer - which, as previous posters observed, you're gonna need</p>

Title: What can I do in order to inform users of potential errors in my software in order to minimize liability?

Body:
I'm an independent software developer that's spent the last few months creating software for viewing and searching map data. The software has some navigation functionality as well (mapping, directions,etc). The eventual goal is to sell it in mobile app markets. I use OpenStreetMap as my data source.

I'm concerned about liability for erroneous map data / routing instructions, etc that might result when someone uses the application. There are a lot of stories on the internet where someone gets into an accident or gets stuck or gets lost because of their GPS unit/Google Maps/mapping app... I myself have come across incorrect map data as well in a GPS unit I have in my car.

While I try to make my own software as bug free as possible, no software is truly bug free. And moving beyond what I can control, OpenStreetMap data (and street map data in general) is prone to errors as well.

What steps can I take to clearly inform the user that results from the software aren't always perfect, and to minimize my liability?


问:
Is it OK to push my code to GitHub while it is still in early development?
I have some projects that are in a very early development state. They are nowhere nearing completion but I do host them (as public repos) on GitHub because:

I have multiple computers and I want access to my code everywhere

I want a backup for my code

I want it to be easy if someone wants to collaborate in some way

I use GitHub Issues as a poor man's project management software

Is it OK to publish a project on GitHub even when it is very early in the development? I am a bit concerned about someone to come by and say OMG this is total BS, this code is so bad! while looking at unpolished/still in development/not tested code.

What are your practices when you start new public projects? Do you wait until you have something substantial to show or you create a bare repo directly on GitHub and start from there?

I used GitHub throughout this post but this applies to every code hosting service out there.

答:
I would say that it depends upon whether you think the code is incomplete or just plain bad.  If bad, you may want to consider whether you are now or might soon be looking for a new position; and whether or not the code is discoverable if a potential employer is researching you.

OTOH, even bad code might be considered a bonus, particulaly if it is commented as such.

My advice: decide with care.


答:
A function that accepts some value and returns some other value, and doesn't disturb anything outside of the function, has no side effects, and is therefore thread-safe.  If you want to consider things like how the way the function executes affects power consumption, that's a different problem.

I am assuming that you're referring to a Turing-complete machine that is executing some sort of well-defined programming language, where the implementation details are irrelevant. In other words, it shouldn't matter what the stack is doing, if the function I'm writing in my programming language of choice can guarantee immutability within the confines of the language. I don't think about the stack when I'm programming in a high-level language, nor should I have to.

To illustrate how this works, I'm going to offer a few simple examples in C#.  In order for these examples to be true, we have to make a couple of assumptions.  First, that the compiler follows the C# specification without error, and second, that it produces correct programs.

Let's say I want a simple function that accepts a string collection, and returns a string that is a concatenation of all of the strings in the collection separated by commas.  A simple, naïve implementation in C# might look like this:

```<code>public string ConcatenateWithCommas(ImmutableList<string> list)
{
    string result = string.Empty;
    bool isFirst = false;

    foreach (string s in list)
    {
        if (isFirst)
            result += s;
        else
            result += ", " + s;
    }
    return result;
}
</code>```

This example is immutable, prima facie.  How do I know that?  Because the string object is immutable.  However, the implementation is not ideal.  Because result is immutable, a new string object has to be created each time through the loop, replacing the original object that result points to.  This can negatively affect speed and put pressure on the garbage collector, since it has to clean up all of those extra strings.

Now, let's say I do this:

```<code>public string ConcatenateWithCommas(ImmutableList<string> list)
{
    var result = new StringBuilder();
    bool isFirst = false;

    foreach (string s in list)
    {
        if (isFirst)
            result.Append(s);
        else
            result.Append(", " + s);
    }
    return result.ToString();
}
</code>```

Notice that I've replaced string result with a mutable object, StringBuilder.  This is much faster than the first example, because a new string is not created each time through the loop.  Instead, the StringBuilder object merely adds the characters from each string to a collection of characters, and outputs the whole thing at the end.

Is this function immutable, even though StringBuilder is mutable?

Yes, it is.  Why?  Because each time this function is called, a new StringBuilder is created, just for that call.  So now we have a pure function that is thread-safe, but contains mutable components.

But what if I did this?

```<code>public class Concatenate
{
    private StringBuilder result = new StringBuilder();
    bool isFirst = false;

    public string ConcatenateWithCommas(ImmutableList<string> list)
    {
        foreach (string s in list)
        {
            if (isFirst)
                result.Append(s);
            else
                result.Append(", " + s);
        }
        return result.ToString();
    }
}
</code>```

Is this method thread-safe?  No, it isn't.  Why?  Because the class is now holding state on which my method depends.  A race condition is now present in the method: one thread may modify IsFirst, but another thread may perform the first Append(), in which case I now have a comma at the beginning of my string which is not supposed to be there.

Why might I want to do it like this?  Well, I might want the threads to accumulate the strings into my result without regard to order, or in the order that the threads come in.  Maybe it's a logger, who knows?

Anyway, to fix it, I put a lock statement around the method's innards.

```<code>public class Concatenate
{
    private StringBuilder result = new StringBuilder();
    bool isFirst = false;
    private static object locker = new object();

    public string AppendWithCommas(ImmutableList<string> list)
    {
        lock (locker)
        {
            foreach (string s in list)
            {
                if (isFirst)
                    result.Append(s);
                else
                    result.Append(", " + s);
            }
            return result.ToString();
        }
    }
}
</code>```

Now it's thread-safe again.

The only way that my immutable methods could possibly fail to be thread-safe is if the method somehow leaks part of its implementation.  Could this happen?  Not if the compiler is correct and the program is correct.  Will I ever need locks on such methods?  No.

For an example of how implementation could possibly be leaked in a concurrency scenario, see here.

Body:
A function that accepts some value and returns some other value, and doesn't disturb anything outside of the function, has no side effects, and is therefore thread-safe.  If you want to consider things like how the way the function executes affects power consumption, that's a different problem.

I am assuming that you're referring to a Turing-complete machine that is executing some sort of well-defined programming language, where the implementation details are irrelevant. In other words, it shouldn't matter what the stack is doing, if the function I'm writing in my programming language of choice can guarantee immutability within the confines of the language. I don't think about the stack when I'm programming in a high-level language, nor should I have to.

To illustrate how this works, I'm going to offer a few simple examples in C#.  In order for these examples to be true, we have to make a couple of assumptions.  First, that the compiler follows the C# specification without error, and second, that it produces correct programs.

Let's say I want a simple function that accepts a string collection, and returns a string that is a concatenation of all of the strings in the collection separated by commas.  A simple, naïve implementation in C# might look like this:

public string ConcatenateWithCommas(ImmutableList<string> list)
{
    string result = string.Empty;
    bool isFirst = false;

    foreach (string s in list)
    {
        if (isFirst)
            result += s;
        else
            result += ", " + s;
    }
    return result;
}

This example is immutable, prima facie.  How do I know that?  Because the string object is immutable.  However, the implementation is not ideal.  Because result is immutable, a new string object has to be created each time through the loop, replacing the original object that result points to.  This can negatively affect speed and put pressure on the garbage collector, since it has to clean up all of those extra strings.

Now, let's say I do this:

public string ConcatenateWithCommas(ImmutableList<string> list)
{
    var result = new StringBuilder();
    bool isFirst = false;

    foreach (string s in list)
    {
        if (isFirst)
            result.Append(s);
        else
            result.Append(", " + s);
    }
    return result.ToString();
}

Notice that I've replaced string result with a mutable object, StringBuilder.  This is much faster than the first example, because a new string is not created each time through the loop.  Instead, the StringBuilder object merely adds the characters from each string to a collection of characters, and outputs the whole thing at the end.

Is this function immutable, even though StringBuilder is mutable?

Yes, it is.  Why?  Because each time this function is called, a new StringBuilder is created, just for that call.  So now we have a pure function that is thread-safe, but contains mutable components.

But what if I did this?

public class Concatenate
{
    private StringBuilder result = new StringBuilder();
    bool isFirst = false;

    public string ConcatenateWithCommas(ImmutableList<string> list)
    {
        foreach (string s in list)
        {
            if (isFirst)
                result.Append(s);
            else
                result.Append(", " + s);
        }
        return result.ToString();
    }
}

Is this method thread-safe?  No, it isn't.  Why?  Because the class is now holding state on which my method depends.  A race condition is now present in the method: one thread may modify IsFirst, but another thread may perform the first Append(), in which case I now have a comma at the beginning of my string which is not supposed to be there.

Why might I want to do it like this?  Well, I might want the threads to accumulate the strings into my result without regard to order, or in the order that the threads come in.  Maybe it's a logger, who knows?

Anyway, to fix it, I put a lock statement around the method's innards.

public class Concatenate
{
    private StringBuilder result = new StringBuilder();
    bool isFirst = false;
    private static object locker = new object();

    public string AppendWithCommas(ImmutableList<string> list)
    {
        lock (locker)
        {
            foreach (string s in list)
            {
                if (isFirst)
                    result.Append(s);
                else
                    result.Append(", " + s);
            }
            return result.ToString();
        }
    }
}

Now it's thread-safe again.

The only way that my immutable methods could possibly fail to be thread-safe is if the method somehow leaks part of its implementation.  Could this happen?  Not if the compiler is correct and the program is correct.  Will I ever need locks on such methods?  No.

For an example of how implementation could possibly be leaked in a concurrency scenario, see here.


问:
What is the difference between "good" designers and "great" designers?
While reading this wikipedia article, Brookes has told that there is a difference between "good" designers and "great" designers.  What is the difference between them? How can I decide if a designer is good or great?</p>

答: A good designer can design for simplicity or flexibility or efficiency or robustness.  A great designer has a deep understanding of the tradeoffs involved and can effectively balance all of these and come up with a solution that satisfies all of them reasonably well.


问:
DB Object passing between classes singleton, static or other?
So I'm designing a reporting system at work it's my first project written OOP and I'm stuck on the design choice for the DB class.

Obviously I only want to create one instance of the DB class per-session/user and then pass it to each of the classes that need it. What I don't know it what's best practice for implementing this. Currently I have code like the following:-

```<code>class db
{
    private $user = 'USER';
    private $pass = 'PASS';
    private $tables = array( 'user','report', 'etc...');

    function __construct(){
        //SET UP CONNECTION AND TABLES
    }
};

class report{
function __construct ($params = array(), $db, $user)
 {
    //Error checking/handling trimed
    //$db is the database object we created
    $this->db = $db;

    //$this->user is the user object for the logged in user
    $this->user = $user;

    $this->reportCreate();
 }

public function setPermission($permissionId = 1)
{
    //Note the $this->db is this the best practise solution?
   $this->db->permission->find($permissionId)

    //Note the $this->user is this the best practise solution?
    $this->user->checkPermission(1)

    $data=array();
    $this->db->reportpermission->insert($data)
}
};//end report
</code>```

I've been reading about using static classes and have just come across Singletons (though these appear to be passé already?) so what's current best practice for doing this?

答:
Singletons in PHP are quite useless, your instances are created when the script is executed, and die when the script ends, regardless of whether they are singletons or not. This is by design, PHP follows a share nothing architecture.

Just continue doing what you already do, it even has a fancy name: constructor injection. Read up on dependency injection, and if you want to make your constructor a bit more robust, consider type hinting:

```<code>class report {
    function __construct (array $params = array(), db $db, $user)
    {
        ....
    }

    ...
}
</code>```

Further reading:

When is Singleton appropriate? (and it's dupe: The Singleton Pattern)

What is so bad about Singletons?

When is it not appropriate to use the dependency injection pattern?

What are the benefits of using Dependency Injection and IoC Containers?

Dependency Injection and Singleton. Are they two entirely different concepts?

Dependency injection: How to sell it

Difference between Dependency Injection (DI) and Inversion of Control (IOC)

Dependency injection: what belongs in the constructor?

S.O.L.I.D., avoiding anemic domains, dependency injection?

Static methods vs singletons: choose neither

Body:
Singletons in PHP are quite useless, your instances are created when the script is executed, and die when the script ends, regardless of whether they are singletons or not. This is by design, PHP follows a share nothing architecture.

Just continue doing what you already do, it even has a fancy name: constructor injection. Read up on dependency injection, and if you want to make your constructor a bit more robust, consider type hinting:

class report {
    function __construct (array $params = array(), db $db, $user)
    {
        ....
    }

    ...
}

Further reading:

When is Singleton appropriate? (and it's dupe: The Singleton Pattern)

What is so bad about Singletons?

When is it not appropriate to use the dependency injection pattern?

What are the benefits of using Dependency Injection and IoC Containers?

Dependency Injection and Singleton. Are they two entirely different concepts?

Dependency injection: How to sell it

Difference between Dependency Injection (DI) and Inversion of Control (IOC)

Dependency injection: what belongs in the constructor?

S.O.L.I.D., avoiding anemic domains, dependency injection?

Static methods vs singletons: choose neither


问:
What does "Human Readable" mean? Is it a misnomer?
Two examples spring to mind:

One of the reasons that .Net programmers are encouraged to use .config files instead of the Windows Registry is that .config files are XML and therefore human-readable.

Similarly, JSON is sometimes considered human-readable compared with a proprietary format.

Are human-readable formats actually readable by humans? In the example of configuration data:

The format doesn't change the underlying meaning of the information - in both cases, the data represents the same thing.

Both registry and .config file are stored internally as a series 0s and 1s. To that extent, the underlying representaion is equally unreadable by humans.

Both registry and .config file require a tool to read, format and display those 0s and 1s and convert them into a format that humans can read. In the case of configuration stored in the Windows Registry, this is a Registry Editor. In the case of XML it could be a text editor or XML reader. Either way, the tool makes the data readable, not the data format.

So, what is the difference between human-readable data formats and non-human-readable formats?

答:
Human readable basically means that if the content is displayed by a program that lacks direct, specific awareness of that file's format, that there's at least a reasonable chance that a person can read and understand at least some of it.

Your basic point about the lack of a clear line of delineation is absolutely correct though --at one time I knew a guy who could diagnose problems with programs (mostly written in Fortran) often in five minutes or less -- going only from an octal core dump, without looking at the source code at all. For most people, that format would hardly qualify as "human readable", but obviously he was an exception...


问:
Should I open Source my iOS application?
I developed an iOS application as a student and I am currently distributing it for free in the app store. I have received a few enquires about adding features to the app including one person who would like the app to be open source so they can add features themselves.

What concerns should I have if I open source my iOS application?

Which open source license should I use?

答:
You can use any open-source license you want, with the exception of the GPL, which is incompatible with the Terms of Service of the Apple Store.

See the the regulations of the Apple Store in the Wikipedia.


答:
You could take out your notepad and review your apps design and architecture. Sometimes looking at it after a while helps you see additional venues.

If you're developing in one of the "framework intensive" langs, like C# or Java, you could explore some pieces of the framework, or just read about langugage syntactic sugar that you didn't have time to check out before.

Having gained additional mastery of your development platform will make you more productive once you're back in work environment.

Title: Being productive during downtime

Body:
Lets say you are somewhere where coding and getting online isn't possible (On a busy flight, for example)what do you do to stay productive?

Things I would do are read whatever tech book I am currently slogging through and maybe doodle some UI stuff or workflows.  What else could I be doing?


问:
two ways of doing the same thing, what is preferred?
I have some context

then I can do:

with context.getError(Object): ErrorHolder

holder.addError(error)

OR

context.setError(Object, error)

setError will probably have this implementation:

context.getError(Object).addError(error)

what approach should I choose and why?

答:
I'm a fan of keeping things simple. This enhances readability and the usability of an API. I don't think there's a definitive answer, But I would go for the second approach, although I would call the method context.addError(object, error), for this implies, that their could be more than one error, which is the case, when I look at your possible implementation.

The getError(object)-approach lacks good naming too, I think. If you choose the first approach consider naming the Method getErrorHolder(object).getError().

EDIT: If I still get you wrong, that's a sign for ambigious naming. Use add for adding to a Collection and set for single instances.


问:
Why didn't "cloud computing" offer appear earlier?
Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago.

What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?

答:
What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?

As other posters have mentioned, the one critical change was ubiquitous access to high speed internet.

The other critical change was the advancement of interactivity in websites. The modern-day richness in web user interfaces is what effectively allowed more and more traditionally desktop applications to be served via the cloud.


答:
Isn't this a case where you would be 'violating' the Law of Demeter ?

The second one, provided you use a name like context.addError(object, error) if you can actually have several errors on an object, hides ErrorHandler to the clients of context. Is ErrorHandler an implementation detail, or could clients of 'context' use it too ?

Title: two ways of doing the same thing, what is preferred?

Body:
I have some context

then I can do:

with context.getError(Object): ErrorHolder

holder.addError(error)

OR

context.setError(Object, error)

setError will probably have this implementation:

context.getError(Object).addError(error)

what approach should I choose and why?


问:
Optimal buffer size for fread/fwrite
What buffer size should I choose for read/write files via POSIX fread/fwrite functions?</p>

答:
The ANSI/ISO fread/fwrite functions are buffered. The buffer is usually 8 KiB and that gives the granularity independent of what you use in your code. It might make sense to increase the buffer a bit, perhaps to the value below. For bulk transfer they will always be a tiny bit slower though due to the extra copies.

For the POSIX read/write functions it depends on operating system and device and a lot of other things, but practical experience is that you don't get any performance improvement by increasing the buffer beyond tens of KiB, so 32 or 64 KiB is about right.

On some systems the dependency is larger than on others. On Linux the difference is usually minimal above 8 KiB (so the default buffer is fine), e.g. on Windows CE (using native API; they don't have POSIX) even bigger than 64 KiB still help. It might also depend on the device.

Title: Optimal buffer size for fread/fwrite


答:
I would definitely go with the second method. Why?

Well it seems to be the simplest answer. In the first instance it will require two calls everytime you need to add or get an error from your context.

There is another alternative, provided that you are providing your Object classes and they are not generated by some 3rd party lib.

You can add an ErrorCollection property to the base class of your data objects that keeps errors. That way when your object moves around the errors are linked with it.

That way you will have

```<code>object.addError()
object.getError(index)
</code>```

This is cleaner because you are not maintaining objects and a relation of objects to their errors.

Body:
I would definitely go with the second method. Why?

Well it seems to be the simplest answer. In the first instance it will require two calls everytime you need to add or get an error from your context.

There is another alternative, provided that you are providing your Object classes and they are not generated by some 3rd party lib.

You can add an ErrorCollection property to the base class of your data objects that keeps errors. That way when your object moves around the errors are linked with it.

That way you will have

object.addError()
object.getError(index)

This is cleaner because you are not maintaining objects and a relation of objects to their errors.


答:
I keep technical videos on my laptop for these times. On a short flight, my preference is just to sleep. I am more likely to watch the videos during all the interminable waiting that surrounds a flight, when you can't safely fall asleep, or on a long flight if I wake up and get bored, or if I am staying awake waiting for a meal. Today I'll be giving  Link some exercise stocking up on just-released PDC videos before my transatlantic flight tomorrow.

For years I spent time every week at events for my kids where there was no wifi but I didn't have any real duties - I bring the child, I can watch if I want, but there's nothing I need to do. I developed the habit of saving certain of my todo's for that time. Revewing a document someone else wrote, or typing in a stack of paper notes I took during a meeting, or making a good copy in Visio of a diagram from a whiteboard that I photographed, that sort of thing. These are also highly interruptable should my child suddenly do something interesting that I want to pay attention to. If you have this kind of downtime regularly, pay attention as you go through your regular workload and ask yourself "could I save this for Tuesday night?".

Title: Being productive during downtime

ContentLicense: CC BY-SA 4.0


问:
Making sure users have a modern web browser
We have several users running on old hardware and old browsers.

What would be the best way to get them to upgrade to a newer web browser, without nagging users with a newer web browser.

答:
If it's not a page that is mandatory to be seen even with an old browser, and you don't mind having a part of the visitors leaving, you could just develop it using latest technology and let the user see the need for updating their browser first-hand. Of course, this is not viable in anything business-like, but for personal pages or for sites that simply require some new feature to work (as strange as that is!), it should be fine.

The courteous thing would be to remind the user that in order to see the page fully, a modern browser is called for. Eventually this will drive the masses to upgrade to modern browsers, and thus make the new features more reliable for the developer to use in more conservative pages (corporate, retail, banks, etc).

This should fit your requirements. Users of modern browsers will see the page as intended, and users of obsolete browsers will see that they need to upgrade.


问:
Are injectable classes allowed to have constructor parameters in DI?
Given the following code:

```<code>class ClientClass{

    public function print(){
        //some code to calculate $inputString
        $parser= new Parser($inputString);
        $result= $parser->parse();
    }
}

class Parser{
    private $inputString;

    public __construct($inputString){
        $this->inputString=$inputString;
    }
    public function parse(){
        //some code
    }
}
</code>```

Now the ClientClass has dependency on class Parser. However, if I wanted to use Dependency Injection for unit testing it would cause a problem because now I can't send the input string to the parser constructor like before as its calculated inside ClientCalss itself:

```<code>class ClientClass{
        private $parser;
        public __construct(Parser $parser){
            $this->parser=$parser;
        }
        public function print(){
            //some code to calculate $inputString
            $result= $this->parser->parse(); //--> will throw an exception since no string was provided

        }
}
</code>```

The only solution I found was to modify all my classes that took parameters in their constructors to utilize Setters instead (example: setInputString()).

However, I think there might be a better solution than this because sometimes modifying existing classes can cause much harm than benefit.

So,

Are injectable classes not allowed to have input parameters?

If a class must take input parameters in its constructor, what would be the way to inject it properly?

UPDATE

Just for clarification, the problem happens when in my production code I decide to do this:

```<code>$clientClass= new ClientClass(new Parser($inputString));//--->I have no way to predict $inputString as it is calculated inside `ClientClass` itself.
</code>```

UPDATE 2

Again for clarification, I'm trying to find a general solution to the problem not for this example code only because some of my classes have 2, 3 or 4 parameters in their constructors not only one.

答:
I realize this might be simplified example of what you deal with, but it seems that your print method (now assuming this is a code you work with and can change) does a little bit too much. To be precise, it calculates value it has to print. Moving that behaviour to separate construct (another dependency) will easily mitigate problem:

```<code>class ClientClass{
    private $parser;
    private $inputProvider;

    public __construct(InputProvider $inputProvider, Parser $parser){
        $this->inputProvider = $inputProvider;
        $this->parser = $parser;
    }

    public function print(){
        $input = $this->inputProvider->calculate();
        $result = $this->parser->parse($input);
    }
}
</code>```

This way, not only you don't have to change any existing code (Parser), but you gain little bit more in terms of lose coupling/separation of concerns. Printing does print, and input calculation logic (which can be unit tested separately, too) is delegated outside.

Body:
I realize this might be simplified example of what you deal with, but it seems that your print method (now assuming this is a code you work with and can change) does a little bit too much. To be precise, it calculates value it has to print. Moving that behaviour to separate construct (another dependency) will easily mitigate problem:

class ClientClass{
    private $parser;
    private $inputProvider;

    public __construct(InputProvider $inputProvider, Parser $parser){
        $this->inputProvider = $inputProvider;
        $this->parser = $parser;
    }

    public function print(){
        $input = $this->inputProvider->calculate();
        $result = $this->parser->parse($input);
    }
}

This way, not only you don't have to change any existing code (Parser), but you gain little bit more in terms of lose coupling/separation of concerns. Printing does print, and input calculation logic (which can be unit tested separately, too) is delegated outside.


答:
In the old code, the ClientClass constructs a Parser. So minimal change would be to inject a parser factory, not an instance. The factory can have any arguments you need and obviously can pass them to the constructor of created class.

To give an example, the code in question should be modified along the lines of:

```<code>class ClientClass{
    private $parserFactory;
    public __construct($parserFactory){
        $this->parserFactory=$parserFactory;
    }
    public function print(){
        $parser = $this->parserFactory($inputString)
        $result= $parser->parse();
    }
}
</code>```

and called like:

```<code>new ClientClass(function($inputString) { return new Parser($inputString) });
</code>```

(of course a named function may be used too). This is perfectly generic; you wrap the construction of the object you need in a function that will pass through any arguments you need, provide that to the dependent class and inside that class you'll call the function instead of constructing the dependence directly. Of course the function you pass can create mock object instead or it can modify the arguments or hardcode some extra arguments or whatever you need.

If your language does not have function objects and lambda expressions, you can instead create a factory class. Where function objects are available, they are easier to write.

PS: I am not proficient in PHP, so I am not absolutely sure I don't have syntax error in the example.

Title: Are injectable classes allowed to have constructor parameters in DI?

Body:
In the old code, the ClientClass constructs a Parser. So minimal change would be to inject a parser factory, not an instance. The factory can have any arguments you need and obviously can pass them to the constructor of created class.

To give an example, the code in question should be modified along the lines of:

class ClientClass{
    private $parserFactory;
    public __construct($parserFactory){
        $this->parserFactory=$parserFactory;
    }
    public function print(){
        $parser = $this->parserFactory($inputString)
        $result= $parser->parse();
    }
}

and called like:

new ClientClass(function($inputString) { return new Parser($inputString) });

(of course a named function may be used too). This is perfectly generic; you wrap the construction of the object you need in a function that will pass through any arguments you need, provide that to the dependent class and inside that class you'll call the function instead of constructing the dependence directly. Of course the function you pass can create mock object instead or it can modify the arguments or hardcode some extra arguments or whatever you need.

If your language does not have function objects and lambda expressions, you can instead create a factory class. Where function objects are available, they are easier to write.

PS: I am not proficient in PHP, so I am not absolutely sure I don't have syntax error in the example.


问:
Why don't research papers that mention custom software release the source code?
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?

答:
That might sound cynical, but in my experience research papers are not written to be easy to understand or simple to reproduce. Instead, in the research community it is more important to have an article that sounds and looks very scientific. For that reason most authors transform their code into mathematical formulas and try to prove that their algorithm is mathematically correct. Usually the number of pages for such an article is limited so there is no space left to publish the code. Yet, of course this would not limit any author to link to the complete code with an URL...

One could assume that if code is not published, either the authors want to mometarize their findings, or (what I personally think is the case more often) they are afraid that people would see that their research is not as awesome as they claim. Often results only apply to a very limited number of cases.

Also, I have seen that from one simple program/algortihm several research papers are spin off. If code would be published, it would be difficult to write any further papers on the same topic. So knowledge is held back in order to publish it over time in little slices.

Always keep in mind that at universities, it is not so much the results or the applicability of research that is important, but the number of papers you publish. It's sad, but true.


答:
In response to your question "Are human-readable formats actually readable by humans", by definition yes they are, that's what human readable means.

There isn't a technical definition of human readable, it's subjective and there might be questions about what level of knowledge the human might need to have to qualify (for instance do they need to understand the very basic principals of XML such as tags and hierarchies, should they understand the business domain the data exists in - personally I'd say yes to both) but your basic test should be if I showed it to someone with basic technical skills who understood the basics of what the data was meant to represent it, can they read it.

On a practical level this will generally mean the following:

1) The data is stored as ASCII text or some other similarly common and easily recognisable format

2) That there is a reasonable structure that is self evident from a basic examination.  For instance you don't have to know that the first X characters related to Y, then the next X relate to Z

3) That both the data and the meta data generally are in English (or whatever your local language is) and require only limited knowledge of the problem domain to understand - so an invoice number would be in an "invoiceNumber" tag, rather than "uDef_Inbr"

4) For non-text data sensible, predictable conventions have been used (for instance TRUE, FALSE, Y, N, 1, 0 rather than something more open to interpretation)


答:
It depends. A person writing a paper, or their supervisor, decides what should be done with the source code. Sometimes, people make the project an open source.

Sometimes, projects are usually funded by companies, meaning it's their property. In those cases, paper's author is not allowed to show the code.

Title: Why don't research papers that mention custom software release the source code?

Body:
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?


答:
More often than not, the actual programme is just a tool to get to the end, rather than the product in its own right.  Giving full details of the source code would be akin to providing a full drawing of the pen used to sign the report, and/or schematics of the PC.

Having said that, especially where peer reviewing is being invited, the source code will be available - although under some form of Non Disclosure Agreement (NDA) - as there is inherently Intellectual Property embodied within the program.

If you are genuinely interested in the code, I suggest @Buttons' comment is the best advice: Ask them :)


答:
Generally, the programs used to produce the papers results are only tools, and only the results matter. So they are not placed on the paper which presents the context, the methodology, the results and a discussion about them.

But results must be reproducible. And then, when the data sources on which the paper is based are publicly available, the programs transforming them into results are generally required too. They are often placed "somewhere" on the Web if it doesn't raise any patent/copyright issue. Or, at least, the authors must send you the programs if you ask them.