问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Missing user requirements

An important and difficult step of
  designing a software product is
  determining what the customer actually
  wants it to do.

Believe it or not sometimes this part is missing or is outdated.
What it comes to cost is that one creates functionalities that the end user never asked for.


问:
Branching strategy to avoid multiple release branches for different customers
I am currently thinking of the following branching strategy

Main branch

Development branch

Feature branch

Release branch

Basically the whole idea is to have a release branch so that hot fix can be applied quickly for specific release.

Here is the issue what if I have an urgent feature that I need to do for a specific customer and I do not want those feature to be applied to other customer using the same release version until it is fully tested. At the same time I do not wish to create multiple release branches for different customers as this will complicate stuff.

What is the best way to handle such situation?

答:
If it concerns a feature that will be delivered to all customers once it has been fully tested, and this one customer takes up part of the testing effort, then it is best to use a second release branch for the testing of this feature. After the feature has been found to be stable enough, the second release branch can be merged into the official release branch.

If the feature will not be used by all customers, then it is better to use a feature toggle, as outlined in the answer by @aquaranga.

ContentLicense: CC BY-SA 3.0


问:
AMD based JavaScript Development for static websites
I'm have been doing some research into making code more testable and modular, but after reading alot about AMD based JavaScript, it doesn't appear to fit the needs of a static website. Is this assumption correct? Is AMD based development geared more toward highly interactive web applications that simple websites?</p>

答: For a truly static website, I'd try to get by with as little javascript as possible (or none -- you can do quite a bit with just HTML and CSS).  Remember, some people browse with javascript disabled.  You wouldn't want to limit your audience unnecessarily. </p>


答: You could see AMD loaders as the missing include of JS. Do you need a big site to start including some files in others?

Title: AMD based JavaScript Development for static websites

Body: I'm have been doing some research into making code more testable and modular, but after reading alot about AMD based JavaScript, it doesn't appear to fit the needs of a static website. Is this assumption correct? Is AMD based development geared more toward highly interactive web applications that simple websites?</p>


问:
Is outsourcing code more expensive in the long term? Does it harm code quality?
I am aware of a company that owns the intellectual property of a decent software product and makes an excellent income from licensing per annum. However, the director (non technical) complains about the cost of maintaining the development team, as it eats significantly into the profit margins, and is considering outsourcing development of specific modules to other countries that charge at a lower rate.

Personally, I don't think this will be a more cost effective solution in the long term. This can lead to communication breakdowns when there are problems, additionally the specifications will need to be water tight which can end up taking taking more time anyway. In my opinion, when working in teams communication is key - or is there an effective way of making this work?

答:
I don't remember the author of this quote, but it hits the nail.

"Loosely coupled teams working together on tightly coupled components fails. Inevitably"

Outsourcing = loosely coupled teams.

Trying to reduce costs by geographically splitting work on interdependent components always fails.

On the other hand, based on my experience, moving a whole part of the software portfolio might work, meaning it can be developed in good quality with reduced costs.


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
If you can make it a web app, make it a web app. Using toolkits like ExtJS, it's relatively easy to make good looking GUI-like cross-browser compatible user interfaces.

Otherwise, Java or QT+C++ or C+Wx are possible options to have one source for all.

Your second approach is appropriate if you want the app to look and feel native on every target platform. Native Mac apps look and feel different than native Windows apps, just using another skin and keybinds will not be enough to cover that.

ContentLicense: CC BY-SA 2.5


问:
Is it useful to use encapsulation in dynamic typed, interpreted programming language?
For what I know, encapsulation is useful because:

if you use directly an attribute and change its type in a static typed language you have to change all the code that uses the class. On the contrary, if you have declared getters and setters for that attribute you have not to do this

it hides the internal functioning of your class, useful if, for example, you're offering an API

it avoids that another class that inherits your class will overwrite attributes or methods

My considerations about dynamic typed, interpreted programming language are:

since the types are dynamic there's no need to encapsulate your class for this reason

you can see the code of an interpreted language, so I think there's not a way to really hide your API

this could be a problem when this is unintended, but my opinion is that it should be better to make attention to unintended overwriting instead of limiting by default this possibility. Python is a good example: if you declare for example, the name of an attribute or method starting it with a double underscore, you can declare it also in a inherited class, but they are threated as two distinct variables even if they have the same name (thank you delnan)

<s>a method name that starts with a "_" character raises a warning if overwritten by a method of an inheriting class.</s>

Am I missing something important?

答:
Yes, you are missing something.

Encapsulation is often described with metaphors of "hiding" or acting "defensive", as if client programmers were your enemy and you had to act stealthily and sneakily to defend yourself against their evil intentions. That is sometimes helpful; for instance, if you program extremely popular frameworks that have to maintain compatibility across a huge number of situations and versions, you start to think of your users as ignorant barbarians whose only intent in life is to cause you trouble with their unreasonable demands of "But it used to work!" or "But I can see that it's an array internally! Why, why, why won't you let me access the elements directly??"

However, the normal case is that the layer using your code is programmed by the same person as your own layer: yourself. Therefore point is not actually to hide information from other routines and their creators, but to free its caller from having to understand it. The trick is to make it possible to write higher-up routines without knowing about the details. The cognitive delusion that if you created something yourself, you are obviously going to understand everything it does is extremely common and extremely strong; large parts of software engineering are dedicated to mitigating the consequences of this error of thought. If you program a subroutine, but you need to know how it works internally in order to use it properly, then you might as well not have a subroutine, because the mental effort necessary isn't actually reduced: the code looks clean and modular, but actually isn't.

This is why we separate big amounts of code into small partitions: because a small amount of code is easier to understand than a large amount, and crucially, two properly decoupled small bits of code are easier to understand than one bit twice the size, because interdependencies within the larger bit add cognitive effort. If we don't avoid that extra effort, sooner or later it will exceed our capability to understand the entire system, and it soon becomes unmaintainable.


问:
What is a good pattern for multi language in MongoDb?
Say I want to build a website that support multiple language and use MongoDB datastore. I wonder what is a good approach to have multiple versions of the body and title of an article, one for each language.

Should I keep all versions in the same article document? Like a collection of key-value pairs of language code and text in the body field of the article. This way I'd get no more than 1 request for viewing articles, but I'd also get more data than I might need so the response is larger.

Is there a better solution? How and why?

答:
I use the following pattern for text that should be indexed in all the languages:

```<code>{
"id":"sdsd"
"title":{"languages":{"en":0,"fr":1},"texts":["this is the title in inglish","Celui ci c'est le titre en francais"]}
}

object = coleccion.find("id='xxxxx'");
</code>```

// now if want the text in English

```<code>print(object.title.texts[object.title.languages["en"]])
</code>```

// the use of objecttitle.languages index array it to improve performance in client accessing a determined text

// that allows us to add indexes to your translated texts on mongo, as

```<code>ensureIndex({title.texts})
</code>```

We can also wrap the code to obtain text in an specific language in a Class.

Body:
I use the following pattern for text that should be indexed in all the languages:

{
"id":"sdsd"
"title":{"languages":{"en":0,"fr":1},"texts":["this is the title in inglish","Celui ci c'est le titre en francais"]}
}

object = coleccion.find("id='xxxxx'");

// now if want the text in English

print(object.title.texts[object.title.languages["en"]])

// the use of objecttitle.languages index array it to improve performance in client accessing a determined text

// that allows us to add indexes to your translated texts on mongo, as

ensureIndex({title.texts})

We can also wrap the code to obtain text in an specific language in a Class.


问:
Looking for meaningful, strong argument in favor of antivirus software on development machines
When forming opinions, it is a good practice to follow scholastic tradition - think as hard as you can against the opinion you hold and try to find counter-arguments.

However, no matter how hard I try, I just cannot find reasonable arguments in favor of antivirus (and related security measures) on development machines.

Arguments against antivirus(AV) in development are plentiful:

It is not uncommon for 1 minute build to take 10 times longer with AV on

In a conference talk, IntelliJ developers claim AV software is #1 suspect when their IDE is sluggish

Unzipping comes with roughly 100 kb/s speed with AV on

AV renders Cygwin completely unusable (vim takes 1 minute to open a simple file)

AV blocks me from downloading useful files (JARs, DLLs) from colleagues' e-mails

I can't use multiple computers for development, since AV / security measures prevent me from unblocking ports

AV kills performance of programs with high file turnover, such as Maven or Ant

Last, but not least - what does AV actually protect me from? I am not aware of my AV program ever stopping any security thread.

If the reason is fear of disclosing NDA stuff - no AV can possibly prevent me from doing it if I set my mind to it.

If the reason is fear of losing source code and/or documentation - there are distributed revision systems for this (there are at least 20 copies of our repo and we sync on daily basis).

If the reason if fear of disclosing customer data - developers rarely work connected to real production databases, instead they are playing around in toy environments.

Even if there are meaningful arguments in favor of having AV on development machines, they fall apart when faced with the ability to run a Virtual Machine in your paranoidly protected environment.

Since I want to keep an open mind of the issue, could anyone present meaningful, strong argument in favor of Anti-virus software for developers?

