问:
Evaluating JSON from popular auto-suggests
I was evaluating the various ways in which the big guys implement auto suggest. These are my observations.(Search string used was "ab") Questions towards the end.

Yahoo tries something like this, where the response was a JSONP. Response is readable and serves the purpose.

Yahoo's response

```<code>yasearch({"q":"ab ","gprid":"Y435dN7TRFqnYqQhnBueJA","f":["k","m"],"r":[["ab de villiers",0],["ab exercises",0],["ab king pro",0],
["ab infi-net internet banking",0],["ab mujhe raat din",0],["ab workouts",0],["ab mp3",0],["ab meri bari",0],["ab ke baras",0],["ab meri baari",0]]})
</code>```

Bing had a similar approach. Returns an "if" block, sa_inst.apiCB() seems to be a function which would process the JSON. Again response is readable and legit.

Bing's response

```<code>if(typeof sa_inst.apiCB == 'function') sa_inst.apiCB({"AS":{"Query":"ab","FullResults":1,"Results":[{"Type":"AS","Suggests": [{"Txt":"ab<strong>p</strong> <strong>news</strong>","Type":"AS","Sk":""},
{"Txt":"ab<strong>bottapp</strong>.ab<strong>bott</strong>.<strong>in</strong>","Type":"AS","Sk":"AS1"},{"Txt":"ab<strong>t</strong> <strong>travels</strong>","Type":"AS","Sk":"AS2"},{"Txt":"ab<strong>p</strong> <strong>ananda</strong>","Type":"AS","Sk":"AS3"},
{"Txt":"ab<strong>hibus</strong>","Type":"AS","Sk":"AS4"},{"Txt":"ab<strong>p</strong> <strong>maza</strong>","Type":"AS","Sk":"AS5"},  {"Txt":"ab<strong>b</strong>","Type":"AS","Sk":"AS6"},
{"Txt":"ab<strong>outgoogle</strong>","Type":"AS","Sk":"AS7"}]}]}} /* pageview_candidate */);
</code>```

Now comes Google. Response is sent as 2 JSON objects(separated by /""/). Most of it is unreadable.

Google's response

```<code>{e:"XteVUYKqDoKHrAfdz4D4Aw",c:0,u:"https://www.google.com/s?hl\x3den\x26gs_rn\x3d14\x26gs_ri\x3dpsy-ab\x26tok\x3dvsobDhICRmdcnY7ayKTGng\x26cp\x3d2\x26gs_id\x3dd\x26xhr\x3dt\x26q\x3dab\x26es_nrs\x3dtrue\x26pf\x3dp\x26output\x3dsearch\x26sclient\x3dpsy-ab\x26oq\x3d\x26gs_l\x3d\x26pbx\x3d1\x26bav\x3don.2,or.r_cp.r_qf.\x26bvm\x3dbv.46751780,d.bmk\x26fp\x3d2647af89de6b6c61\x26biw\x3d1366\x26bih\x3d453\x26tch\x3d1\x26ech\x3d2\x26psi\x3dVteVUcYuzOGsB6LpgdgB.1368774484351.1",p:true,d:"[\x22ab\x22,
[[\x22ab\\u003Cb\\u003Ec\\u003C\\/b\\u003E\x22,0,[]],[\x22ab\\u003Cb\\u003Ec news\\u003C\\/b\\u003E\x22,0,[]],[\x22ab\\u003Cb\\u003Eercrombie\\u003C\\/b\\u003E\x22,0,[]],[\x22ab\\u003Cb\\u003Ecya\\u003C\\/b\\u003E\x22,0,[]]],
{\x22j\x22:\x22d\x22,\x22q\x22:\x22t8z6h8KhWvbkEX6xablxgYxDUq4\x22,\x22t\x22:
{\x22bpc\x22:false,\x22tlw\x22:false}}]"}
/*""*/
{e:"XteVUYKqDoKHrAfdz4D4Aw",c:-1,u:"https://www.google.com/searchdata?hl\x3den\x26gs_rn\x3d14\x26gs_ri\x3dpsy-ab\x26tok\x3dvsobDhICRmdcnY7ayKTGng\x26cp\x3d2\x26gs_id\x3dd\x26xhr\x3dt\x26q\x3dab\x26es_nrs\x3dtrue
\x26pf\x3dp\x26output\x3dsearch\x26sclient\x3dpsy-ab\x26oq\x3d\x26gs_l\x3d\x26pbx\x3d1\x26bav\x3don.2,or.r_cp.r_qf.\x26bvm\x3dbv.46751780,d.bmk\x26fp\x3d2647af89de6b6c61\x26biw\x3d1366\x26bih\x3d453\x26tch\x3d1\x26ech\x3d2\x26psi\x3dVteVUcYuzOGsB6LpgdgB.1368774484351.1",
p:true,d:"{\x22snp\x22:1}"}
/*""*/
</code>```

Are those hex codes or what do you call them?

Why is there a need for 2 objects to be returned?

What is the need for encoding the JSON?

Which is the ideal format for JSON among these three?

Any thoughts on this are welcome.

答:
JSONP is not technically a thing, it's actually just Javascript. So it's not JSON but Javascript object initializers.

If you notice, Google's response does not run as Javascript code nor is it valid JSON. So it doesn't do anything if a 3rd party site
includes it as a script. Those are not 2 JSON objects for sure because the keys are not quoted. They are Javascript
object initializers which have a property that contains a JSON string that can be parsed as JSON.

You can get the JSON out of the first part like so:

```<code>var res = '{e:"XteVUYKqDoKHrAfdz4D4Aw",c:0,u:"https://www.google.com/s?hl\\x3den\\x26gs_rn\\x3d14\\x26gs_ri\\x3dpsy-ab\\x26tok\\x3dvsobDhICRmdcnY7ayKTGng\\x26cp\\x3d2\\x26gs_id\\x3dd\\x26xhr\\x3dt\\x26q\\x3dab\\x26es_nrs\\x3dtrue\\x26pf\\x3dp\\x26output\\x3dsearch\\x26sclient\\x3dpsy-ab\\x26oq\\x3d\\x26gs_l\\x3d\\x26pbx\\x3d1\\x26bav\\x3don.2,or.r_cp.r_qf.\\x26bvm\\x3dbv.46751780,d.bmk\\x26fp\\x3d2647af89de6b6c61\\x26biw\\x3d1366\\x26bih\\x3d453\\x26tch\\x3d1\\x26ech\\x3d2\\x26psi\\x3dVteVUcYuzOGsB6LpgdgB.1368774484351.1",p:true,d:"[\\x22ab\\x22,[[\\x22ab\\\\u003Cb\\\\u003Ec\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Ec news\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Eercrombie\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Ecya\\\\u003C\\\\/b\\\\u003E\\x22,0,[]]],{\\x22j\\x22:\\x22d\\x22,\\x22q\\x22:\\x22t8z6h8KhWvbkEX6xablxgYxDUq4\\x22,\\x22t\\x22:{\\x22bpc\\x22:false,\\x22tlw\\x22:false}}]"}'

console.log(JSON.parse(eval("(" + res  + ")" ).d));
</code>```

Note that I added additional slashes so that the initial res would be exactly the same because it goes through additional string interpolation that it otherwise wouldn't go through.

A third party website can't extract the contents of the script, they can only run it. If Google just included JSON directly, then a 3rd party site could just override Object/Array constructors and access your data.

See

http://www.lazycoder.com/weblog/2007/04/02/ajax-library-security-advisory/

http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

http://jeremiahgrossman.blogspot.fi/2006/01/advanced-web-attack-techniques-using.html

Body:
JSONP is not technically a thing, it's actually just Javascript. So it's not JSON but Javascript object initializers.

If you notice, Google's response does not run as Javascript code nor is it valid JSON. So it doesn't do anything if a 3rd party site
includes it as a script. Those are not 2 JSON objects for sure because the keys are not quoted. They are Javascript
object initializers which have a property that contains a JSON string that can be parsed as JSON.

You can get the JSON out of the first part like so:

var res = '{e:"XteVUYKqDoKHrAfdz4D4Aw",c:0,u:"https://www.google.com/s?hl\\x3den\\x26gs_rn\\x3d14\\x26gs_ri\\x3dpsy-ab\\x26tok\\x3dvsobDhICRmdcnY7ayKTGng\\x26cp\\x3d2\\x26gs_id\\x3dd\\x26xhr\\x3dt\\x26q\\x3dab\\x26es_nrs\\x3dtrue\\x26pf\\x3dp\\x26output\\x3dsearch\\x26sclient\\x3dpsy-ab\\x26oq\\x3d\\x26gs_l\\x3d\\x26pbx\\x3d1\\x26bav\\x3don.2,or.r_cp.r_qf.\\x26bvm\\x3dbv.46751780,d.bmk\\x26fp\\x3d2647af89de6b6c61\\x26biw\\x3d1366\\x26bih\\x3d453\\x26tch\\x3d1\\x26ech\\x3d2\\x26psi\\x3dVteVUcYuzOGsB6LpgdgB.1368774484351.1",p:true,d:"[\\x22ab\\x22,[[\\x22ab\\\\u003Cb\\\\u003Ec\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Ec news\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Eercrombie\\\\u003C\\\\/b\\\\u003E\\x22,0,[]],[\\x22ab\\\\u003Cb\\\\u003Ecya\\\\u003C\\\\/b\\\\u003E\\x22,0,[]]],{\\x22j\\x22:\\x22d\\x22,\\x22q\\x22:\\x22t8z6h8KhWvbkEX6xablxgYxDUq4\\x22,\\x22t\\x22:{\\x22bpc\\x22:false,\\x22tlw\\x22:false}}]"}'

console.log(JSON.parse(eval("(" + res  + ")" ).d));

Note that I added additional slashes so that the initial res would be exactly the same because it goes through additional string interpolation that it otherwise wouldn't go through.

A third party website can't extract the contents of the script, they can only run it. If Google just included JSON directly, then a 3rd party site could just override Object/Array constructors and access your data.