答:
On developer machines? Yes because developers tend to download all sorts of things (both related and unrelated to work).

On build machines, it's also important simply to protect yourself.  It would really stink to deploy/ship your code only to find that it has a virus once it makes it to its destination.


问:
What encoding is used by javax.xml.transform.Transformer?
Please can you answer a couple of questions based on the code below (excludes the try/catch blocks), which transforms input XML and XSL files into an output XSL-FO file:

```<code>File xslFile = new File("inXslFile.xsl");
File xmlFile = new File("sourceXmlFile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
FileOutputStream fos = new FileOutputStream(new File("outFoFile.fo");
transformer.transform(new StreamSource(xmlFile), new StreamResult(fos));
</code>```

inXslFile is encoded using UTF-8 - however there are no tags in file which states this.
sourceXmlFile is UTF-8 encoded and there may be a metatag at start of file indicating this.

am currently using Java 6 with intention of upgrading in the future.

What encoding is used when reading the xslFile?

What encoding is used when reading the xmlFile?

What  encoding will be applied to the FO outfile?

How can I obtain the info (properties) for 1 - 3? Is there a method call?

How can the properties in 4 be altered - using configuration and dynamically?

if known - Where is there info (web site) on this that I can read - I have looked without much success.

答:
If you know that the encoding is always going to be UTF-8, you could use the InputStreamReader class which allow you to specify an encoding, and pass those instances to StreamSource. Otherwise, I'd expect the system to use the encoding specified in the XML file, and if it's not specified then either use the system default encoding or make a best guess (that should not be depended on to be correct). The best solution would be to ensure that the XML files have correct encoding metadata.

The output encoding can be controlled using the <xsl:output> tag. From Java, this can be done using the setOutputProperty() method.


答:
XML is defined to be UTF-8 or UTF-16 with BOM in the absence of an explicit encoding in the prologue: http://www.w3.org/TR/REC-xml/#charencoding

If you're reading/writing an XML file using a standard parser/serializer, you should always use FileInputStream / FileOutputStream and rely on the library doing the right thing.

If you're getting input from an HTTP server, you have to pay attention to the encoding specified in the Content-Type header. In this case you should use an InputStreamReader to wrap the socket with the correct encoding. If you don't have an explicit encoding specification, just pass the socket's stream to the parser.

Similarly, if you're writing XML on a server, make sure that you're not accidentally creating an incorrect Content-Type. You should explicitly set application/xml without encoding, and rely on the serializer doing the right thing.