See

http://www.lazycoder.com/weblog/2007/04/02/ajax-library-security-advisory/

http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

http://jeremiahgrossman.blogspot.fi/2006/01/advanced-web-attack-techniques-using.html


问:
Best way to learn Java if you already have an OOP background, like ActionScript 3?
I'm looking to learn Java, but I don't want to get a book that is going to tell me what an object is, how OOP works, etc. I know this from my existing ActionScript 3 work.

One idea is to look at all the areas Java covers, pick one that is of interest to me and delve into that. Is this a good idea?

Any other suggestions?

答: The best way to learn any programming language is simply to use it as much as you can while digesting information about the language one concept at a time.  Break the language up into smaller pieces and focus on each piece until you understand it then move to the next piece.  The SCJP Study Guide mentioned above takes this approach and it works.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Simple explanation of Continuous Integration
How would you define Continuous Integration and what specific components does a CI server contain?

I want to explain to someone in the marketing department what Continuous Integration is. They understand Source control - i.e. they use Subversion. But I'd like to explain to them properly what CI is. The Wikipedia Article never properly defines it, the Martin Fowler article only gives the following, which is basically a tautology followed by a vague explanation of 'integration':

Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily - leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible.

Update: I sent them this image, I couldn't find a simpler one.

Update 2: Feed back from the marketing chap (for the time when there was 3 questions):

I actually like all 3 answers – for different reasons.  I feel like logging in just to thank them all!

Obviously he can't - so thanks on his behalf :)

Update 3: I've realised looking at the Wikipedia article that it does contain the principles which, when you take just the headings, is quite a good list:

Maintain a code repository

Automate the build

Make the build self-testing

Everyone commits to the baseline every day

Every commit (to baseline) should be built

Keep the build fast

Test in a clone of the production environment

Make it easy to get the latest deliverables

Everyone can see the results of the latest build

Automate deployment

答:
I guess for your marketing department it is not important how CI works, but what CI means for new releases of your software.

CI will ideally mean that you can produce a new potentially releaseable version of your software every day, ready to be presented or sold to your customer, with some new features, functionality or bugfixes added. That does not mean you must deliver the new version every day, but you can if you want.

For example, if you have a new feature set planned to be officially released for the "2015"er version of your software, and you have parts of that feature set already coded and integrated today, the marketing guys can take the current version of your software and show it - more or less safely - at the next conference now in 2013. Without CI, they had to ask your team for an unplanned code freeze, every team member had to integrate the half-baked feature he is working on into the product, they might not have enough automatic tests ready, and guess what will happen at the conference - the "alpha version" of your 2015er release will have a much higher risk of crashing, especially when the new features are demonstrated.


答:
You can't know what CI is unless you know what we used to do. Imagine a system with 3 parts. There's a UI that gathers data and puts it in the database. There's a reporting system that makes reports from the database. And there's some sort of server that monitors the database and sends email alerts if certain criteria are met.

Long ago this would be written as follows:

Agree on the schema for the database and the requirements - this would take weeks because it had to be perfect as you'll soon see why

Assign 3 devs, or 3 independent teams of devs, to the 3 pieces

Each dev would work on their piece and test their piece using their own database copy, for weeks or months.

During this time the devs would not run each other's code, nor try to use a version of the database that had been created by someone else's code. The report writer would just hand add a bunch of sample data. The alert writer would hand add records that simulated report events. And the GUI writer would look at the database to see what the GUI had added. Over time, the devs would realize the spec was wrong in some way, such as not specifying an index or having too short a field length, and "fix" that in their version. They might tell the others, who might act on it, but usually these things would go on a list for later.

When all three parts were completely coded, and tested by their devs, and sometimes even tested by the users (showing them a report, a screen or an email alert) then would come the "integration" phase. This was often budgeted at several months but would still go over. That field length change by dev 1 would be discovered here, and would require devs 2 and 3 to make huge code changes and possibly UI changes too. That extra index would wreak its own havoc. And so on. If one of the devs was told by a user to add a field, and did, now would be the time the other two had to add it also.

This phase was brutally painful and pretty much impossible to predict. So people began to say "we have to integrate more often." "We have to work together from the beginning." "When one of us raises a change request [that's how we talked then] the others have to know about it." Some teams began to do integration tests earlier while continuing to work separately. And some teams began to use each other's code and output all the time, from the very beginning. And that became Continuous Integration.

You may think I am exaggerating that first story. I did some work for a company once where my contact chewed me out for checking in some code that suffered from the following flaws:

a screen that he wasn't working on had a button that didn't do anything yet

no user had signed off on the screen design (precise colours and fonts; the existence of the screen, its capabilities and what buttons it had were in the 300 page spec.)

It was his opinion that you don't put stuff into source control until it is DONE. He typically did one or two checkins a YEAR. We had a bit of a philosophy difference :-)

Also, if you find it hard to believe teams would be disconnected around a shared resource like a database, you really won't believe (but it's true) that the same approach was taken to code. You're going to write a function I can call? That's great, go ahead and do that, I will just hardcode what I need in the meantime. Months later I'll "integrate" my code so it calls your API and we'll discover it blows up if I pass null, I blow up if it returns null (and it does that a lot) it returns things that are too large for me, it can't handle leap years, and a thousand other things. Working independently and then having an integration phase was normal. Now it sounds like insanity.

Title: Simple explanation of Continuous Integration

Body:
How would you define Continuous Integration and what specific components does a CI server contain?

I want to explain to someone in the marketing department what Continuous Integration is. They understand Source control - i.e. they use Subversion. But I'd like to explain to them properly what CI is. The Wikipedia Article never properly defines it, the Martin Fowler article only gives the following, which is basically a tautology followed by a vague explanation of 'integration':

Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily - leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible.

Update: I sent them this image, I couldn't find a simpler one.

Update 2: Feed back from the marketing chap (for the time when there was 3 questions):

I actually like all 3 answers – for different reasons.  I feel like logging in just to thank them all!

Obviously he can't - so thanks on his behalf :)

Update 3: I've realised looking at the Wikipedia article that it does contain the principles which, when you take just the headings, is quite a good list:

Maintain a code repository

Automate the build

Make the build self-testing

Everyone commits to the baseline every day

Every commit (to baseline) should be built

Keep the build fast

Test in a clone of the production environment

Make it easy to get the latest deliverables

Everyone can see the results of the latest build

Automate deployment


问:
How do I get from a highly manual process of development and deploy to continuous integration?
We have a development process which is completely manual. No unit tests, interface tests are manual, and merging and integration are as well. How could we go from this state to implementing continuous integration with full (or at least close to full) automation of build and test? We have a pretty intense development cycle, and are not currently using agile, so switching to agile with CI in one move would be a very complicated and expensive investment. How can we take it slowly, and still moving constantly towards a CI environment?</p>

答:
As you commented that you're using PHP - installing Netbeans for PHP might be a good way to go.

It sounds like you've got source control which is the first obvious step

The next obvious step is to make sure Doc Blocks are written for each new function and any function you happen to edit - which Netbeans will help automate

Beyond that Netbeans gives you good instructions on how to integrate all the components you need for CI.

Going from PHPUnit

to PhpDocumentor

through to the Hudson (Jenkins) CI server - they're all bundled in the PHP options for Netbeans.


答:
When someone changes the files that make up the software product and then attempts to check them in (in other words, attempts to integrate the changes into the main product code) you want to make sure that the software product can still be successfully built.

There is usually an external system, called the CI server, that either periodically or on every change, will grab the source files from version control, and attempt to build the product (compile/test/package). If the CI server can successfully do a build, the changes have been successfully integrated.

The CI server also has to be able to broadcast if the build failed or succeeded, so systems like Jenkins (one of the most used CI server today) will have ways to send emails/texts as well as a dashboard-like web interface with a bunch of information about current and past builds, who checked-in code, when things broke, etc. (On your image above, this would be the Feedback Mechanism.)

CI is important, because it ensures that on a continuous basis, you have a working product. This is important for all the developers who are working on the software product as well as for all the people who want to have access to daily releases of the software product, like QA.

ContentLicense: CC BY-SA 4.0


答:
First of all, you don't need to be doing agile to go to a CI deploy environment.

We have a pretty intense development cycle

Well, don't we all? Just bite the bullet and do it! No more procrastinating, if the team want to do it, then assign someone (or more) to do it.

If management grumble about being a man down for features for a week, come up with some stats around how much time you think moving to CI will save you. How long does it take to do a manual build? how often does a manual build not work and have to be redone? How often does a environment have to be rebuilt because of a poor manual build etc.

Once you are over those hurdles, figure out:

which CI tool, there are lots

what environments you plan to have

what servers you're going to need for those, and how many

identify all the different disparate "sections" of your system, figure out the dependencies (you probably know that already) and get it into your CI environment.

Title: How do I get from a highly manual process of development and deploy to continuous integration?

Body: We have a development process which is completely manual. No unit tests, interface tests are manual, and merging and integration are as well. How could we go from this state to implementing continuous integration with full (or at least close to full) automation of build and test? We have a pretty intense development cycle, and are not currently using agile, so switching to agile with CI in one move would be a very complicated and expensive investment. How can we take it slowly, and still moving constantly towards a CI environment?</p>


问:
iOS App Signing and Certificates
In order to sign an application for the Apple App Store, we need to create a certificate by saving a certificate request file from keychain and then upload it to the Apple store.

I was wondering, what does this certificate request file contain?

Does the certificate contain any information (like a finger print) about the OS or hardware?

答:
The excerpt below comes from an article on Apple's Developer website about code signing:

To enable signed code to fulfill these purposes, a code signature consists of three parts:

A seal, which is a collection of checksums or hashes of the various parts of the code, such as the identifier, the Info.plist, the main
  executable, the resource files, and so on. The seal can be used to
  detect alterations to the code and to the app identifier.