You should never write XML to a string and then write that string to a file. Nor should you ever write XML to a FileWriter (you shouldn't use FileWriter or FileReader for anything, not just XML, because they use the platform default encoding).

Unfortunately, a lot of people do that (or worse, don't use a serializer), so you may be getting a file that looks like XML but isn't.

Title: What encoding is used by javax.xml.transform.Transformer?

Body:
Please can you answer a couple of questions based on the code below (excludes the try/catch blocks), which transforms input XML and XSL files into an output XSL-FO file:

```<code>File xslFile = new File("inXslFile.xsl");
File xmlFile = new File("sourceXmlFile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
FileOutputStream fos = new FileOutputStream(new File("outFoFile.fo");
transformer.transform(new StreamSource(xmlFile), new StreamResult(fos));
</code>```

inXslFile is encoded using UTF-8 - however there are no tags in file which states this.
sourceXmlFile is UTF-8 encoded and there may be a metatag at start of file indicating this.

am currently using Java 6 with intention of upgrading in the future.

What encoding is used when reading the xslFile?

What encoding is used when reading the xmlFile?

What  encoding will be applied to the FO outfile?

How can I obtain the info (properties) for 1 - 3? Is there a method call?

How can the properties in 4 be altered - using configuration and dynamically?

if known - Where is there info (web site) on this that I can read - I have looked without much success.


答:
I agree that antivirus software is so intrusive that it makes one wonder whether the medicine is worse than the cure.  I, too, am tempted to turn it do without and see what happens.

However, I have never done this, because there are serious risks to doing without antivirus software.  Information can be stolen, data can be lost, or your computer can be bogged down by spyware.  Your software has likely blocked many attacks that you weren't even aware of.  And anyway, "it hasn't happened yet" is never a good argument against precautionary measures.

One thing I would suggest is tweaking the settings of your anti-virus software.  You can probably disable some of the features to arrive at an acceptable compromise between performance and security.  Most of the major problems that you describe come from real-time file scanning. I do not think you really need this (as long as you're not doing anything stupid), and if you turn it off, you will probably find that 90% of the annoyance goes away.

Title: Looking for meaningful, strong argument in favor of antivirus software on development machines

Body:
When forming opinions, it is a good practice to follow scholastic tradition - think as hard as you can against the opinion you hold and try to find counter-arguments.

However, no matter how hard I try, I just cannot find reasonable arguments in favor of antivirus (and related security measures) on development machines.

Arguments against antivirus(AV) in development are plentiful:

It is not uncommon for 1 minute build to take 10 times longer with AV on

In a conference talk, IntelliJ developers claim AV software is #1 suspect when their IDE is sluggish

Unzipping comes with roughly 100 kb/s speed with AV on

AV renders Cygwin completely unusable (vim takes 1 minute to open a simple file)

AV blocks me from downloading useful files (JARs, DLLs) from colleagues' e-mails

I can't use multiple computers for development, since AV / security measures prevent me from unblocking ports

AV kills performance of programs with high file turnover, such as Maven or Ant

Last, but not least - what does AV actually protect me from? I am not aware of my AV program ever stopping any security thread.

If the reason is fear of disclosing NDA stuff - no AV can possibly prevent me from doing it if I set my mind to it.

If the reason is fear of losing source code and/or documentation - there are distributed revision systems for this (there are at least 20 copies of our repo and we sync on daily basis).

If the reason if fear of disclosing customer data - developers rarely work connected to real production databases, instead they are playing around in toy environments.

Even if there are meaningful arguments in favor of having AV on development machines, they fall apart when faced with the ability to run a Virtual Machine in your paranoidly protected environment.

Since I want to keep an open mind of the issue, could anyone present meaningful, strong argument in favor of Anti-virus software for developers?


答:
There are many reasons to use an anti-virus. However, personally, I don't feel the trade offs are worth it. You can protect yourself by just being smart about using computers:

When something asks for administrative permissions, why is it doing that. What does it need those for?

Ensure your machine receives automatic updates

Disable dangerous and unneeded things from automatically running in your browser (Flash, Java, Silverlight)

Checked msconfig every once in a while. Is a strange program running at start up? Time to do a (one-time) scan and ensure it's not anything bad

Use a VM for development. This has a speed penalty, but last time Windows 8 died on my VM, all I had to do was revert to a snapshot from a week back and do a git pull. Much easier to do this than to keep snapshots of physical machines, especially with changing hardware

I've never seen an antivirus that didn't significantly impact system performance. I've switched to Linux and/or OpenBSD in 2008, where I still watch what programs I run, but it's much easier there than Windows to know what a program will do (primarily due to most things being open source).

Anyway, since I've switched, I now run Windows in a VM and Linux on the physical machine almost exclusively, including at my (Microsoft shop) workplace. I've never installed an antivirus on a VM. I don't really browse the web or anything on the VM for obvious reasons, so I don't worry much about my bank account info going anywhere. The worst thing they could get is some proprietary info or my password. I use random passwords, so that's pretty pointless. And if the virus is to get proprietary info (say proprietary source code), then it's probably so targeted and custom that no antivirus will detect it anyway.

Edit:

Actually, I do run one AV program on my VM. I use Windows Defender, but that's basically because it's on by default, and so lightly intrusive that I've never noticed it running


答:
The one reason to use anti-virus software on development machines that trumps all your arguments is:

To comply with security audits.

Banks, government agencies, large regulated firms with sensitive data don't have a choice on this matter.


答:
Really, there is absolutely no reason to exempt developers from having anti-virus software on their machines. And overwhelmingly many reasons to require it.

Most of the disadvantages you mention can be addressed by telling the anti-virus software that your development folder (the one tied to your code repository) is a trusted location. After we had done that (and made IT postpone the daily scan for us to some time point in the evening as most developers leave their machines on anyway), we no longer had any issues with anti-virus software on our machines.

As for the download of files from e-mails: just tell your friends to use a different extension. Not a known one - anti-virus software is clever enough to check that it is or isn't what it purports to be, a made-up one. Update: Please note that this is a way to get around most e-mail clients' rather dumb rules regarding attachments. Most anti-virus software isn't fooled by the extension change and even if it is, the anti-virus will kick when you come to re-rename the extension to actually use it.

And for the port issue: that is about the only thing in which the policies of the anti-virus software may need to be different for developers, but honestly, we have to and can unblock our server instances all we like, we can still not accept connections from outside our local network. And security wise, that is how it should be. And we are working with a remote team. They use a VPN (Virtual Private Network) so are "within" the local network as far as the anti-virus software is concerned.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
My feeling is no.

What I suspect you'd find if you did this is that instead of having individual teams producing libraries that no-one outside that team used, you'd have a specialised team producing libraries that no-one outside the team used (and doing so at considerable additional cost).

There are assorted problems with the sort of team you describe, but for me the main on is that it doesn't address the issue you actually have.

The problem you have is not who produces the libraries (by the sounds of things you already have many solutions to these problems so how is one more going to help?), it's that the teams aren't talking and interacting.

There are good reasons why teams don't reuse each others code (for instance that the problems while superficially similar are subtly different, or that the project timing just doesn't allow for the additional dependency of developing something together), but you need to look at how you can get them to interact when it is possible.

I'd suggest:

rotate teams between projects

hold inter team lunches and discussion groups

post project reviews going over how problems were solved (attended by the other teams)

set up an area of the wiki outlining code which might be reusable (and who to talk to about it)

think about incentivising good re-use - seriously actually pay people extra for doing it.  If re-using a component saves 5 days and $2000 in costs, why not give $200 of what is now extra profit to the team for a night out at the end of the project (when you've validated the saving was genuine)

A libraries team would be, I suspect, overhead with no benefit.

In terms of it being a common project that developers work on for fun - no company should rely on programmers working on things in their own time.  That's just unpaid overtime and is, in any case, not dependable as there will likely be large periods where no-one wants to work on things.

If you're saying it would be people working in company time between projects then maybe it can work but I still don't think it's the real problem.  You still need to work out how you're going to get people to use the libraries.  As I said, you already have solutions to these problems which are being developed on each project, your issue is why aren't they being shared.


答:
You are forgetting two things.

First, encapsulation is first and foremost about keeping the amount of coupling between your modules low in a structured way, i.o.w., keeping your code modular. Proper encapsulation separates interfaces from implementations, and being able to change internal workings without touching the interface goes much further than simple getters/setters, and covers more than just return types. Take, for example, a rectangle. There are two possible representations: (left, top, right, bottom), or (left, top, width, height). Neither is better, but either may be more suitable for certain situations. If you make getters/setters for all six properties (left, right, top, bottom, width, height), you can change the internal representation in 5 minutes, without touching any other code.

A more important reason, though, is that encapsulation limits the scope of fields and methods. This means that when you want to change a private field, you only have to take its containing class into account; if it's public, you have to check the entire codebase for possible regressions. By extension, reasoning about properly encapsulated code is easier than code where everything is openly accessible from anywhere.

Title: Is it useful to use encapsulation in dynamic typed, interpreted programming language?

Body:
For what I know, encapsulation is useful because:

if you use directly an attribute and change its type in a static typed language you have to change all the code that uses the class. On the contrary, if you have declared getters and setters for that attribute you have not to do this

it hides the internal functioning of your class, useful if, for example, you're offering an API

it avoids that another class that inherits your class will overwrite attributes or methods

My considerations about dynamic typed, interpreted programming language are:

since the types are dynamic there's no need to encapsulate your class for this reason

you can see the code of an interpreted language, so I think there's not a way to really hide your API

this could be a problem when this is unintended, but my opinion is that it should be better to make attention to unintended overwriting instead of limiting by default this possibility. Python is a good example: if you declare for example, the name of an attribute or method starting it with a double underscore, you can declare it also in a inherited class, but they are threated as two distinct variables even if they have the same name (thank you delnan)

<s>a method name that starts with a "_" character raises a warning if overwritten by a method of an inheriting class.</s>

Am I missing something important?


问:
Is it bad practice to have FooObject and FooObjectSummary?
I have a service where users can upload/download/replace/delete files. These files have about a dozen attributes that are saved to a SQL Database. Periodicaly throughout their session they will have to download a summary (FileName, size0in-KB, and ID) of a subset of files.

When working in the service it creates an object of these attributes (FooObject) in the DB. But, when the info is sent to the User, a summary object (FooObjectSummary) is created. FooObjectSummary has 3 attributes, FooObject has 12 or so (none of the attributes are anything but strings or primitive types).

I originaliy did this so that as little extra info would be transferred across. None of this extra data in FooObject would be dangerous for the user to have, but it wouldn't be exposed to them anyways?

Am I just writing extra code? Or is it good practice to only expose the user to as much info as they need and not a bit more?

答:
As with all things, it depends.

The Interface Segregation Principle indicates you should probably have the two views into the data so that you're not breaking consumers if one of the non-vital properties is changed.

In general, you shouldn't share the interface that you use to get at the database with consumers. What happens when you want to change how the data is stored, but keep the consumer interface the same? Though not obvious the gist of the Single Responsibility Principle applies here too.

All that said, if that interface really is going to be the same (if you change either the consumer interface or the SQL interface both are going to need to change regardless [your service is just a pass-thru]) and the extra data really isn't big or important then saving the time and complexity might be best.

You'll need to weigh the time saved versus the likelihood that violating the two principles will bite you in the ass later on.


答:
I can see why you've gone down the path you have and understand your reasons for doing it. After all why go and get twelve properties when you're only going to use three. Why send an object with twelve properties when you are only going to display three. It just feels tidier to do it the way you have.

I'm not going to say you are right or wrong. All I'd say is that if more and more properties start being added to FooObjectSummary then it starts to look like needless duplication. Right now I'd say it's something to be aware of, but I'm sure you've got other more pressing issues.

It'll be interesting to know what others think though.

Title: Is it bad practice to have FooObject and FooObjectSummary?

Body:
I have a service where users can upload/download/replace/delete files. These files have about a dozen attributes that are saved to a SQL Database. Periodicaly throughout their session they will have to download a summary (FileName, size0in-KB, and ID) of a subset of files.

When working in the service it creates an object of these attributes (FooObject) in the DB. But, when the info is sent to the User, a summary object (FooObjectSummary) is created. FooObjectSummary has 3 attributes, FooObject has 12 or so (none of the attributes are anything but strings or primitive types).

I originaliy did this so that as little extra info would be transferred across. None of this extra data in FooObject would be dangerous for the user to have, but it wouldn't be exposed to them anyways?

Am I just writing extra code? Or is it good practice to only expose the user to as much info as they need and not a bit more?


答:
Don't Confuse Server Interfaces With Inner Interfaces

The client interacts with the server and exchanges data based upon the published interface for that server. What the server does to create that data doesn't matter to the client, and the server should not send unwanted or useless data that only pertains to the server.

While the server maintains an inner object called FooObject and sends a FooObjectSummary. The two really are not the same thing. One is an inner data model that relates to database storage, and the other is a communications response to be sent to the client.

If you alter your class names, then things start to become more clear. FooObject is renamed to FooModel and FooObjectSummary is renamed to FooResponse. Now you centralize your code so that only FooModel is used to create a FooResponse.

```<code> class FooModel
 {
      public FooResponse getResponse() {....}
 }
</code>```

You can now document that the server will only send response objects for requesting data.

Body:
Don't Confuse Server Interfaces With Inner Interfaces

The client interacts with the server and exchanges data based upon the published interface for that server. What the server does to create that data doesn't matter to the client, and the server should not send unwanted or useless data that only pertains to the server.

While the server maintains an inner object called FooObject and sends a FooObjectSummary. The two really are not the same thing. One is an inner data model that relates to database storage, and the other is a communications response to be sent to the client.

If you alter your class names, then things start to become more clear. FooObject is renamed to FooModel and FooObjectSummary is renamed to FooResponse. Now you centralize your code so that only FooModel is used to create a FooResponse.

 class FooModel
 {
      public FooResponse getResponse() {....}
 }

You can now document that the server will only send response objects for requesting data.


问:
How do I make an estimate for my first website?
Technically not my first, but my new client wants to enter into negotiations regarding the cost of a website.

It's fairly straight-forward, it's a little bit more than a portfolio page, and I should be able to finish it without much complications.

However, I don't know how to make an estimate to enter negotiations. One that will not scare the client away, and will ensure that I'm making the best out of it as well.

答:
Charge by the hour.  Seriously.  You're new, it's a new-to-you client, and you don't have a large portfolio to ensure this task is "just like the other 100 you've done recently".

If you absolutely must offer up a fixed-price bid, make your best estimate of how many hours it will take, multiply that by the hourly rate you need, then add at least 30% to cover all the unexpected issues that will inevitably arise.*

If the bid is too high for the client, then the fix is to find another client - DON'T lower your bid unless you like making less per hour than your neighbor's babysitter.

Flat rate bids are for repetitive work - crank out a web site that's identical (except for font & color) to many others you've done.

Since it is necessary to negotiate, it's obvious this is not simple repetitive work.

@Michael's answer includes some excellent points about estimating - keep breaking up tasks into smaller sub tasks until no single task is more than xx hours long.  I like to aim for 8, but sometimes miss.


答:
In scenarios like this, I usually find it most helpful to take the project (e.g. website that functions as a portfolio page) and break it down into individual tasks.

For example:

Front-end display

Database schema

Backend:

User management

Portfolio management

Testing

Bugfixing

Once the list is complete, I usually assign hour estimates to each. Borrowing from Joel Spolsky (http://www.joelonsoftware.com/articles/fog0000000245.html) and planning poker (http://www.planningpoker.com/), I try to keep these short. My rule of thumb, doubtless lifted from somewhere, is to keep all estimates below 32 hours and try to shoot for below 12. Anything larger needs to be broken up. I am firmly of the opinion that no one actually has any clue how long something estimated at over 40 hours will take.

Once you have done this, take your hour counts, sum them up and add some buffering. 10-20% usually seems pretty good. Also notice that testing and bugfixing are explicitly listed as tasks. I haven't always remembered to do it myself, but it is vital that they be included in estimates. You will wind up doing these things so include them in your estimates.

It is entirely possible that the resulting number will scare your client. Most clients have a poor intuition for how much work goes into development. What you do with this is up to you. I would remark that in my own experiences, failing to land a contract was not the worst thing to happen to me. Landing a contract that was not sustainable was. It created extra work, stress and a shortage of cash (even if only relative to the trouble).

Title: How do I make an estimate for my first website?

Body:
Technically not my first, but my new client wants to enter into negotiations regarding the cost of a website.

It's fairly straight-forward, it's a little bit more than a portfolio page, and I should be able to finish it without much complications.

However, I don't know how to make an estimate to enter negotiations. One that will not scare the client away, and will ensure that I'm making the best out of it as well.


答:
Since I want to keep an open mind of the issue, could anyone present
  meaningful, strong argument in favor of Anti-virus software for
  developers, please?

I suspect most people who visit this forum are smart enough not not to download or visit dangerous internet sites, so they view AV as an annoyance or not needed.

But, really you need AV software.  Not for you, but for the poor sap (computer neophyte) who clicks on "Click here to see cute kittens" link in an email and the last thing they see are hundreds of pop ups with cute little kittens saying "all your bases belong to us" as there machine is infected by malware.

Then the malware spreads across your network and then next thing you see is your processor running at 100% and nothing is working.

Unless you developing in a bubble, I want protection.  I can cite that once I worked for company who decided they didn't need AV and for a time it was OK, until everyone's machine got infected.  Well machines got reformatted and a lot of time was lost.   Then everyone got AV and a company notice to not disable or un-install AV.

As others have suggested, you can tweak the AV so it will have less impact on your daily efforts.

You can walk the tightrope without a net, but really I prefer having a the net, even if I never need it.


问:
Applying commits into another branch without merging
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

I need to maintain these changes because I need them to run the software on different computers. So there is no master and development branch, both are equally important.

Nevertheless, I need to "synchronize" the core code base of the branches. So I would like to somehow apply the commits from one branch in a sort of patch fashion to the other branch and vice versa, without merging them, in order to maintain the different setups.

Is this possible with git?
If yes, how can I accomplish this?

Edit: can I merge only some files and leaves others out, but maintain the two branches?

答:
I don't think the question makes sense.

In git, every repository is essentially a branch. There is no form of code inclusion that is not merging. You either need to synchronize them and in the process, manually perform the merge, or you need to let the software do the merge itself.


答: This sounds like a task for a build system, not a version control system.</p>

Title: Applying commits into another branch without merging

Body:
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

I need to maintain these changes because I need them to run the software on different computers. So there is no master and development branch, both are equally important.

Nevertheless, I need to "synchronize" the core code base of the branches. So I would like to somehow apply the commits from one branch in a sort of patch fashion to the other branch and vice versa, without merging them, in order to maintain the different setups.

Is this possible with git?
If yes, how can I accomplish this?

Edit: can I merge only some files and leaves others out, but maintain the two branches?


答:
You should be able to do this using patches.  Take a look at this post:

How to create and apply patches

and this SO question:

Generate a patch for a specific commit

Googling for git patches also provides plenty of information.


问:
Somewhere to put miscellaneous files
We want to be able to offer users of our software the facility of having a miscellaneous folder for each of their clients.

All these client folders would be stored together in another folder called 'miscellaneous data' for example

It would be accessible via an icon in the client record window in our software and would be a place to just drop files that aren't catered for by us.

A really simple solution is just to do a Shell call to explorer.exe with the folder address.

All the files would have the correct icons and look familiar and the user would be able to open them with their default programs

The problem with this is that this then allows the user to use file explorer to navigate up to the 'miscellaneous data' folder  and possibly do something unintentional like delete a bunch of client folders.

I'd be very grateful for suggestions for a simple but more secure design

答:
The problem with this is that this then allows the user to use file explorer to navigate up to the 'miscellaneous data' folder and possibly do something unintentional like delete a bunch of client folders.

That's what happens.  Your user's hard drive could also crash, or they could open up %ProgramFiles% or %SystemRoot%and just start deleting.

If a hidden folder in %AppData% doesn't fit your needs, consider storing the information in a local SQL Server database, an application-managed file archive (Zip or Cap or whatnot), or some other container that sits as a single file on the drive.

If you really want it to be user-proof, you'll need something running with a distinct user account that writes to a folder accessible only to that account.  A background service would be appropriate.  (And, honestly, this is what you'd be doing with SQL Server.)

Title: Somewhere to put miscellaneous files


答:
I've never understood the appeal of AMD loaders for the client-side web in general, although they did make some sense for mobile at one point because resource files didn't cache on Android and parsing performance wasn't great.

If you attach script files in 3 categories in the following order,

General 3rd party libraries

App-specific in-house libraries that reference the 3rd party libraries

Implementation code that can reference both

... where's the problem? Scripts that aren't used on a page aren't ever more than a one-time loading performance hit because they're cached. If juggling dependencies within those categories just by appending script tags in the right order has become an exceedingly difficult task, I'd call that an architecture/file-management issue that shouldn't be hard to handle with a little clean-up/consolidation.

If two functions or constructors share a dependency, it usually makes sense to have everybody in the same file and that shouldn't be hard when you've separated the code that implements, from things that are used by implementation, from 3rd party things that can be used anywhere. Within a given category don't split things into separate files if they share a common problem domain. And of course combine/minify in production.

If all you're using JS for is client-side templating, I would not expect anyone would want to use AMD. As a general rule, don't use anything that doesn't provide an obvious/immediate benefit. It's easier to add later than it is to take away.


答:
Can you have three branches instead of two?

branch work, with all platform-independent code, which is 99% in your case;

branch platform-A with code specific to platform A;

branch platform-B with code specific to platform B.

Your main work happens on work branch. You periodically merge changes from it into platform-A and platform-B, tweaking platform-specific aspects if needed.

This way, things specific to platform A never unintentionally seep into platform B code, and vice versa. You can also easily keep the bulk of your tests platform-agnostic.


答:
This can be done with the git cherry-pick command, but that's really intended to be used sparingly.  Making it a regular part of your process is going to eventually get painful.

A slightly better option is to create a master branch with all the common code, then have each configuration's custom changes done in their own branches.  That lets you merge from master down to the individual configuration branches.

However, the best option is to refactor your code so you can just use a build flag or a config file to switch between the different configurations.  Keeping two configurations in separate branches is reasonable, but as your needs grow, it will become unwieldy very quickly.  It's better to bite the bullet now when it's easier to refactor.


问:
How do you tell if advice from a senior developer is bad?
Recently, I started my first job as a junior developer and I have a more senior developer in charge of mentoring me in this small company. However, there are several times when he would give me advice on things that I just couldn't agree with (it goes against what I learned in several good books on the topic written by the experts, questions I asked on some Q&A sites also agree with me) and given our busy schedule, we probably have no time for long debates.

So far, I have been trying to avoid the issue by listening to him, raising a counterpoint based on what I've learned as current good practices. He raises his original point again (most of the time he will say best practice, more maintainable but just didn't go further), I take a note (since he didn't raise a new point to counter my counterpoint), think about it and research at home, but don't make any changes (I'm still not convinced). But recently, he approached me yet again, saw my code and asked me why haven't I changed it to his suggestion. This is the 3rd time in 2--3 weeks.

As a junior developer, I know that I should respect him, but at the same time I just can't agree with some of his advice. Yet I'm being pressured to make changes that I think will make the project worse. Of course as an inexperienced developer, I could be wrong and his way might be better, it may be 1 of those exception cases.

My question is: what can I do to better judge if a senior developer's advice is good, bad or maybe it's good, but outdated in today context? And if it is bad/outdated, what tactics can I use to not implement it his way despite his 'pressures' while maintaining the fact that I respect him as a senior?

答: It's okay to question things while doing them exactly as asked. A good senior person might not always be able to convince you of the rightness of doing things before they need to be done, for business reasons or even just for task-dependency reasons; but should take time to acknowledge your concern, admit when they have failed to address it, and touch on it at another time.</p>


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答: The Groovy language does exactly this, getters and setters are generated on the fly. But I must admit that too much magic always makes me wonder what the program really does, since there are too many things to keep in mind that happen behind the curtain. Explicit getters and setters, as generated by the IDE, make it a bit easier to follow the flow of the program.</p>

Title: IDE Generated Code


答:
At my last job, I worked alongside another developer who'd only been there for a months more than me. He had some existing experience at other companies working on similar systems. He was very calm and level headed. Still, he gave me the impression that wasn't a native software developer. By "native", I mean he just sort of fell into a developer position gradually over time. You could tell that he was well read in some areas, but lacked some fundamentals. It was clear that he struggled on some seemingly simple problems. He could get the software to do what he wanted, but he just didn't "get it".

Personally, I could never get over the "my way is better because I read it in a book" mentality, which was something I openly admitted when I worked there. In many ways, my previous experience made me a bad fit for the position. I'm not sure if it was because I was "too advanced" or just on a different path.

He and I continually argued about how to do unit testing. He believed in a very white box approach, via monkey patching. I prefer black box testing supported with mocks and dependency injection. I thought his approach led to fragile tests, but I'm sure some of my opinions were swayed by my background in C#. He had always worked in Python. Who was right? Both of us? Neither of us?

Companies should be more careful when promoting developers to senior status. It is very difficult to gain enough experience at one job. A good senior developer has to know about what tools are available and how other shops handle similar problems. It wasn't until I left my first job (where I was a senior developer) that I learned how to build modern websites, properly do continuous deployment, manage source control branches, build distributed services or use NoSQL databases. You need to learn new philosophies, technologies and processes to really be a senior developer.

Ultimately, the six months he'd been there longer than me gave him the advantage. I always bent to his will and did testing his way. That's what professionals do. I was there to learn. Still, as with most not-quite-developers, he wormed his way into a management position. In less than 3 weeks, we had a meeting and I walked out with a cardboard box. Now I am glad that I was fired because that place was boring me to tears.

It wasn't an environment of self-improvement. Unfortunately, policies intended to help, start to harm productivity when followed too strictly. I'd sit there for hours waiting for others to review my code, only to get comments back about line spacing and naming conventions. When I started making suggestions contrary to policy... I suddenly became labeled a rebel, a naysayer and an instigator.

Title: How do you tell if advice from a senior developer is bad?

Body:
Recently, I started my first job as a junior developer and I have a more senior developer in charge of mentoring me in this small company. However, there are several times when he would give me advice on things that I just couldn't agree with (it goes against what I learned in several good books on the topic written by the experts, questions I asked on some Q&A sites also agree with me) and given our busy schedule, we probably have no time for long debates.

So far, I have been trying to avoid the issue by listening to him, raising a counterpoint based on what I've learned as current good practices. He raises his original point again (most of the time he will say best practice, more maintainable but just didn't go further), I take a note (since he didn't raise a new point to counter my counterpoint), think about it and research at home, but don't make any changes (I'm still not convinced). But recently, he approached me yet again, saw my code and asked me why haven't I changed it to his suggestion. This is the 3rd time in 2--3 weeks.

As a junior developer, I know that I should respect him, but at the same time I just can't agree with some of his advice. Yet I'm being pressured to make changes that I think will make the project worse. Of course as an inexperienced developer, I could be wrong and his way might be better, it may be 1 of those exception cases.

My question is: what can I do to better judge if a senior developer's advice is good, bad or maybe it's good, but outdated in today context? And if it is bad/outdated, what tactics can I use to not implement it his way despite his 'pressures' while maintaining the fact that I respect him as a senior?


问:
How do you decide what code to put into a function?
I started out with a script that was a few hundred lines. Later, I realized I wanted another script that would require much of the same code. I decided to wrap certain areas of the original script that would be shared, into definitions. When I was deciding exactly what should be in a function, I came across various things to consider:

What should I set as its input parameters? If anything was needed in the function, I should probably require it as a parameter, right? Or should I declare it within the function itself?

If function x always requires the output of function y, but function y sometimes is needed alone, should function X include the code of function y or simply call function y?

Imagine a case where I have 5 functions that all call a function 'sub' (sub is essential for these 5 functions to complete their work). If 'sub' always is supposed to return the same result, then wouldn't multiple calls from these parent functions duplicate the same work? If I move the call to 'sub' outside of the 5 functions, how can I be sure that 'sub' is called before the first call to any of the 5 functions?

If I have a segment of code that always produces the same result, and isn't required more than once in the same application, I normally wouldn't put it in a function. However, if it is not a function, but is later required in another application, then should it become a function?

Sorry if these questions are too vague, but I feel there should be some general guidelines. I haven't programmed for very long, and bounced around between OOP and functional, but I've never remembered reading anything that explained this. Could it simply be a matter of personal preference?

答:
There are no recipes for logic, but I will answer your specific questions:

Q: What should I set as its input parameters?

A: the things needed to do the calculation

Q: If anything was needed in the function, I should probably require it as a parameter, right?

A: yes, or you can get it from a file or database

Q: If function x always requires the output of function y, but function y sometimes is needed alone, should function X include the code of function y or simply call function y?

A: simply call y

Q: Imagine a case where I have 5 functions that all call a function 'sub' (sub is essential for these 5 functions to complete their work). If 'sub' always is supposed to return the same result, then wouldn't multiple calls from these parent functions duplicate the same work?

A: if sub always returns the same result, then no work is beeing done.

Q: If I move 'sub' outside the 5 functions, how can I be sure that 'sub' is called before the first call to any of the 5 functions?

A: wasn't sub already outside the 5 functions ?... Do not call sub from within any of those functions. Call it in the parent program before calling the 5 functions.

Q: If I have a segment of code that always produces the same result, and isn't required more than once in the same application, I normally wouldn't put it in a function. However, if it is not a function, but is later required in another application, then should it become a function?

A:If it is complex enough. Put it into a function. If other app needs it, share the library.


答:
In Clean Code, Robert Martin argues that fewer parameters are better. Consider whether something should be an instance variable instead of a parameter. Also, see Preserve Whole Object in Refactoring by Martin Fowler.

Call function y. Don't Repeat Yourself (DRY) as recommended in Pragmatic Programmer (Hunt and Thomas)

I'm not sure what you mean by "always returns the same result". Do you mean that the same result is returned for the same input parameters (deterministic)? Are you asking about lazy loading?

Before I read Clean Code, I was reluctant to create small functions that were used only once. Now I do so frequently. Consider extraction a function if you have a long function with several blocks that represent sub steps in the function. The tell-tale sign is a comment that says something like "Calculates Monthly Sales". You should probably extract the code block into a function called calculateMonthlySales.

Title: How do you decide what code to put into a function?

Body:
I started out with a script that was a few hundred lines. Later, I realized I wanted another script that would require much of the same code. I decided to wrap certain areas of the original script that would be shared, into definitions. When I was deciding exactly what should be in a function, I came across various things to consider:

What should I set as its input parameters? If anything was needed in the function, I should probably require it as a parameter, right? Or should I declare it within the function itself?

If function x always requires the output of function y, but function y sometimes is needed alone, should function X include the code of function y or simply call function y?

Imagine a case where I have 5 functions that all call a function 'sub' (sub is essential for these 5 functions to complete their work). If 'sub' always is supposed to return the same result, then wouldn't multiple calls from these parent functions duplicate the same work? If I move the call to 'sub' outside of the 5 functions, how can I be sure that 'sub' is called before the first call to any of the 5 functions?

If I have a segment of code that always produces the same result, and isn't required more than once in the same application, I normally wouldn't put it in a function. However, if it is not a function, but is later required in another application, then should it become a function?

Sorry if these questions are too vague, but I feel there should be some general guidelines. I haven't programmed for very long, and bounced around between OOP and functional, but I've never remembered reading anything that explained this. Could it simply be a matter of personal preference?


答:
there are 2 ways to pass data into a function: parameters or globals, in small scripts globals are acceptable but really try to avoid them

it's easier to simply extract y this is also better when you need to change y later

you can use lazy initialization here:

```<code>var subresult=undefined

function sub(){
    if(subresult===undefined){
        subresult=//calculate...
    }
    return subresult;
}
</code>```

there are 2 competing principles here SRP and YAGNI:

A. Single Responsibility Principle means essentially that each function should do a single thing and do it correctly

B.  You Aren't Going to Need It: don't waste time on stuff that may or may not be needed in the future, focus on what you need now

Body:
there are 2 ways to pass data into a function: parameters or globals, in small scripts globals are acceptable but really try to avoid them

it's easier to simply extract y this is also better when you need to change y later

you can use lazy initialization here:

var subresult=undefined

function sub(){
    if(subresult===undefined){
        subresult=//calculate...
    }
    return subresult;
}

there are 2 competing principles here SRP and YAGNI:

A. Single Responsibility Principle means essentially that each function should do a single thing and do it correctly

B.  You Aren't Going to Need It: don't waste time on stuff that may or may not be needed in the future, focus on what you need now


答:
Part of how you approach the estimate is knowing how you intend or are expected to stay involved with the effort after the first pass of the work is completed.  What degree of service or support do you intend to provide beyond the initial delivery during the revision or testing phases, and then again in the post-delivery phase?

The estimate for the first pass of the effort is a fixed cost.  This estimate for the first pass is the time it takes to do those discreet, "clearly" defined tasks (scope) negotiated up front (statement of work).  It is something you and only you know how long it might take since you were doing the work.

The subsequent passes will take the form of revisions, refinements, and late additions.  This is where the customer explains that what you did is appreciated and quite nice, but not precisely what they want or need.  This phase is highly variable, and so costing it out should eventually reflect that variability.

These subsequent passes can sparsely demand your time, or remain overwhelming for the near future.  When the demands of a project are sparse, charging on a rate basis (by the hour, by the revision, by the additional feature complexity) makes sense for both parties involved.  You can, without guilt, work on other things that may be more pressing.  You may anticipate a minimum number of hours spent on this phase, and is often safe to do include some fixed period of time and cost for revision and refinement, and then move to a more variable cost after that pool of time initially set aside is exhausted.

Most efforts will involve both the initial cut and the later edits.  The estimate should reflect and note the difference as it is in everyone's best interest.

Example:

Initial Cut: 40 dedicated hours, 25 hours committed per week ~ 8 business days

Expected Revision/Refinement: 15 dedicated hours, 3 hours per day ~ 5 business days

Total Allocated: 55 dedicated hours, 13 business days @ base_rate

Additional Revisions/Refinement: as needed and as available @ base_rate + some premium

Be sure to include some form of a statement of work with the cost figures (even if somewhat vague) so there isn't a big misunderstanding later about what was expected and what was delivered.


答:
You are thinking about functions only to be a container of code beeing reused somewhere. That's not the worst start when learning how to build functions, but it is not necessarily the only approach or the "best" way.

A different point of view is to use functions for creating abstractions. You wrote you have a script with a few 100 lines - fine. Now you have blocks within this script doing a certain subtask. Each of these blocks belongs into a function of its own. The name of the function should be self-explanatory telling you what that subtask is. When you avoid global variables and side-effects, it becomes self-evident what parameters your functions will need and what they must return.

This way, your functions are becoming the building blocks of your application. This is mostly independent of how often they are reused, and independent of how often they are called.

If function x always requires the output of function y, but function y sometimes is needed alone, should function X include the code of function y or simply call function y?

y is a single subtask within x, something which for which you can up easily with a separate name. Hence it should clearly be in its own function - independently of being needed alone or not!

Imagine a case where I have 5 functions that all call a function 'sub'
(sub is essential for these 5 functions to complete their work). If
'sub' always is supposed to return the same result, then wouldn't
multiple calls from these parent functions duplicate the same work? If
I move the call to 'sub' outside of the 5 functions, how can I be sure
that 'sub' is called before the first call to any of the 5 functions?

First, if there is the same thing calculated twice, does that really matter in your case? There is no need to optimize that away as long as you have not a proven performance bottleneck. Second, if your really have a performance bottleneck in such a case, there is the technique of memoization, which will exactly solve this problem.

If I have a segment of code that always produces the same result, and isn't required more than once in the same application, I normally wouldn't put it in a function.

That is exactly what you should do differently - put it into a function, not for the purpose of reuse, but for the purpose of creating an abstraction.

ContentLicense: CC BY-SA 4.0


答:
Don't give a user's clients (a 3rd party) direct access to the user's file system.  Just don't do it, even if the user -thinks- it might be ok.

Give these 3rd party users delegated access.  Let the 3rd party upload files to a file processor with restricted but adequate privileges to read and write from 'safe' location.  The processor might perform some filtering by document type, size, age, and context (if the 3rd party didn't upload it, they can't read it back for example; or if the 3rd party's IP address or subnet mask isn't known and whitelisted; or whatever other protections might be relevant) before allowing the activity.

For the user, they can access the file system normally, or they may have and use a 'safe' interface that provides some auxiliary auditing beyond any OS based auditing.

Title: Somewhere to put miscellaneous files

Body:
We want to be able to offer users of our software the facility of having a miscellaneous folder for each of their clients.

All these client folders would be stored together in another folder called 'miscellaneous data' for example

It would be accessible via an icon in the client record window in our software and would be a place to just drop files that aren't catered for by us.

A really simple solution is just to do a Shell call to explorer.exe with the folder address.

All the files would have the correct icons and look familiar and the user would be able to open them with their default programs

The problem with this is that this then allows the user to use file explorer to navigate up to the 'miscellaneous data' folder  and possibly do something unintentional like delete a bunch of client folders.

I'd be very grateful for suggestions for a simple but more secure design


问:
What license is best for this: Software is open source and free to use as long as you don't charge your customers
I'm releasing an open-source jQuery plug-in that is free to use, modify and redistribute as long as you don't directly or indirectly charge your customers. Your software doesn't need to be open-source, it just need to be free. If you charge your customers, you need a commercial license.

I'm not sure about the licensing. http://www.turnjs.com/ is a plug-in that is similarly licensed and it is Non-comercial BSD license. But I can't find the definition for this license online.

Can anyone help me determining the best license for me based on my description? Thanks.

答:
"Believe it or not", what you're suggesting moves your project out of the open source realm into the non-free realm.  Have a look at this Wikipedia entry on Open Source licenses, and in particular this quote in the 1st paragraph.

Licenses which only permit non-commercial redistribution or modification of the source code for personal use only are generally not considered as open-source licenses.

So with that detail out of the way, the FSF has provided a number of comments on other licenses that may suit your needs.  Have a look at the FSF license list and look for where they discuss commercial aspects.  Some examples would be:

Code Project Open License

Microsoft Shared Source CLI, C#, and Jscript License

Scilab License

Sun Solaris Source Code

University of Utah Public License

Needless to say, FSF does not approve of any of those license since they aren't Free.  But their commentary may guide you to one that works for you.  Code Project and the Microsoft Shared Source appear to be two good bets.


问:
In API design, when to use/avoid ad hoc polymorphism?
Sue is designing a JavaScript library, Magician.js. Its linchpin is a function which pulls a Rabbit out of the argument passed.

She knows its users may want to pull a rabbit out of a String, a Number, a Function, perhaps even a HTMLElement. With that in mind, she could design her API like so:

The strict interface

```<code>Magician.pullRabbitOutOfString = function(str) //...
Magician.pullRabbitOutOfHTMLElement = function(htmlEl) //...
</code>```

Each function in the above example would know how to handle the argument of the type specified in the function name/parameter name.

Or, she could design it like so:

The "ad hoc" interface

```<code>Magician.pullRabbit = function(anything) //...
</code>```

pullRabbit would have to account for the variety of different expected types that the anything argument could be, as well as (of course) an unexpected type:

```<code>Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  }
  // etc.
};
</code>```

The former (strict) seems more explicit, perhaps safer, and perhaps more performant -- as there are little or no overheads for type checking or type conversion. But the latter (ad hoc) feels simpler looking at it from the outside, in that it "just works" with whatever argument the API consumer finds convenient to pass to it.

For the answer to this question, I'd like to see specific pros and cons to either approach (or to a different approach altogether, if neither is ideal), that Sue should know which approach to take when designing her library's API.

答:
This is JavaScript. As you get it better at it you'll find there's often a middle-road that helps negate dilemmas like this. Also, it really doesn't matter whether an unsupported 'type' is caught by something or breaks when somebody tries to use it because there is no compile vs. run-time. If you use it wrong it breaks. Trying to hide that it broke or make it work half-way when it broke doesn't change the fact that something is broken.

So have your cake and eat it too and learn to avoid type confusion and unnecessary breakage by keeping everything really, really obvious, as in well-named and with all the right details in all the right places.

First of all, I highly encourage getting into the habit of getting your ducks in a row before you need to check types. The leanest and most efficient (but not always best where native constructors are concerned) thing to do would be to hit the prototypes first so your method doesn't even have to care about what supported type is in play.

```<code>String.prototype.pullRabbit = function(){
    //do something string-relevant
}

HTMLElement.prototype.pullRabbit = function(){
    //do something HTMLElement-relevant
}

Magician.pullRabbitFrom = function(someThingy){
    return someThingy.pullRabbit();
}
</code>```

Note: It's widely regarded as bad form to do this to Object as everything inherits from Object. I personally would avoid Function too. Some might feel antsy about touching any native constructor's prototype which might not be a bad policy but the example could still serve when working with your own object constructors.

I wouldn't worry about this approach for such a specific-use method that's not likely to clobber something from another library in a less complicated app but it's a good instinct to avoid asserting anything overly generally across native methods in JavaScript if you don't have to unless you're normalizing newer methods in out-of-date browsers.

Fortunately, you can always just pre-map types or constructor names to methods (beware IE<=8 which doesn't have <object>.constructor.name requiring you parse it out of the toString results from the constructor property). You're still in effect checking constructor name (typeof is kind of useless in JS when comparing objects) but at least it reads much nicer than a giant switch statement or if/else chain in every call of the method to what could be a wide variety of objects.

```<code>var rabbitPullMap = {
    String: ( function pullRabbitFromString(){
        //do stuff here
    } ),
    //parens so we can assign named functions if we want for helpful debug
    //yes, I've been inconsistent. It's just a nice unrelated trick
    //when you want a named inline function assignment

    HTMLElement: ( function pullRabitFromHTMLElement(){
        //do stuff here
    } )
}

Magician.pullRabbitFrom = function(someThingy){
    return rabbitPullMap[someThingy.constructor.name]();
}
</code>```

Or using the same map approach, if you wanted access to the 'this' component of the different object types to use them as if they were methods without touching their inherited prototypes:

```<code>var rabbitPullMap = {
    String: ( function(obj){

    //yes the anon wrapping funcs would make more sense in one spot elsewhere.

        return ( function pullRabbitFromString(obj){
            var rabbitReach = this.match(/rabbit/g);
            return rabbitReach.length;
        } ).call(obj);
    } ),

    HTMLElement: ( function(obj){
        return ( function pullRabitFromHTMLElement(obj){
            return this.querySelectorAll('.rabbit').length;
        } ).call(obj);
    } )
}

Magician.pullRabbitFrom = function(someThingy){

    var
        constructorName = someThingy.constructor.name,
        rabbitCnt = rabbitPullMap[constructorName](someThingy);

    console.log(
        [
            'The magician pulls ' + rabbitCnt,
            rabbitCnt === 1 ? 'rabbit' : 'rabbits',
            'out of her ' + constructorName + '.',
            rabbitCnt === 0 ? 'Boo!' : 'Yay!'
        ].join(' ');
    );
}
</code>```

A good general principle in any language IMO, is to try to sort out branching details like this before you get to code that actually pulls the trigger. That way it's easy to see all of the players involved at that top API level for a nice overview, but also much easier to sort out where the details somebody might care about are likely to be found.

Note: this is all untested, because I assume nobody actually has an RL use for it. I'm sure there's typos/bugs.

Body:
This is JavaScript. As you get it better at it you'll find there's often a middle-road that helps negate dilemmas like this. Also, it really doesn't matter whether an unsupported 'type' is caught by something or breaks when somebody tries to use it because there is no compile vs. run-time. If you use it wrong it breaks. Trying to hide that it broke or make it work half-way when it broke doesn't change the fact that something is broken.

So have your cake and eat it too and learn to avoid type confusion and unnecessary breakage by keeping everything really, really obvious, as in well-named and with all the right details in all the right places.

First of all, I highly encourage getting into the habit of getting your ducks in a row before you need to check types. The leanest and most efficient (but not always best where native constructors are concerned) thing to do would be to hit the prototypes first so your method doesn't even have to care about what supported type is in play.

String.prototype.pullRabbit = function(){
    //do something string-relevant
}

HTMLElement.prototype.pullRabbit = function(){
    //do something HTMLElement-relevant
}

Magician.pullRabbitFrom = function(someThingy){
    return someThingy.pullRabbit();
}

Note: It's widely regarded as bad form to do this to Object as everything inherits from Object. I personally would avoid Function too. Some might feel antsy about touching any native constructor's prototype which might not be a bad policy but the example could still serve when working with your own object constructors.

I wouldn't worry about this approach for such a specific-use method that's not likely to clobber something from another library in a less complicated app but it's a good instinct to avoid asserting anything overly generally across native methods in JavaScript if you don't have to unless you're normalizing newer methods in out-of-date browsers.

Fortunately, you can always just pre-map types or constructor names to methods (beware IE<=8 which doesn't have <object>.constructor.name requiring you parse it out of the toString results from the constructor property). You're still in effect checking constructor name (typeof is kind of useless in JS when comparing objects) but at least it reads much nicer than a giant switch statement or if/else chain in every call of the method to what could be a wide variety of objects.

var rabbitPullMap = {
    String: ( function pullRabbitFromString(){
        //do stuff here
    } ),
    //parens so we can assign named functions if we want for helpful debug
    //yes, I've been inconsistent. It's just a nice unrelated trick
    //when you want a named inline function assignment

    HTMLElement: ( function pullRabitFromHTMLElement(){
        //do stuff here
    } )
}

Magician.pullRabbitFrom = function(someThingy){
    return rabbitPullMap[someThingy.constructor.name]();
}

Or using the same map approach, if you wanted access to the 'this' component of the different object types to use them as if they were methods without touching their inherited prototypes:

var rabbitPullMap = {
    String: ( function(obj){

    //yes the anon wrapping funcs would make more sense in one spot elsewhere.

        return ( function pullRabbitFromString(obj){
            var rabbitReach = this.match(/rabbit/g);
            return rabbitReach.length;
        } ).call(obj);
    } ),

    HTMLElement: ( function(obj){
        return ( function pullRabitFromHTMLElement(obj){
            return this.querySelectorAll('.rabbit').length;
        } ).call(obj);
    } )
}

Magician.pullRabbitFrom = function(someThingy){

    var
        constructorName = someThingy.constructor.name,
        rabbitCnt = rabbitPullMap[constructorName](someThingy);

    console.log(
        [
            'The magician pulls ' + rabbitCnt,
            rabbitCnt === 1 ? 'rabbit' : 'rabbits',
            'out of her ' + constructorName + '.',
            rabbitCnt === 0 ? 'Boo!' : 'Yay!'
        ].join(' ');
    );
}

A good general principle in any language IMO, is to try to sort out branching details like this before you get to code that actually pulls the trigger. That way it's easy to see all of the players involved at that top API level for a nice overview, but also much easier to sort out where the details somebody might care about are likely to be found.

Note: this is all untested, because I assume nobody actually has an RL use for it. I'm sure there's typos/bugs.


问:
Writing Testable Code vs Avoiding Speculative Generality
I was reading some blog posts this morning, and stumbled across this one:

If the only class that ever implements the Customer interface is
  CustomerImpl, you don't really have polymorphism and substitutability
  because there is nothing in practice to substitute at runtime. It's
  fake generality.

That makes sense to me, as implementing an interface adds complexity and, if there is only ever one implementation, one might argue that it adds needless complexity.  Writing code that is more abstract than it needs to be is often considered to be code smell called "speculative generality" (also mentioned in the post).

But, if I'm following TDD, I can't (easily) create test doubles without that speculative generality, whether in the form of interface implementation or our other polymorphic option, making the class inheritable and its methods virtual.

So, how do we reconcile this tradeoff?  Is it worth it to be speculatively general to facilitate testing/TDD?  If you're using test doubles, do these count as second implementations and thus make the generality no longer speculative?  Should you consider a more heavyweight mocking framework that allows mocking of concrete collaborators (e.g. Moles versus Moq in the C# world)?  Or, should you test with the concrete classes and write what could be considered "integration" tests until such time as your design naturally requires polymorphism?

I'm curious to read other people's takes on this matter -- thanks in advance for your opinions.

答:
I'll answer in two parts:

You don't need interfaces if you're only are interested in testing. I use mocking frameworks for that purpose (in Java: Mockito or easymock). I believe that the code you design should not be modified for testing purposes. Writing testable code, is equivalent of writing modular code, so I do tend to write modular (testable) code and test only the code public interfaces.

I've been working in a big Java project and I'm becoming deeply convinced that using read-only (only getters) interfaces is the way to go (please note that I'm a big fan of immutability). The implementing class may have setters, but that's an implementation detail that should not be exposed to outer layers. From another perspective I do prefer composition over inheritance (modularity, remember?), so interfaces also help here. I'm willing to pay the cost of speculative generallity than shooting my self in the foot.


问:
Formal definition of "concepts / type system" for parametric types - Where to start?
I would be interested in formally defining (and consequently demonstrating) a "type system" for, well, a type system. More specifically, I would like to explore the idea of what C++ calls concepts for my bachelor's thesis. How would one go about defining such system  (formally) ? It's basically a meta-language for generic programming I suppose, but all the material I've found so far is basically bound to syntax of a specific programming language.

The basic idea is to provide an interface for parametric types.

For example:

An argument for the function foo(T) is some (unfortunately any) T. (This type is known statically.) And, I would like to define an interface for such type, so that this T is actually not any T, but some type that complies to an interface, such as: "In order for this type to be legal for the function foo, it needs to comply to: This and that concept / interface to statically check against."

Concepts would define related, meaningful "interfaces" that would constrain the type T. Currently, the language C++ doesn't do any such checks, it simply tries to do whatever it is that foo(T) does on any type and hopes it works. If it doesn't the error message is of length of a decent novel, as the error is detected too late and the compiler needs to "spit out" the entire process of how it got to an error.

I would eventually like to show the concept (errm, idea, sorry for the ambiguity) on the C++ specifically, if that's any relevant.

Thanks,

~Scarlet

答:
These are known as Kinds or Type Classes (in some areas, not others) or a few other things. They are defined formally as any other function, except the Type Constructors (another searchable term for parameterized types) use kinds as their signature rather than first level types.

These have been formally defined in the past and proper academic research should provide tons of papers on the subject. Lambda the Ultimate should also have resources to help.

The results will largely be bound to a specific language, since they are very language specific. C++'s implementation specifically precludes such things, so you would need to extend/change the language - probably in ways that other languages have already done.


问:
Is user story the best form of requirement in agile project?
Statistically speaking, user story maybe the most popular requirement technique in Agile but I am curious to know the alternatives and why.</p>

答:
As far as I know, there are no alternatives to user stories, intended in their original meaning of "placeholders for conversations that we need to have".

Stories cannot be more than placeholders because

The most efficient and effective method of
  conveying information to and within a development
  team is face-to-face conversation.

is one of the 12 core concepts in agile.

On the other hand, you might be referring to the: "As a XXX, I want to YYY, so that ZZZ" format. In that case, there are infinite alternatives, because that format is just a simple way of putting a little formality on something that is essentially informal.

The three parts of "story form" are three very important pieces of information that are useful to remember at all times (who benefits, what's the final objective, the value), nothing more.

In fact, Mike Cohn suggests that the "value" is optional.

In my user stories book and in all my training and conference sessions on user stories I advocate writing user stories in the form of: “As a , I want  so that .” While I consider the so-that clause optional, I really like this template.

--http://www.mountaingoatsoftware.com/blog/advantages-of-the-as-a-user-i-want-user-story-template

Others like suggest the exact opposite, and put the value first: "In order to achieve ZZZ as a XXX, I want YYYY".

Elizabeth Keogh suggests that business value is more important than user role and presents a revised template for writing user stories, which she credits to Chris Matts. The traditional format emphasizes the importance of the user, mentioning them first. The newly proposed variation switches the emphasis to the business value

-- http://www.infoq.com/news/2008/06/new-user-story-format

In XP, extreme programming:

User Stories are written by the customers as things that the system needs to do for them. They are similar to usage scenarios, except that they are not limited to describing a user interface. They are in the format of about three sentences of text written by the customer in the customers terminology without techno-syntax.

--http://www.extremeprogramming.org/rules/userstories.html

So they are free form.

In general, there is no predefined concept and whatever works for the current team is fine.


答:
That is the job of an architect.

The main responsibilities of a software architect include:

Limiting the choices available during development by choosing a standard way of pursuing application development

creating, defining, or choosing an application framework for the application

Recognizing potential reuse in the organization or in the application by Observing and understanding the broader system environment

Creating the component design
Having knowledge of other applications in the organization

Read more about:
- Software architect
- Solutions Architect
- Enterprise architect.

Title: Should a software company have a dedicated team for research and/or utility libraries?

Body:
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.


问:
Verification for value of test standards
We are currently developing a concept for our tests standards. Up until now, we don't have standards. All we do is to tell the developer to write tests. Now we have the following basic idea:

We will use the coverage metric described in Developer Testing blog article Selecting Developer Testing Metrics to visualize the status quo.

We won't make demands how much percent the code has to be covered. Nonetheless we want some kind of control. Therefore we will check if the coverage has significantly reduced over time. If this is the case the whole team will be informed. There should be no personal blaming.

To encourage the developer to write more tests we will ask them to do the estimate of a feature with the tests in mind, so that they have enough time do write the tests.

We don't have much experience in test standards. Is this a good approach? Is this metric useful? And what do you think about our strategy to control the team members?

EDIT

Some additional information regarding Sklivvz's post. We have nearly no code covered. Overall it is about 25%. Some components are just not covered. Our problem is, that our developers - mostly people with 10+ years experience - don't write tests at all. Therefor we invests much time in fixing bugs found by our testing team. What we want, is to have more assurance that we don't break something by implementing another thing and that we don't make the same bugs.

Additional it would be nice to let the tests guide our team members to make a better architecture in their components. I personally have seen it in a component where I came in later and had refactored the whole component at some point, because it was not even a little bit testable.

We develop a software platform which grows several years now. Therefor we have much code which is not covered by tests. Like I said above we want to motivate our team members to write tests for their components which they are currently developing.

答:
Caveat emptor: why are you implementing test standards?

The only correct answer here is to evaluate the test standards in comparison with what you are trying to get out of testing.

Example: if you are trying to have a defect-free embedded medical application (like a pace-maker), then your standards are probably too low. If you are writing prototype throw-away applications, like demos, your standards are definitely too high.

Another example: if your team is very senior, and you need to write lean and fast code, probably other forms of testing are more important than unit tests. If you have a junior team that is prone to make a lot of mistakes and you want to implement defensive standards, then this strategy doesn't seem strong enough.

That said, I would say that with the standards you are suggesting, you won't get a lot from the tests:

Partial code coverage is better than nothing, but if you introduce complexity due to testing you may have an increased defect count in the non-tested parts.

Partial code coverage does not allow your team to refactor mercilessly with impunity.

Giving developers time to write tests is good, but, asking them to write tests first is much better, and giving them acceptance tests is probably better in your case.

As you can see, my answers are very general, but they do represent my repeated experience. In no case mix-and-match indices have been useful to me.

There are two uses of code coverage, as far as I know:

when your code has low coverage (say <85%), code coverage is only useful in identifying places that need testing love. The percentage is frankly irrelevant.

when your code coverage is high, you can use a minimum coverage metric to turn the build red. Yes, high coverage doesn't guarantee correctness, but low coverage is certainly correlated with more defects, so once your team achieve high standards it's good if they can maintain them.

Your strategy of making the coverage check unobtrusive will only work if the team has already high code coverage, otherwise they will need to know exactly what to cover, in which case they will need to have constantly available a line-by-line map of the coverage they have!

Finally, if you have a lot of untested code simply giving your developers time to write tests for new features will not fix the initial coverage problems. This is important, because in order to make the new code testable, your team will need to refactor the old code, and in order to do that with confidence... they need to test the old code first. You haven't specified if this is for a greenfield project or a brownfield one - it makes a big difference.

Let me address the further information you provided.

You want to shorten your feedback cycles;

You want to motivate your team;

You want your team to write tests;

You want to reduce bug count for new features;

You want to reduce regressions;

These objectives are laudable but very hard to achieve in an ideal situation, let alone in a complicated, legacy application scenario.

What I suggest is that you focus on the most important one and achieve that first, and then move on to the next. Make sure that once you start rearchitecting your application you have very well set architectural qualities (i.e., performance is a feature).

For example:

Put your testing and development team working together, and have them come back with a good plan to test the application automatically. The solution needs to be achievable within some constraints (typically of time). You don't want 100% coverage at this stage. You simply want an automate testing set-up to be run, with the quick-win tests being run on it.

Once the above is done, set some concrete objectives on quality, and let the team propose the best strategy to achieve these. Typically they will come up with some form of vertical testing, like integration tests. Measure everything, be transparent, monitor successes and failures. You want code coverage here, but also bug count graphs, etc.

Once the above is done, and if TDD is appropriate, refactor, rearchitecture and unit test the legacy code (wrap and refactor), and develop new features using TDD.

...


答:
If your company writes Antivirus Software you might need to test or dogfood your software.

Sounds far fetched, but it was exactly my case 3 or 4 years ago, and I can assure you it was not zero impact at all.

Furthermore, in 2010,

The malware industry has published nearly four new viruses per minute in the first half of the year.

--https://www.gdatasoftware.co.uk/press-center/news/article/article/1760-number-of-new-computer-viruses.html

Given those numbers, the only way AV software can keep up is through heuristics -- in practice monitor particular win32 calls and making them trigger the AV. Of course, this is a bit of a problem if you need to make those calls as a developer. Again, a problem I did see happen.


问:
How can I keep a production Python environment secure?
Most of my work is creating websites in Django (a Python web framework) and deploying them to my own or clients' servers. I work from a virtualenv to separate site from system packages and have perhaps 60-80 packages installed in there and that lot is  shared between two-dozen sites.

This obvious limitation to this approach is needing to test every site if I upgrade a package it uses. I consider that a fair trade-off for not needing to keep on top of umpteen separate virtualenvs.

And that is essentially my whole problem. How on earth are you supposed to keep on top of virtualenv deployments? People just seem to treat them like a dumping ground but if the programming universe has learnt anything this past week from the Ruby on Rails explosion, using old versions of software is unacceptable.

I have a simple script that attempts to check for current package versions with the latest pip counterpart but it's quite inacurrate. It also doesn't differentiate between security upgrades and feature upgrades (which require days of testing and fixing).

I am looking for something better. I am looking for something that can let me know if Django has a new security release out, or if something is end-of-life. I want something to help me (and other Python devops) not become the next batch of people crying after a wave of kids with scanners and scripts convert our servers into a botnet.

Does such a thing exist?

答:
For getting notified when exploits exist there are RSS feeds, services and products out there that will let you know about exploits. At the very least any admin should probably be following CVE or NVD (which includes CVE).

How to manage exploits in libraries used by your application, but not in the virtualenv?  For example ImageMagick, the python executable itself or a system library that python uses.  I think your only option is to upgrade the platform, and then do the required vetting of the virtualenv and application.

At my work we create our own package (RPM) which includes python.  We are in the same boat if there is a system library security flaw (upgrade the platform, vet the application).  However application libraries or python itself are easily managed as they are in the toolchain package.  We simply rev that, run it through our continuous integration build which rebuilds all the projects and generates all new packages for the upgrade toolchain.

There is no vertically integrated solution specific to python or django that I know of.