A digital signature, which signs the seal to guarantee its integrity. The signature includes information that can be used to
  determine who signed the code and whether the signature is valid.

A unique identifier, which can be used to identify the code or to determine to which groups or categories the code belongs. This
  identifier can be derived from the contents of the Info.plist for the
  app, or can be provided explicitly by the signer.

As for more information, check out this post on why and how to do code signing from Adam Eberbach, an experienced full-time IOS developer: http://www.raywenderlich.com/2915/ios-code-signing-under-the-hood.

Title: iOS App Signing and Certificates


问:
Training old timey fortran programmers to better code design. hints?
I need to quickly train Fortran 90 developers into object oriented design, good coding, and general coding practices to make code maintenance easier and accessible to everybody. Their current style is the usual:

long routines that do too much

modules are aggregated in "family mode" (routines that have something to do with different kind of objects who share a common use are all in one module, instead of having different modules for different type)

huge globals module with hundreds of variables

general un-greppability of identifiers

This is just out of my head. I did a course to one of them explaining OO and modularization in terms of a Pen (with methods such as uncap(), and members like inkLevel) and I was very successful in diverting his point of view. I also gave him the exercise to code in OO style a very simple textual adventure, where the player can move around rooms. I also introduced the concept of patterns and antipatterns.

I would like to know any hints and suggestions on how to perform this task at best.

Thanks

答:
As you are well aware, this is far different than teaching college kids the basics of OO.  You're talking to people who have written working, deployed code just fine with these strategies for possibly quite some time.

Instead of focusing on the what, I would focus on the why.  I think the best way to demonstrate the why is to start with a piece of well-written OO code to which a feature needs to be added.  As you extend the functionality of the code, you can demonstrate where it is easy to add the necessary hooks for the new functionality.

Reading OO code is the best way to understand it, in my experience.


答:
Start by automating your build. With PHP, this will probably be a shell script. It should do the following things:

If you're using a database, create a new database instance and populate it with initial data. Don't be tempted to reuse an existing instance, as that will eventually cause spurious errors. IMO, this is the most important stop to automating a build, regardless of the language; your data is what drives the system.

Check out trunk into a clean directory and apply any configuration changes (for example, pointing to the database instance you just created).

Configure your server to point to this directory and start the server.

Run wget or curl to verify that your homepage is accessible.

This is a basic continuous integration script, although it doesn't do actual testing. You can run this script with cron, or from a commit hook on your database.

The next step is to add testing. In a perfect world, you've separated your business logic from presentation, and could write PHP scripts that load up your modules and exercise them. I'm guessing this isn't your world.

In which case your first round of tests will probably use wget or curl, along with some other shell programs (grep, perhaps) to verify that you're getting something close to what you expect. You could also write PHP scripts that exercise your app: deploy them on another server, and invoke from your build scripts. How detailed you want to get is up to you.

For completely exercising your app, you'll probably want a tool like Selenium.

However you proceed, be sure to mail all of your developers when the build fails. You don't want to leave the build broken, and the person who broke the build may not be the best person to fix it.


问:
Why can't an xml comment contain two hyphens
I was applying markdown comments in the xml comments of a config file when the XmlParser reported that two hyphens (--) are not allowed in xml comments.

Checking the XML Specification, it appears that xml comment isn't designed to contain two hyphens for compatibility reasons with SGML parsers.

Why do SGML parsers disallow double hyphens in comments?

答: Because a double hyphen is the comment delimiter in SGML. The <! starts an SGML instruction, the -- indicates the start or end of a comment. So basically it is for the same reason that a C++ comment cannot contain */.


问:
is this javascript property defaulting pattern a code smell?
In some javascript code I'm working on refactoring I've handled cases where I wanted to default an object property to true without having to go through the code-base and add the property to every instance of the object by doing something like this:

```<code>if(typeof(thisBool) === 'undefined' || thisBool) {
    //do cool stuff here;
}
</code>```

so for existing instances I only had to fix up the model in cases where I wanted to set thisBool to some value calculated somewhere else, or to set it to false; if it was unset then this code treated it as true.

The objects are built dynamically when used - they're not defined classes, but are "instantiated" something like this:

```<code>var thing1 = {
    Name: 'thing No 1',
    HasCat: false,
    [thisBool: true]
};
</code>```

and thing1 is passed into the function

Is this a terrible idea? I'm updating that code (and all of the instances) so now is the time to fix this, if it's a code smell.

For my own part I would rather be more explicit, but I also see the value in not having to supply a thisBool: true in hundreds of places, where by default thisBool should be true. Is there a better way to achieve this?

答:
I don't think there is anything terribly wrong with the if statements provided.  It is not a big deal but I am not a fan of having a method outside of that instantiated object determining the defaults for that object. I don't know the codebase so I could't tell you if it is worth refactoring.

If you are writing something from scratch I would suggest using inheritance to define default properties such as bools strings and numbers.

```<code>function Thing(config) {
    for(key in config) {
        this[key] = config[key];
    }
}

Thing.prototype.bool = true;

new Thing().bool
>> true

new Thing({bool: false}).bool
>>false
</code>```

Also it would be quite easy to integrate the Thing object in the existing code base.  Instead of :

```<code>var thing1 = {
    Name: 'thing No 1',
    HasCat: false,
    [thisBool: true]
};
</code>```

It would be:

```<code>var thing1 = new Thing({
    Name: 'thing No 1',
    HasCat: false
});
</code>```

Body:
I don't think there is anything terribly wrong with the if statements provided.  It is not a big deal but I am not a fan of having a method outside of that instantiated object determining the defaults for that object. I don't know the codebase so I could't tell you if it is worth refactoring.

If you are writing something from scratch I would suggest using inheritance to define default properties such as bools strings and numbers.

function Thing(config) {
    for(key in config) {
        this[key] = config[key];
    }
}

Thing.prototype.bool = true;

new Thing().bool
>> true

new Thing({bool: false}).bool
>>false

Also it would be quite easy to integrate the Thing object in the existing code base.  Instead of :

var thing1 = {
    Name: 'thing No 1',
    HasCat: false,
    [thisBool: true]
};

It would be:

var thing1 = new Thing({
    Name: 'thing No 1',
    HasCat: false
});


答:
This page outlines quite a bit of the HTML/SGML history, and the rather convoluted rules of those two consecutive hyphens (double dash).

The relevant part about SGML:

To put it simply, the double dash at the start and end of the comment do not start and end the comment. Double dash indicates a change in what the comment is allowed to contain. The first -- starts the comment, and tells the browser that the comment is allowed to contain > characters without ending the comment. The second -- does not end the comment. It tells the browser that if it encounters a > character, it must then end the comment. If another -- is added, then it goes back to allowing the > characters.

Title: Why can't an xml comment contain two hyphens

Body:
I was applying markdown comments in the xml comments of a config file when the XmlParser reported that two hyphens (--) are not allowed in xml comments.

Checking the XML Specification, it appears that xml comment isn't designed to contain two hyphens for compatibility reasons with SGML parsers.

Why do SGML parsers disallow double hyphens in comments?


问:
New PHP Project - Should I still be supporting PHP 5.2?
I'm about to start working on a new commercial PHP project with a friend that will be licensed and sold as a script to run on your own shared hosting account or server.

Looking at the statistics (http://w3techs.com/technologies/details/pl-php/5/all) 50.3% of PHP 5 installations are still PHP 5.2 or lower (43.5% being php 5.2). With this in mind, is it wise to ensure new software still supports PHP 5.2 given that such a high proportion of installations arent going to support modern PHP features such as namespacing and the likes of Composer.

答:
I don't think you can rely on statistics to show you this or not; the answer will depend more on who your prospective clients are.

Personally, I think you should be aiming to support PHP 5.3, as the new features really do make a significant difference. Performance is better, for a start.

If you want to appeal to the widest possible market, then support PHP 5.2, but at the end of the day, people will not upgrade unless they need to, which makes supporting older versions a bit of a circular problem; you'll have to support it in perpetuity.


问:
How to ascertain from the users if performance tuning has had the desired effect
So you've made some code changes that should hopefully speed up some part of an application. But there is just one problem - you don't know how it will perform in live.

Different networks, different machines, different memory, different configuration, different times of day, different users, different server loads etc etc etc

So...

(a) Do you ask them if that bit of the application has got faster?

(b) Do you ask them to monitor that part of the application?

Or...

(c) Do you just ask them to see if they notice any difference in the application in general? After all, you can't be 100% sure you haven't affected something else.

Each of these approaches would seem to have problems (I know this as I've tried them all):

(a) You're asking a leading question. Before such a fix goes life, there is an emperor's new clothes scenario. The developer believes the code should be faster so there is some kind of crusade to get everyone believing it before it goes live. So...it goes live. Some people say it is faster, some slightly slower and others about the same. What then?

(b) Again: Some people say it is faster, some slightly slower and others about the same. What then?

(c) You're no longer asking a leading question, but you start getting hit with a whole torrent of issues that people have known about for months (maybe years) but you've now opened Pandora's box. How can you be sure which if these (if any) are new issues?

Or maybe I should be asking different questions entirely. Any thoughts?

EDIT:

No doubt there are processes leading up to this point that could potentially be improved. But the nub of the question is this:

The change is tested and has been put live. You have a myriad of stats to prove the changes should improve performance. Your boss has given the stats a once over but now wants to make sure the users are happy before signing off the release. What question(s) should you be asking the users?

答:
What question(s) should you be asking the users?

Here is the next version of our program.  Please report any unexpected behavior.

Unless your users are using stopwatches, or your program has some very long-running processes, users are unlikely to be able to provide anything but subjective feedback.  And for optimization I'd be more worried about behavior not caught by your automated tests than an uneven speed increase.


问:
Benefits of using XML builder vs templating language like ERB?
I'm doing a lot of work with XML, our legacy XML generators use the ruby template language ERB to create the XML files. I've been experimenting with Nokogiri and the builder model of creating XML, but I seem to be able to accomplish everything I want using both methods. So, what should I be taking into account when choosing one common method going forward? What are the benefits of using a builder method to construct the XML vs a template language?

One that I can think of is the builder method(nokogiri) provides methods for do much more than creating the file, such as searching and rearranging, etc. So if I use the builder method I can have a common tool for doing all xml related tasks.

答:
ERb is not an XML templating system. It is a plain text templating system. It doesn't know anything about XML, therefore it cannot guarantee anything about the generated XML code.

```<code><blody>
  <%= 2 + 2 %>
</BoDY>
</code>```

is perfectly valid ERb but of course not valid XML. This cannot happen with Builder:

```<code>xml.body {
  2 + 2
}
</code>```

Body:
ERb is not an XML templating system. It is a plain text templating system. It doesn't know anything about XML, therefore it cannot guarantee anything about the generated XML code.

<blody>
  <%= 2 + 2 %>
</BoDY>

is perfectly valid ERb but of course not valid XML. This cannot happen with Builder:

xml.body {
  2 + 2
}


问:
In Java, what are checked exceptions good for?
Java's checked exceptions have gotten some bad press over the years. A telling sign is that it's literally the only language in the world that has them (not even other JVM languages like Groovy and Scala). Prominent Java libraries like Spring and Hibernate also don't use them.

I personally have found one use for them (in business logic between layers), but otherwise I'm pretty anti-checked exceptions.

Are there any other uses that I don't realize?

答:
I love exceptions.

I am, however, constantly bemused by their miss-use.

Don't use them for flow-handling. You don't want code that tries to do something and uses an exception as a trigger to do something else instead because Exceptions are objects that need to be created and use memory etc. etc. just because you couldn't be bothered to write some kind of if() check before you made your call. That's just lazy and gives the glorious Exception a bad name.

Don't swallow them. Ever. Under any circumstances. As an absolute minimum you stick something in your log file to indicate that an Exception happened. Trying to track your way through code that swallows exceptions is a nightmare. Again, curse you exception-swallowers for bringing the mighty Exception into disrepute!

Do treat Exceptions with your OO hat on. Create your own Exception objects with meaningful hierarchies. Layer your business logic and your exceptions hand in hand. I used to find that if I started on a new area of a system I'd find the need to sub-class Exception within half an hour of coding so these days I start by writing the Exception classes.

If you're writing 'frameworky' bits of code, make sure all your initial interfaces are written to throw your own new Exceptions where appropriate... and make sure your coders have some sample code around the place of what to do when their code throws an IOException but the interface they're writing to wants to throw a 'ReportingApplicationException'.

Once you've groked how to make Exceptions work for you you'll never look back.


问:
Single Responsibility principle VS KISS principle
Let's assume the modeling of User model in a context of a social network.

User concept is composed of two notions:

Authentication elements like userName/Password/Email etc...

Extra data information sometimes called "User profile" like firstName, birthday, pictures etc..

At first glance, this analysis involves separation of tasks/responsibilities if we want to keep SRP.

However, typically in the case of a social network, userName may be seen as a pure information belonging to a user's profile rather than a pure element of authentication.

Thus, there is three ways, according to me, to model the User concept.

First, the whole in one class:

User (userName, password, email, firstName, birthday, picture etc...)

Second, a one-to-one relationship between User and UserProfile:

User(userName, password, email)
UserProfile(firstName, birthday, picture etc...)

Third, a one-to-one but with a redundancy of the common fields (being as focused on authentication as a visible user information on the website):

User(userName, password, email)

UserProfile(userName, firstName, birthday, picture etc...)

Why repetition here?  Of course for consitency and at the same time to avoid joins in cases of relational database when one want to retrieve each Use's profile data.

What is a good practice to model these both concepts?
Where should I place userName field?

Dilemma being:  keeping KISS (Keep it simple stupid!)  or SRP ;)

答:
You're confusing KISS; simple isn't referring to simple to implement for the developer, it refers to simple design, simple to understand and use. Following SRP makes your code simpler to understand and use because it's simpler to use a purpose built class for a single purpose than a multipurpose class, it's also simpler to maintain.

SRP supports Simplicity, even if it's more work for the developer to implement, the result is a simpler system.


问:
Entity to DTO Usage
Been trying to come up with a flow for a basic tiered web application, and have been reading conflicting information online.  What I'm trying to figure out is if there is an advantage to still using DTO objects from your DAO to Service layer through the use of some sort of mapper.

The basic flow I foresee is as follows:

UI Model / Form --> Controller

Controller converts Model into Domain Object (Entity)

Domain Object --> Service Layer

Domain Object --> DAO

DAO --> Domain Object(s)

Service --> UI

UI converts Domain into UI models

If DTO was followed DAO would pass back a DTO not the Entity.  After doing some reading it seems like DTO has become slightly defunct since (at least in Java) entities have become annotated POJOs meaning their memory footprint has become very small.

Is this the case, or should DTOs be used to completely encapsulate the domain objects within the DAO layer, and, if this is the case, what would the service layer pass to the DAO?

Thanks a bunch!

答:
According to me, passing a persistable POJO, like for instance a bean managed by JPA, is not THE good practice.

Why?

I see three main reasons:

Potential issue with lazy collections. http://java.dzone.com/articles/avoid-lazy-jpa-collections

Entity should contain behaviour (in contrary of an Anemic domain model)
You may not want to let your UI call some unexpected behavior.

In case of anemic domain model you may not want to expose your model structure to the UI, since every new change to model may break UI.

I prefer letting my service layer convert entities to corresponding DTO in both directions. DAO still returning entity (it's not its job to ensure the conversion).

Title: Entity to DTO Usage


答:
IMO this is a false dichotomy. If you follow SRP, you keep your system simple overall. Multiple small classes tend to be more "simple" (in many cases) rather than fewer large classes. Plus it seems like you are conflating two issues: how you design your classes vs. how you design your database. The two do not need to be related.

In your given case, it sounds like you probably have 3 classes: User (username, password, email), UserProfile (name, birthday, etc.), and UserPictures (the pictures, because why would they be part of the "profile"?). Then you can create your User class to include (via composition) the other two.

Of course, this is just a rough attempt at design without any broader overall picture of requirements. There are plenty of different valid, simple, and SRP ways to do break down your classes based on the actual need. The main point is just that KISS and SRP aren't inherently at odds.

Edited much later after learning more:

Back when I wrote this answer, I was thinking about SRP in terms of "a class should only have one responsibility" which has a lot to do with cohesion and coupling. This is good, but I have since learned more about what SRP really is.

The book Clean Architecture has a good description about SRP (and all of SOLID and more). Originally the definition was "a module should have one, and only one, reason to change." But Uncle Bob revised it to be "a module should be responsible to one, and only one, actor." So it's more about the use-cases of why a particular persona might want things to change.

To tie this back to the OP, classes that control behaviors for things like passwords, birthday, and pictures might all be responsible to different actors. Your security team cares about passwords and may cause you to change those behaviors separately from product managers who want to edit how birthdays are handled. So then, to follow SRP it would be wise to understand who those stakeholders are and create separations (e.g. separate classes) based on those stakeholders. Thus, you might have a UserCredential class for managing passwords instead of putting it in another class along with data that changes because of other stakeholders' reasons.

Following SRP keeps things simple in many of the same ways I mentioned originally, but it also makes things simple when you don't mix changes made for different reasons in the same class. So even with this revision, SRP and KISS can still live happily together.

Title: Single Responsibility principle VS KISS principle

Body:
Let's assume the modeling of User model in a context of a social network.

User concept is composed of two notions:

Authentication elements like userName/Password/Email etc...

Extra data information sometimes called "User profile" like firstName, birthday, pictures etc..

At first glance, this analysis involves separation of tasks/responsibilities if we want to keep SRP.

However, typically in the case of a social network, userName may be seen as a pure information belonging to a user's profile rather than a pure element of authentication.

Thus, there is three ways, according to me, to model the User concept.

First, the whole in one class:

User (userName, password, email, firstName, birthday, picture etc...)

Second, a one-to-one relationship between User and UserProfile:

User(userName, password, email)
UserProfile(firstName, birthday, picture etc...)

Third, a one-to-one but with a redundancy of the common fields (being as focused on authentication as a visible user information on the website):

User(userName, password, email)

UserProfile(userName, firstName, birthday, picture etc...)

Why repetition here?  Of course for consitency and at the same time to avoid joins in cases of relational database when one want to retrieve each Use's profile data.

What is a good practice to model these both concepts?
Where should I place userName field?

Dilemma being:  keeping KISS (Keep it simple stupid!)  or SRP ;)


答:
thing objects should be responsible for setting their own default values. If you force other functions to know that the default for thisBool is true, your code becomes harder to understand. Also, you run the risk that someone might add a new function but not know that thisBool is supposed to be true by default.

Below is my suggestion for a constructor-like function.

```<code>var createThing = function () {
  var myThing = {};
  myThing.thisBool = true;
  return myThing;
};

var thing1 = createThing();
thing1.name = "thing no 1";
...
</code>```

On a pragmatic note, it might not be feasible for you to make the changes described above. If you have thousands of thing objects, a couple of functions, and a lack of justification to change all of the thing objects, you may need another solution.

One option is for you to change the semantics of thisBool so that the default is false. Because properties are undefined by default and undefined is falsey, you would reduce the risk of surprising future programmers.

```<code>if (notThisBool) {  // hopefully you have better semantics than notThisBool
  // do special case
} else {
  // do default case
}
</code>```

As a last resort, I would suggest that your function check for exactly false, and include a comment explaining why.

```<code>// check for exactly false because thisBool is an optional property
// that should be considered true unless it is set to false
if (myThing.thisBool === false) {
  // special case
} else {
  // default case
}
</code>```

I realize that "not exactly false" is slightly different than "undefined or truthy". (In my above code a falsey value other than "false" would run the default case.) I think that my code is more clear.

Title: is this javascript property defaulting pattern a code smell?

Body:
In some javascript code I'm working on refactoring I've handled cases where I wanted to default an object property to true without having to go through the code-base and add the property to every instance of the object by doing something like this:

```<code>if(typeof(thisBool) === 'undefined' || thisBool) {
    //do cool stuff here;
}
</code>```

so for existing instances I only had to fix up the model in cases where I wanted to set thisBool to some value calculated somewhere else, or to set it to false; if it was unset then this code treated it as true.

The objects are built dynamically when used - they're not defined classes, but are "instantiated" something like this:

```<code>var thing1 = {
    Name: 'thing No 1',
    HasCat: false,
    [thisBool: true]
};
</code>```

and thing1 is passed into the function

Is this a terrible idea? I'm updating that code (and all of the instances) so now is the time to fix this, if it's a code smell.

For my own part I would rather be more explicit, but I also see the value in not having to supply a thisBool: true in hundreds of places, where by default thisBool should be true. Is there a better way to achieve this?

Body:
thing objects should be responsible for setting their own default values. If you force other functions to know that the default for thisBool is true, your code becomes harder to understand. Also, you run the risk that someone might add a new function but not know that thisBool is supposed to be true by default.

Below is my suggestion for a constructor-like function.

var createThing = function () {
  var myThing = {};
  myThing.thisBool = true;
  return myThing;
};

var thing1 = createThing();
thing1.name = "thing no 1";
...

On a pragmatic note, it might not be feasible for you to make the changes described above. If you have thousands of thing objects, a couple of functions, and a lack of justification to change all of the thing objects, you may need another solution.

One option is for you to change the semantics of thisBool so that the default is false. Because properties are undefined by default and undefined is falsey, you would reduce the risk of surprising future programmers.

if (notThisBool) {  // hopefully you have better semantics than notThisBool
  // do special case
} else {
  // do default case
}

As a last resort, I would suggest that your function check for exactly false, and include a comment explaining why.

// check for exactly false because thisBool is an optional property
// that should be considered true unless it is set to false
if (myThing.thisBool === false) {
  // special case
} else {
  // default case
}

I realize that "not exactly false" is slightly different than "undefined or truthy". (In my above code a falsey value other than "false" would run the default case.) I think that my code is more clear.


问:
Pass around record ids in the url in PHP
I'm doing a PHP application with CodeIgniter and most of my controllers accept record ids as parameters for retrieving purposes.
I also pass record ids in my forms action.
Like this: www.sample.com/records/save/sFKu=4

Is this the right way to do this? Note that the record ids are encrypted.

答:
Yes, thats fine for retreival.  Just make sure in your PHP code you are properly validating user rights to the resource, so that people cant edit id's that dont belong to them.  You dont want people changing the id's in the URL to be able to access records they arent supposed to be seeing.

For forms or deleting data, you might instead consider placing the id parameter in a hidden input field rather than the URL so they are submitted as POST variables.


问:
Protect Database Design - SQL
Perhaps a bit of an odd question but I can't think of a way to achieve what I want.

I produce a product which ends up installed on-site at clients premises. It is a business critical and high availability application, and has to handle processes very quickly.

While obviously most of the work goes into the actual application (Windows Services) part of the reason why the product is so good is intelligent database design.

Until recently I usually provided the servers and I was the only person to have access to the database and SQL Server instance. However more recently customers have asked to run the application on their production server, usually VMWare, and use their SQL Farm for the database.

This is fine for the application, however I am worried about who will have access to the SQL server and if they would be able to have a poke around in my application's database.

Is there anything I can do to prevent access to it? Or is it a case of if they're hosting it there is nothing I can do?

Thanks

EDIT:

If I am hit by a bus, company folds etc. there is an escrow agreement which will give them the source code of everything they need.

As to why I am worried I have seen examples in the past of people making changes to data tables and reports, and no they did not have  the nous to do so. This meant that someone had to go in and fix everything, while of course we charge for this I was wondering if there was a way to avoid it all together, or at least minimise the risk.

答:
If they're hosting it on a hardware to which they have root access, in their copy of a database program, you cannot prevent them from gaining access to your database's design.  At best, you could add a layer of obfuscation to your code, such as writing a program to re-name all of your internal tables and fields and variables and attempting to scrub the "SQL Text" contents of some system tables.

Should you not trust your customers that much, you can require that the software only run on hardware that you manage, and then YOU could manage their internal SQL server farm.  Which may result in them kicking you to the curb regardless.

(The best answer is "don't worry", and have an install program that checks for modifications to protect you from supporting someone else's alternations, and a license agreement that protects your rights if they try and take your work and sell it as their own.)

Title: Protect Database Design - SQL


答:
Can you not measure performance in a development environment, before and after fixes? If it's 20% faster, it's usually safe to assume it'll be 20% faster in production too.

You should usually be able to find out quite easily the main bottlenecks in your infrastructure from past experience (or experience of other developers) and take that into consideration when profiling.

Title: How to ascertain from the users if performance tuning has had the desired effect

Body:
So you've made some code changes that should hopefully speed up some part of an application. But there is just one problem - you don't know how it will perform in live.

Different networks, different machines, different memory, different configuration, different times of day, different users, different server loads etc etc etc

So...

(a) Do you ask them if that bit of the application has got faster?

(b) Do you ask them to monitor that part of the application?

Or...

(c) Do you just ask them to see if they notice any difference in the application in general? After all, you can't be 100% sure you haven't affected something else.

Each of these approaches would seem to have problems (I know this as I've tried them all):

(a) You're asking a leading question. Before such a fix goes life, there is an emperor's new clothes scenario. The developer believes the code should be faster so there is some kind of crusade to get everyone believing it before it goes live. So...it goes live. Some people say it is faster, some slightly slower and others about the same. What then?

(b) Again: Some people say it is faster, some slightly slower and others about the same. What then?

(c) You're no longer asking a leading question, but you start getting hit with a whole torrent of issues that people have known about for months (maybe years) but you've now opened Pandora's box. How can you be sure which if these (if any) are new issues?

Or maybe I should be asking different questions entirely. Any thoughts?

EDIT:

No doubt there are processes leading up to this point that could potentially be improved. But the nub of the question is this:

The change is tested and has been put live. You have a myriad of stats to prove the changes should improve performance. Your boss has given the stats a once over but now wants to make sure the users are happy before signing off the release. What question(s) should you be asking the users?


问:
Javascript storing data
Hi I am a beginner web developer and am trying to build the interface of a simple e-commerce site as a personal project.The site has multiple pages with checkboxes. When someone checks an element, it retrieves the price of the element and stores it in a variable. But when I go to the next page and click on new checkboxes products the variable automaticly resets to its original state.How can I save the value of that variable in Javascript?

This is the code I've writen using sessionStorage but it still dosen't work when I move to next page the value is reseted.

How can I write this code so that it dosen't reset on each page change. All pages on my website use the same script.

```<code>$(document).ready(function () {
    var total = 0;

    $('input.check').click(function () {
        if ($(this).attr('checked')) {
            var check = parseInt($(this).parent().children('span').text().substr(1, 3));
            total += check;
            sessionStorage.var_name = 0 + total;
            alert(sessionStorage.var_name);

        } else {
            var uncheck = parseInt($(this).parent().children('span').text().substr(1, 3));
            total -= uncheck;
        }
    })
})
</code>```

答:
I have personally used jStorage (www.jstorage.info) in a client project. The API is simple, cross-browser and uses HTML5 local storage where available. (It uses userData behavior in decrepit versions of IE.) With local storage, you can unplug your PC with no data loss, so it will certainly persist your data across page loads.

Sample syntax:

```<code>var subTotal = $.jStorage.get( CACHEsubTotal );
subTotal += currentlySelectedItem;
$.jStorage.set( CACHEsubTotal, subTotal );
</code>```

UPDATE DEC 2017:

Today I use localDataStorage, where one may transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Examples:

```<code>localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );

localDataStorage.get( 'key1' );   -->   'Belgian'
localDataStorage.get( 'key2' );   -->   1200.0047
localDataStorage.get( 'key3' );   -->   true
localDataStorage.get( 'key4' );   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' );   -->   null
</code>```

All of the conversion work is done in the background: just set and get.

Title: Javascript storing data

Body:
I have personally used jStorage (www.jstorage.info) in a client project. The API is simple, cross-browser and uses HTML5 local storage where available. (It uses userData behavior in decrepit versions of IE.) With local storage, you can unplug your PC with no data loss, so it will certainly persist your data across page loads.

Sample syntax:

var subTotal = $.jStorage.get( CACHEsubTotal );
subTotal += currentlySelectedItem;
$.jStorage.set( CACHEsubTotal, subTotal );

UPDATE DEC 2017:

Today I use localDataStorage, where one may transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Examples:

localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );

localDataStorage.get( 'key1' );   -->   'Belgian'
localDataStorage.get( 'key2' );   -->   1200.0047
localDataStorage.get( 'key3' );   -->   true
localDataStorage.get( 'key4' );   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' );   -->   null

All of the conversion work is done in the background: just set and get.


问:
Coding Style And defects
Over the years I have developed several style based techniques which I use to keep my from make Error if(const == lvalue) rather then if(lvalue == const) since the first can't fall victim to the classic accidental assignment goof.

I recently  worked on a project with very unusual style standards and I found that I had much greater difficulty reading code.  Has anyone seen any statistics on a particular coding style and its defect levels or have any experience with changing style alone to improve defect rates.

答:
In general, the most significant characteristics of a coding style are that the company has one, and that it is followed consistently by everyone.  The actual details of that coding style are of secondary importance, provided the coding style is a reasonably good one.

The (const == lvalue) trick has been largely superseded by the fact that compilers and IDE's are now available that can generate a suitable warning.

Title: Coding Style And defects


答:
One of the reasons I think this discussion comes up repeatedly is because it seems like a serious pain-in-the-ass to take an object with all the data you need and convert it to an object that looks identical or nearly identical to the one you are handing off.

It's true, it's a PITA. But there are a few reasons (besides those enumerated above) for doing so.

Domain objects can get very heavy and contain a lot of useless information for the call. This bloat slows down the UI because of all the data transmitted, marshalled/unmarshalled and parsed. When you consider a FE will have numerous links referring to your webservices and being called with AJAX or some other multi-thread approach you will quickly make your UI sluggish. All this gets to the general scalability of webservices

Security can easily be compromised by exposing too much data. At a minimum you could expose email addresses and phone numbers of users if you don't eliminate them from the the DTO result.

Practical considerations: For 1 object to parade as a persisted domain object AND a DTO it would have to have more annotations than code. You will have any number of issues with managing the state of the object as it passes through layers. In general this is be much more of a PITA to manage then simply doing the tedium of copying fields from a domain object to a DTO.

But, you can manage it fairly effectively if you encapsulate the translation logic into a collection of converter classes

Have a look at lambdaJ where you can do 'convert(domainObj,toDto)' there is an overload of this for use with collections. Here is an example of a controller method that makes use of it. As you can see, it doesn't look so bad.

```<code>    @GET
    @Path("/{id}/surveys")
    public RestaurantSurveys getSurveys(@PathParam("id") Restaurant restaurant, @QueryParam("from") DateTime from, @QueryParam("to") DateTime to) {

        checkDateRange(from, to);

        MultiValueMap<Survey, SurveySchedule> surveysToSchedules = getSurveyScheduling(restaurant, from, to);
        Collection<RestaurantSurveyDto> surveyDtos = convert(surveysToSchedules.entrySet(), SurveyToRestaurantSurveyDto.getInstance());
        return new RestaurantSurveys(restaurant.getId(), from, to, surveyDtos);

    }
</code>```

Title: Entity to DTO Usage

Body:
Been trying to come up with a flow for a basic tiered web application, and have been reading conflicting information online.  What I'm trying to figure out is if there is an advantage to still using DTO objects from your DAO to Service layer through the use of some sort of mapper.

The basic flow I foresee is as follows:

UI Model / Form --> Controller

Controller converts Model into Domain Object (Entity)

Domain Object --> Service Layer

Domain Object --> DAO

DAO --> Domain Object(s)

Service --> UI

UI converts Domain into UI models

If DTO was followed DAO would pass back a DTO not the Entity.  After doing some reading it seems like DTO has become slightly defunct since (at least in Java) entities have become annotated POJOs meaning their memory footprint has become very small.

Is this the case, or should DTOs be used to completely encapsulate the domain objects within the DAO layer, and, if this is the case, what would the service layer pass to the DAO?

Thanks a bunch!

Body:
One of the reasons I think this discussion comes up repeatedly is because it seems like a serious pain-in-the-ass to take an object with all the data you need and convert it to an object that looks identical or nearly identical to the one you are handing off.

It's true, it's a PITA. But there are a few reasons (besides those enumerated above) for doing so.

Domain objects can get very heavy and contain a lot of useless information for the call. This bloat slows down the UI because of all the data transmitted, marshalled/unmarshalled and parsed. When you consider a FE will have numerous links referring to your webservices and being called with AJAX or some other multi-thread approach you will quickly make your UI sluggish. All this gets to the general scalability of webservices

Security can easily be compromised by exposing too much data. At a minimum you could expose email addresses and phone numbers of users if you don't eliminate them from the the DTO result.

Practical considerations: For 1 object to parade as a persisted domain object AND a DTO it would have to have more annotations than code. You will have any number of issues with managing the state of the object as it passes through layers. In general this is be much more of a PITA to manage then simply doing the tedium of copying fields from a domain object to a DTO.

But, you can manage it fairly effectively if you encapsulate the translation logic into a collection of converter classes

Have a look at lambdaJ where you can do 'convert(domainObj,toDto)' there is an overload of this for use with collections. Here is an example of a controller method that makes use of it. As you can see, it doesn't look so bad.

    @GET
    @Path("/{id}/surveys")
    public RestaurantSurveys getSurveys(@PathParam("id") Restaurant restaurant, @QueryParam("from") DateTime from, @QueryParam("to") DateTime to) {

        checkDateRange(from, to);

        MultiValueMap<Survey, SurveySchedule> surveysToSchedules = getSurveyScheduling(restaurant, from, to);
        Collection<RestaurantSurveyDto> surveyDtos = convert(surveysToSchedules.entrySet(), SurveyToRestaurantSurveyDto.getInstance());
        return new RestaurantSurveys(restaurant.getId(), from, to, surveyDtos);

    }


答:
It is perfectly reasonable for a corporate customer to prefer to host your application internally. It allows them to set the standard for accessing the data directly, for backups, to survive your eventual death, etc.. A business should be concerned if one individual over whom they have no oversight and for whom they have no replacement controls something that is critical to their business. What if you get hit by a bus?

To mitigate this, contracts were invented. You can sign a new contract with them, that (for example)

Grants them a copy of the source code.

Grants them permission to run an instance of the application for their business.

Grants them permission to modify the application for their business.

Denies them permission to release the source code, and specifies penalties.

Denies them permission to derive new applications from the source code, and specifies penalties.

Absolves you of any responsibility for correcting their changes to the source code.

Absolves you of any responsibility for integrating changes to your version of the source code and their version of the source code; you are required only to provide them with the source code that produces the application you host for other clients.

You should see a lawyer about what should be included in any contract, I am not a lawyer.

Title: Protect Database Design - SQL

Body:
Perhaps a bit of an odd question but I can't think of a way to achieve what I want.

I produce a product which ends up installed on-site at clients premises. It is a business critical and high availability application, and has to handle processes very quickly.

While obviously most of the work goes into the actual application (Windows Services) part of the reason why the product is so good is intelligent database design.

Until recently I usually provided the servers and I was the only person to have access to the database and SQL Server instance. However more recently customers have asked to run the application on their production server, usually VMWare, and use their SQL Farm for the database.

This is fine for the application, however I am worried about who will have access to the SQL server and if they would be able to have a poke around in my application's database.

Is there anything I can do to prevent access to it? Or is it a case of if they're hosting it there is nothing I can do?

Thanks

EDIT:

If I am hit by a bus, company folds etc. there is an escrow agreement which will give them the source code of everything they need.

As to why I am worried I have seen examples in the past of people making changes to data tables and reports, and no they did not have  the nous to do so. This meant that someone had to go in and fix everything, while of course we charge for this I was wondering if there was a way to avoid it all together, or at least minimise the risk.


答:
You should concern yourself with data rather than subjectivity. Thus you should be monitoring/measuring/profiling to determine improvements. That monitoring needs to be in both production and test (and dev) environments.

Ideally, you shouldn't be optimizing anything until after you see the results of performance. Otherwise you risk a "premature optimization" which doesn't improve anything meaningful and perhaps was a waste of time and money. It is very easy to see a piece of code and think, "This is terrible, it will never perform well." only to find out later that it is only executed 1% of the time and the real bottleneck is somewhere else.


问:
Ensuring that headers are explicitly included in CPP file
I think it's generally good practice to #include the header for any types used in a CPP file, regardless of what is already included via the HPP file. So I might #include <string> in both my HPP and CPP, for example, even though I could still compile if I skipped it in the CPP. This way I don't have to worry about whether my HPP used a forward declaration or not.

Are there any tools that can enforce this #include coding style? Should I enforce this coding style?

Since the preprocessor/compiler doesn't care whether the #include is coming from the HPP or CPP, I get no feedback if I forget to follow this style.

答:
I would say there are both advantages and disadvantages to this convention. On the one hand it is nice to know exactly what your .cpp file is including.  On the other hand, the list of includes can easily grow to a ridiculous size.

One way to encourage this convention is not to include anything in your own headers, but only in .cpp files.  Then any .cpp file using your header will not compile unless you explicitly include all other headers it depends on.

Probably some reasonable compromise is in order here.  For example, you may decide it is ok to include standard library headers inside your own headers, but no more.


问:
Dev approaches to complex JavaScript UI's
I am trying to understand the landscape of different approaches, and best practices, around the development of complex client-side JavaScript.

I'm not sure what to label this class of application, perhaps heavy AJAX or RIA (but not plugins like Flash/Silverlight).  I'm referring to web apps with these characteristics:

Emulate rich/native desktop UX in JavaScript

Contain most/all behavior in client-side JS, using the server as a data-API (JSON/Html-Templates).

This is in contrast to using the web-server for the UI rendering, producing all HTML in a page-refresh model.

Some examples are:

Google Docs / Gmail

Mindmeister

Pivotal Tracker

As we move forward into HTML5, I can see this style of RIA development, with heavy JavaScript, becoming ever more common and necessary to compete.

QUESTION: So what are the common approaches emerging around managing these kinds of heavy JS developments?

Client-side code, as an app grows in features, is fiendishly complicated.  There are problems scaling a development effort across multiple teams with raw JS (or so I hear, and can well believe it).

Google has approached the problem by building GWT that compiles from a higher level language (Java) to JS, leaning on the existing development infrastructure that the higher level language has (Eclipse, strong-typing, refactoring tools), along with abstracting browser compatibility and other issues away from the developer.

There are other tools, like Script# for C# that do something similar.  All this puts JS more in the role of an IL (Intermediate Language). ie. "You never really write in that 'low level language' anymore."

But this 'compile to JS' is not the only approach.  It's not apparent that GWT is the dominant approach...or indeed will become it.

What are people doing with rich-client JavaScript? Some orienting questions:

Are most shops crafting JS manually (atop libs like jQuery et al)?

Or are there many many different approaches, with no clear best-practice emerging?

Are most shops avoiding RIA scale development in favor of the simpler to developer server-side/page-redraw model?  If so, will this last?

Is compiling to JS perhaps an emerging future trend?  Or is this just wrong headed?

How do they manage the complexity and refactoring of client JS?

Modularization and distribution of work across teams?

The application, enforcement, and testing of client-side patterns like MVC/MVP etc.

So, what are the emerging trends in this heavy-JavaScript and HTML5 future of ours?

Thanks!

答:
I would say GWT is risky. Once you decided to use it you're stuck with it. Basically it means that you treat your markup, DOM and some aspects of CSS as an execution environment. It's getting really hard to mix manually written JavaScript with GWT as your client code becomes more and more sophisticated. GWT has native methods but those are quite limited in terms of possible applicability. That's a big trade off and it's a big bet.

Google tries to sell GWT as a very fast X-platform execution environment with a decent server-side integration. But as others already pointed out it's no longer the case - JQuery and YUI are as fast if not faster. And it's much easier to profile and optimize your pages when they are assembled manually so you have a full control over CSS, markup and JavaScript.

GWT tries to hide the underlying platform from you which might actually be a wrong way to do things. A lot of so-called component web-frameworks did the same. You were supposed to write ambiguous XML-derived code with EL and custom tags thrown in. The output would be a mess of poorly formed HTML with small pieces of crappy JavaScript sprinkled all over the place. Pages were slow, buggy and totally unmaintainable.

In our current project we use Stripes - a low-level action-based framework, - and JQuery on a client side. It's very easy to do Ajax once you clearly see all pieces of a puzzle: here's your Server-side code which operates on data. Here's your client-side code - for data retrieval and for making things happen on a pages. Here's your CSS, here's your markup, here's your templating - everything is clean and decoupled. Easily extensible, hackable, tunable and debuggable. I love it.

I love JQuery with it's attitude towards speed and simplicity. I love YUI3 for modularity and comprehensive widgets. I love YUI CSS for giving me consistency across browsers. I love JavaScript for Good Parts. I love Java for letting me Get Job Done.

Just KISS, and you'll be fine!


问:
Program modules separated in different DLLs
We have an existing ERP system written in VB 6 that we are converting to .Net incrementally. Now, every module in the system is being separated into DLLs so that the product becomes customizable and flexible. I'm not sure if this is the way to do this.

I think this will cost a lot of maintenance in the future. What do you think?

答:
A DLL itself doesn't constitute a module design or improve flexibility. It meanly defines the state that the compiled source code exists in and is transported into the application.

Customizability

Usually implies an API layer that allows developers to plugin additional functionality as either optional features, customer requested features or to separate feature development from application framework development.

The Pros

Isolation of source code ensures that a plugin developer doesn't make unnecessary changes to the application.

Ability to load features on demand.

Ability to expand the application over time.

Clearly define boundaries between layers allow for different developments team with different skill sets. (i.e. a core team, a UI team and a features team).

Different release schedules for the different modules can make meeting deadlines easier.

The Cons

Tight coupling between plugins and application API can cause higher development costs when the API needs to change.

The cost of implementing a feature can increase as the API layer has to always be adjusted to accommodate new requirements.

The advantages of replaceable components is never utilized by the business. I see this happen a lot, where developers sing the praises of modular design but the business never takes advantage of it.

The need to support the lowest common denominator. Rather than support the latest version of something like OpenGL. The application is stuck using an older version, because the API is too generic and improving the API is too costly.

If different development teams create modules, then the application can suffer from having different user experiences for features.


答:
I don't think such a tool exists, but I would be happy if some other answer disproves me.

The problem with writing such a tool is that it very easily reports a false result, so I estimate the net advantage of such a tool to be close to zero.

The only way such a tool could work is if it could reset its symbol table to just the contents of the header file it processed, but then you run into the problem that the headers that form the external API of a library delegate the actual declarations to internal headers.

For example, <string> in the GCC libc++ implementation does not declare anything, but it just includes a bunch of internal headers that contain the actual declarations. If the tool resets its symbol table to just that what was declared by <string> itself, that would be nothing.

You could have the tool differentiate between #include "" and #include <>, but that doesn't help you if an external library uses #include "" to include its internal headers in the API.

Title: Ensuring that headers are explicitly included in CPP file

Body:
I think it's generally good practice to #include the header for any types used in a CPP file, regardless of what is already included via the HPP file. So I might #include <string> in both my HPP and CPP, for example, even though I could still compile if I skipped it in the CPP. This way I don't have to worry about whether my HPP used a forward declaration or not.

Are there any tools that can enforce this #include coding style? Should I enforce this coding style?

Since the preprocessor/compiler doesn't care whether the #include is coming from the HPP or CPP, I get no feedback if I forget to follow this style.


答:
If you are concern about record IDs presenting some kind of security risk, then do not use auto-incrementing integers.

I can see a record ID as 2837 then I know there is a 2836, 2835 and so on.

Instead, use UUID as a record identifier. This will ensure each record gets a UUID that is different, and using reading one UUID doesn't give you any information about what other UUID might exist in the system.

There is a Codeigniter UUID project that might help, and some information on what UUIDs are.

Title: Pass around record ids in the url in PHP

Body:
I'm doing a PHP application with CodeIgniter and most of my controllers accept record ids as parameters for retrieving purposes.
I also pass record ids in my forms action.
Like this: www.sample.com/records/save/sFKu=4

Is this the right way to do this? Note that the record ids are encrypted.


问:
Are regular expressions a programming language?
In the academic sense, do regular expressions qualify as a programming language?

The motivation for my curiosity is an SO question I just looked at which asked "can regex do X?" and it made me wonder what can be said in the generic sense about the possible solutions using them.

I am basically asking, "are regular expressions Turing complete"?

答:
In .Net, not only can Regex handle multiple forms of conditionals, using different combinations of alternation and lookarounds, but can also manipulate its own stack.

```<code>(?xm)
    (?>
        <(?<Tagname>table)[^>]*>
    )
(?(Tagname)
    (
        </(?(?!\k'Tagname')(?<-Tagname>))*\k'Tagname'>(?<-Tagname>)
    |
        (?>
            <(?<Tagname>[a-z][^\s>]*)[^>]*>
        )
    |
        [^<]+
    )+?
    (?(Tagname)(?!))
)
</code>```

This, for example, is a small snippet I wrote to retrieve an HTML Table.  Unlike other regex engines, this controls the stack of capture collections (push, peek, and pop), and can handle nested objects.  I have a more complex one, but it's sorta proprietary.

I think in this example, Regex can be looked at as having all the basic requirements of a programming language.  It has variables, inline memory, conditionals, input and output, it compiles using one of multiple regex compile engines (.Net in this case).

In Response to the over-used squawking to (NEVER) Parse HTML with Regex, I went ahead and posted a pre-typed response that I can post: Parsing HTML

Anoter example (just a demonstration) is the following:

```<code>Function Regex("<(td>)((?:[^<]*(?(?!</\1)<))*)</\1")
    Group(0) = "<"
    Group(1) = "td>"
    Group(0) += Group(1)
    Group(2) = LoopMethod()
    Group(0) += Group(2)
    Group(0) += "</" & Group(1)
    Return Group()
End Function

Function LoopMethod()
    retGroup = ""
    Do
        tmpGroup = Everything that is NOT an Opening HTML Delimeter
        If the Text following tmpGroup Does NOT Equal "</" & Group(1) Then
            tmpGroup += "<"
            retGroup += tmpGroup
        Else
            Exit Do
        End If
    Loop
    Return retGroup
End Function
</code>```

Again, for the HTML parrots: Parsing HTML

This shows a simpler regex performing loops and conditionals (algorithms?).  The only thing missing is actual Mathematical computation.  This is a more detailed Regular Expression which just pulls a TD Cell more efficiently than the typical "(.*?)" method.

But even as a Regex enthusiast and self-proclaimed master, I wouldn't go around telling anybody Regex is a Programming language.  My own argument against myself is that it can't stand alone, it has to be run through its own engine while being supported by another programming language engine.

Body:
In .Net, not only can Regex handle multiple forms of conditionals, using different combinations of alternation and lookarounds, but can also manipulate its own stack.

(?xm)
    (?>
        <(?<Tagname>table)[^>]*>
    )
(?(Tagname)
    (
        </(?(?!\k'Tagname')(?<-Tagname>))*\k'Tagname'>(?<-Tagname>)
    |
        (?>
            <(?<Tagname>[a-z][^\s>]*)[^>]*>
        )
    |
        [^<]+
    )+?
    (?(Tagname)(?!))
)

This, for example, is a small snippet I wrote to retrieve an HTML Table.  Unlike other regex engines, this controls the stack of capture collections (push, peek, and pop), and can handle nested objects.  I have a more complex one, but it's sorta proprietary.

I think in this example, Regex can be looked at as having all the basic requirements of a programming language.  It has variables, inline memory, conditionals, input and output, it compiles using one of multiple regex compile engines (.Net in this case).

In Response to the over-used squawking to (NEVER) Parse HTML with Regex, I went ahead and posted a pre-typed response that I can post: Parsing HTML

Anoter example (just a demonstration) is the following:

Function Regex("<(td>)((?:[^<]*(?(?!</\1)<))*)</\1")
    Group(0) = "<"
    Group(1) = "td>"
    Group(0) += Group(1)
    Group(2) = LoopMethod()
    Group(0) += Group(2)
    Group(0) += "</" & Group(1)
    Return Group()
End Function

Function LoopMethod()
    retGroup = ""
    Do
        tmpGroup = Everything that is NOT an Opening HTML Delimeter
        If the Text following tmpGroup Does NOT Equal "</" & Group(1) Then
            tmpGroup += "<"
            retGroup += tmpGroup
        Else
            Exit Do
        End If
    Loop
    Return retGroup
End Function

Again, for the HTML parrots: Parsing HTML

This shows a simpler regex performing loops and conditionals (algorithms?).  The only thing missing is actual Mathematical computation.  This is a more detailed Regular Expression which just pulls a TD Cell more efficiently than the typical "(.*?)" method.

But even as a Regex enthusiast and self-proclaimed master, I wouldn't go around telling anybody Regex is a Programming language.  My own argument against myself is that it can't stand alone, it has to be run through its own engine while being supported by another programming language engine.


问:
Re-architecting a classic inheritance design
I have the opportunity to rewrite a core piece of a project (C#) that is inheritance-heavy and feels increasingly restrictive in how it is designed. The scenario is pretty simple, imagine an application that is built to handle various small tasks. Every task is unique in it's functionality so it implements an ITask interface with a few simple methods that get implemented by each task class (e.g. Init(), Start(), Stop(), etc).

In addition to the ITask interface there is also an abstract BaseTask class that all tasks inherit from. This BaseTask class is sort of an 'everything but the kitchen sink' approach that contains useful pieces of functionality that the tasks often require. For example, all tasks record their status and progress the exact same way so this logic is defined in the BaseTask and available to all children through a protected method. Or to give another example, some tasks have to send email notifications out when certain conditions are met, so again, the BaseTask provides access to the core smtp functionality of the app for this purpose. There are many examples of these kind of 'helper' methods/properties

The problem of course is that this base class has already grown unwieldy and cluttered with properties and methods that are not universal to all tasks and it's starting to introduce more problems than it is solving. For example, anytime a change is required to the base class you find yourself in a position where you might wind up breaking some (or all) of the tasks. It also just seems like its breaking encapsulation and the single responsibility principal. It's also quite clear how this happened in the first place (and a common occurrence too). Initially this was a very small, specialized application but it blew up in terms of scope and size very quickly and what was initially probably not a bad decision architecturally has proven inflexible and awkward.

Where would you start with something like this? How would you approach the problem and what principals or design patters would you choose? Thank you very much

答:
Step 1: Make each of those methods in BaseTask static and pass any required private members as arguments. Now they can live, and breathe comfortably, outside of the class.

Step 2: Implement an IOC container. Resolve your tasks from there.

Step 3: Take all of those protected methods and move them to a service, make them public. Make them non-static. Don't use them yet.

Step 4: Find a related group of methods, delete them and create an interface that exposes all of those methods. Implement that interface on your service (should be easy, as you're deleting methods that exist here) and constructor-inject them into only the tasks that are no longer compiling.

Step 5: Repeat step 4 until all the methods have gone from BaseTask.

Step 6: Break the service up into smaller services that implement only one interface; let your IOC registration know.

Step 7: Refactor til you drop.


答:
I've seen the same complexity in Infragistics controls which can do just about anything you want but they provide an unwieldy API that is almost impossible to navigate without experience.

With large APIs it makes sense to logically group methods into functional suites that all serve a single area of responsibility.  For this I might create decorators.  Doing so is very simple and straightforward so it will greatly reduce your chances of introducing bugs.  Each decorator is instantiated as needed in order to access the features it provides.  Your decorator would do nothing more than wrap the core object (a task) with additional properties/methods -- relocating the existing ones from the core object to the decorator object.

Title: Re-architecting a classic inheritance design

Body:
I have the opportunity to rewrite a core piece of a project (C#) that is inheritance-heavy and feels increasingly restrictive in how it is designed. The scenario is pretty simple, imagine an application that is built to handle various small tasks. Every task is unique in it's functionality so it implements an ITask interface with a few simple methods that get implemented by each task class (e.g. Init(), Start(), Stop(), etc).

In addition to the ITask interface there is also an abstract BaseTask class that all tasks inherit from. This BaseTask class is sort of an 'everything but the kitchen sink' approach that contains useful pieces of functionality that the tasks often require. For example, all tasks record their status and progress the exact same way so this logic is defined in the BaseTask and available to all children through a protected method. Or to give another example, some tasks have to send email notifications out when certain conditions are met, so again, the BaseTask provides access to the core smtp functionality of the app for this purpose. There are many examples of these kind of 'helper' methods/properties

The problem of course is that this base class has already grown unwieldy and cluttered with properties and methods that are not universal to all tasks and it's starting to introduce more problems than it is solving. For example, anytime a change is required to the base class you find yourself in a position where you might wind up breaking some (or all) of the tasks. It also just seems like its breaking encapsulation and the single responsibility principal. It's also quite clear how this happened in the first place (and a common occurrence too). Initially this was a very small, specialized application but it blew up in terms of scope and size very quickly and what was initially probably not a bad decision architecturally has proven inflexible and awkward.

Where would you start with something like this? How would you approach the problem and what principals or design patters would you choose? Thank you very much


答:
doesn't #Pragma once achieve this? You can include something as many times as you want, either directly or via chained includes, and as long as there is a #Pragma once next to each of them, the header is only included once.

As to enforcing it, well maybe you could create a build system that just includes each header by itself with some dummy main function, just to ensure it compiles. #ifdef chain includes for best results with that method of testing.


答:
I think this huge base class is a symptom of something deeper.

In your case I see two problems, which you should focus on solving before you start refactoring.

Developers are not experienced in OOP design. This is quite common problem. Instead of creating proper OOP structure, they simply find one global place and put their code here. So even if you have some semblance of OOP on the outside, it degenerates into procedural code on the inside. Try teach your developers in proper OOP design and motivate them to practice it.

The Task abstraction stopped being enough. Thanks to much complex requirements, it seems that you should make much more fine-grained abstraction. So instead of focusing on implementing specific task, you focus on separate components and then compose final task from those components. If you had proper OOP design and were doing refactoring as you went, you would probably see this problem much sooner.

If you don't fix these problems before you start refactoring, the problem might reappear. But this time, it will be even worse thanks to increased complexity.

Also, I would recomend you do practice Test Driven Development or at least make unit tests for most common use-cases. This will help you understand how your design should look like from outsider's perspective.


问:
How to handle conflicts between developers in your team?
This is happening in every team.

For some reasons, conflicts arise in the team and they affect the overall motivation and productivity.

What is your recommended approach to solve that common problem?

Examples:

one part of the team wants to implement dependency injection, the other part think it's a waste of time.

some developers think the rest of the team is slowing down development (which explains why they are late on the schedule)

personal incompatibilities between one or more developers

one developer refuse to talk to another one (without apparent reason)

答:
Have a third-party unbiased mediator sit down with both conflicted parties and have them talk it out.

It helps if the mediator is someone the problem-havers are comfortable talking around, but that they still respect and will not talk overtop of


答:
This sounds like a prime candidate for the SOLID principles.

S: Single Responsibility Principle

Separate out all the functionality in the base class into separate classes, each doing only one thing. Need to send emails through an SMTP server? Build a single class that does this. Need to send emails through an Exchange server (without using its SMTP interface)? Implement a different class that does this. If needs be, create inheritance here with what is common.

For instance, sending email is pretty much universal in requirements, so build a base class that has the common items, and derived classes that implement the actual sending logic, i.e. talking to the different kinds of servers.

O: Open/Closed Principle

Instead of making one task able to report through email, make it able to report through some common interface that can take the type of report it produces. If it reports only dumb text, that's what the interface should be about. Don't make the interface named or topically related to email. This way you can bolt-on new classes later that can take those reports and send them through IM, through SMS, dump them to a logging system, or similar.

If the task needs input, say from a file, make it instead take an interface akin to a "input source" which it would ask for the input to process. This way the task could take any kind of source as input, as long as the source could produce the input in the format required by the task. Today you can process files, tomorrow you can process records from a database, or pages downloaded over HTTP.

This way you can finalize the logic of the task (close it), while still keep it open for new features later on (new types implementing the required interfaces).

L: Liskov Substitution Principle

(not sure how this would apply)

I: Interface Segregation Principle

Move everything out of the base class, except those things that logically belong in there, i.e. those things that all tasks require/need. Everything else should be in small classes that can easily be tested by themselves, reused in other places, etc.

D: Dependency Inversion Principle

Instead of adding SMTP capabilities to a task that needs to report progress, make it take in an object implementing a generic (not in the .NET/C# way, but a general-purpose) interface that is about reporting, and make the task type use that object for its reporting purposes. This way, today, you only have email reporting using SMTP, but the knowledge about how to send that report is neither built into the class, or hard-wired into the environment of the class. The task can in the future be asked to report over any kind of medium that can be targeted by a type implementing that very same interface.

OwnerDisplayName: Lasse V. Karlsen


答:
Right now its standard practice for retrieval BUT i think it should be avoided whenever possible.

Whereas if you have a unique name for the same asset like:

sample.com/products/galactic_telescope

now you have given real meaning to the URL - for humans and for search engines. and you have a flexible system. you can change the ID of that product, you can add variations and accessories, it can go out of stock - and the URL remains the same.

If you are using forms then you can pass the ID in a hidden form field. It also allows you to do other kinds of checks - like you can validate and check the value of that field in your constructor - and if no good - for example the form was filled in by a rogue bot - bounce to a different page or class before any other actions.


问:
Implementation of automated updates
What is the best way to implement automated updates?  I've gotten as far as libcurl, I imagine I need to ping the server every now and again with the current version of the software.  But then what should I do?  What server tech needs to respond, and how? </p>

答: I'd have the server run a checksum on itself and then respond with that checksum. If the checksum is current, then the system continues on as normal. Otherwise, you'd push the update to the server and undertake the steps necessary to install it. Using diff is also an option.</p>

Title: Implementation of automated updates


答:
You may want some intermediate classes.  Say classes W and X want to do something one way, and classes Y and Z want to do it another.  You currently have some confusing method in base class A that does it both ways with lots of if's.  Create subclasses of A, say B and C, each with its own copy of this method containing only relevant code.  Now make W and X inherit from B and Y and Z inherit from C.

This gets complicated as you add methods, but with luck and a little brilliance you have a chance of ending up with orderly, easy-to-understand, simple, DRY code.  There may be lots of classes and several levels of inheritance, but each class ought to be easy to understand.


答: Always include header files in CPP file. This not only shorten compile time significantly, but also saves you a lot of trouble if you decide to go with precompiled headers. In my experience, even doing the trouble of forward declarations is worth while practice. Break rule only when necessary.</p>