答:
Try explanatory variable names

Comments can be great, but when possible, make the code self-documenting. One way of doing this is with explanatory variable names. For example, rather than this:

```<code>if (user.has_sideburns && user.can_gyrate) {
  // This user is a potential Elvis impersonator

}
</code>```

I'd prefer a named variable:

```<code>is_potential_elvis_impersonator = user.has_sideburns && user.can_gyrate

if (is_potential_elvis_impersonator) {
  ...
}
</code>```

Body:
Whenever I'm writing a typical if-else-construct in any language I wonder what would be the best way (in terms of readability and overview) to add comments to it. Especially when commenting the else clause the comments always feel out-of-place for me. Say we have a construct like this (examples are written down in PHP):

```<code>if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}
</code>```

I could comment it like this:

```<code>// check, what kind of magic should happen
if ($big == true) {
    // do some big magic stuff
    bigMagic();
} else {
    // small magic is enough
    smallMagic()
}
</code>```

or

```<code>// check, what kind of magic should happen
// do some big magic stuff
if ($big == true) {
    bigMagic();
}
// small magic is enough
else {
   smallMagic()
}
</code>```

or

```<code>// check, what kind of magic should happen
// if:   do some big magic stuff
// else: small magic is enough
if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}
</code>```

What are your best-practice examples for commenting this?

Body:
Try explanatory variable names

Comments can be great, but when possible, make the code self-documenting. One way of doing this is with explanatory variable names. For example, rather than this:

if (user.has_sideburns && user.can_gyrate) {
  // This user is a potential Elvis impersonator

}

I'd prefer a named variable:

is_potential_elvis_impersonator = user.has_sideburns && user.can_gyrate

if (is_potential_elvis_impersonator) {
  ...
}


问:
best way to handle a many to many relationship?
I am drawing a class diagram and I want to know what's the proper notation for many to many relationship between supplier and product?

Should I show the table created supplier_product or leave it out and have the relationship many to many between supplier and product?

I have seen various representations online.

答:
It depends on the business. On our business you can get the same spare part from multiple suppliers and each and every one has its own internal item code. So we have our own product item master which holds our code with the relative data.

Then there is the supplier master table with the suppliers.

Finally a Cross reference table exists where you bind one item with one supplier and provide the suppliers Description and item code.

so i suppose that in our case its a many to many relationship....

ContentLicense: CC BY-SA 3.0


答:
I annotate the line with "*..*".  For 1-to-many it would be "1..*".  It's a standard way of denoting multiplicity.

http://en.wikipedia.org/wiki/Cardinality_%28data_modeling%29

http://www.agilemodeling.com/artifacts/classDiagram.htm

Title: best way to handle a many to many relationship?

Body:
I am drawing a class diagram and I want to know what's the proper notation for many to many relationship between supplier and product?

Should I show the table created supplier_product or leave it out and have the relationship many to many between supplier and product?

I have seen various representations online.


问:
Is there a term for quasi-open source proprietary software?
Say a company wants to keep development of new features of a piece of software internal, but wants to make the source code for previous versions public, up to and including existing public features, so that other people can benefit from using and modifying the software themselves, and even possibly contribute changes that can be applied to the development branch.

Is there a term for this sort of arrangement, and what is the best way of accomplishing it using existing version control tools and platforms?

答:
I believe the term is dual-licensing. (or multi-licensing)

The portion of the project you want people to dink around with you release under, say, the LGPL which lets it call proprietary material. The port of the project you want to keep under your thumb is a proprietary for-sale software.


问:
Shelving code in Team Foundation Server (TFS)
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?

答:
I don't trust my local hard drive not to crash overnight. Shelving = backup, for me personally.

I've also been on teams that use the shelving feature for exploratory/proof of concept coding that might span several days. It let's you see how something might fit into the software without really committing to it too much.


答: I don't know about others but sometimes I'm working on a large change that is lower priority and another change comes up that is higher priority and so I shelve my work and do whatever needs done first. Also as Fish pointed out shelving backs up your code. Nothing worse than losing all your work especially right before it is done.</p>

Title: Shelving code in Team Foundation Server (TFS)

Body:
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?


问:
How do graphics programmers deal with rendering vertices that don't change the image?
So, the title is a little awkward.  I'll give some background, and then ask my question.

Background: I work as a web GIS application developer, but in my spare time I've been playing with map rendering and improving data interchange formats.  I work only in 2D space.

One interesting issue I've encountered is that when you're rendering a polygon at a small scale (zoomed way out), many of the vertices are redundant.  An extreme case would be that you have a polygon with 500,000 vertices that only takes up a single pixel.  If you're sending this data to the browser, it would make sense to omit ~499,999 of those vertices.  One way we achieve that is by rendering an image on a server and and sending it as a PNG: voila, it's a point.  Sometimes, though, we want data sent to the browser where it can be rendered with SVG (or canvas, or webgl) so that it can be interactive.

The problem: It turns out that, using modern geographic data sets, it's very easy to overload SVG's rendering abilities.  In an effort to cope with those limitations, I'm trying to figure out how to visually losslessly reduce a data set for a given scale and map extent (and, if necessary, for a known map pixel width and height).

I got a great reduction in data size just using the Douglas-Peucker algorithm, and I believe I was able to get it to keep the polygons true to within one pixel.  Unfortunately, Douglas-Peucker doesn't preserve topology, so it changed how borders between polygons got rendered.  I couldn't readily find other algorithms to try out and adapt to the purpose, but I don't have much CS/algorithm background and might not recognize them if I saw them.

答:
What you are looking for is 2d level of detail algorithms.

There is much documented about this on google if you search for those highlighted terms.

This question on stackoverflow has the information you are looking for on 2D Level of Detail rendering.


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
Choosing a programming convention is effectively the same as choosing subset of the target language.  We all do this for the usual reasons: code readability, maintainability, stability, portability, etc.  -- while potentially sacrificing flexibility.  These reasons are real business reasons.

Reasons such as "saving keystrokes," and "programmers should learn the JavaScript rules" are marginal business reasons so they carry little practical weight.

In my case I needed to come up to speed in JavaScript very fast, so leveraging a limited subset of the language was to my advantage.  So I chose the JSLint subset of JavaScript, turned on the Rockstar apps JSLinter in Eclipse to the most restrictive settings I could stand, and haven't looked back.

I'm grateful to be able to avoid the details of the difference between "==" and "===", or the details of semicolon insertion, because I've got a mile high task list already and those details won't help get those jobs done one second earlier.

Of course the most important thing about a convention is consistency, and thinking of it as a language subset helps to reinforce this imperative.  And although this may not help answer the OP's question, I think it might help with the practical framing of it.


问:
Does it make sense to write build scripts in C++?
I'm using CMake to generate my projects IDE/makefiles, but I still need to call custom "scripts" to manipulate my compiled files or even generate code.

In previous projects I've been using Python and it was OK, but now I'm having serious trouble managing a lot of dependencies in two very big projects I'm working on so I want to minimize the dependencies everywhere.

Someone suggested to me to use C++ to write my build scripts instead of adding a language dependency just for that. The projects themeselves already use C++ so there are several advantages that I can see:

to build the whole project, only a C++ compiler and CMake would be necessary, nothing else (all the other dependencies are C or C++);

C++ type safety (when using modern C++) makes everything easier to get "correct";

it's also the language I know the better so I'm more at ease with it even if I'm able to write some good Python code;

potential gain in execution speed (but i don't think it will really be perceptible);

However, I think there might be some drawbacks and I'm not sure of the real impact as I didn't try yet:

might be longer to write the code (that said I'm not sure because I'm efficient enough in C++ to write something that work quickly, so maybe for this system it wouldn't be so long to write) (compilation time shouldn't be a problem for this case);

I must assume that all the text files I'll read as input are in UTF-8, I'm not sure it can be easilly checked at runtime in C++ and the language will not check it for you;

libraries in C++ are harder to manage than in scripting languages;

I lack experience and forsight so maybe I'm missing advantages and drawbacks.
So the question is: does it make sense to use C++ for this? do you have experiences to report and do you see advantages and disadvantages that might be important?

答:
Don't write scripts yourself, you are duplicating effort and re-inventing wheels.

Use something like SCONS or even Maven 3 which has support for C++ build systems.

A good build system, regardless of language should not require custom logic in the form of scripts to build a functioning executable artifact.

If you have to write scripts for a build system to customize it, it isn't a good build system. Writing a plugin for a build system is a different story, but still that should be very particular to an environment/hardware mostly, and should be something that is rarely resorted to.


问:
Implementing Command Pattern in Web Application
I'm looking to implement the command pattern in a web application (asp.net c#)... Since the commands come in text format from the client, what is the best way to translate the string to a command object? Should I use reflection? Currently I just assume the command that comes in matches the file name of a user control. This is a bit of a hack.

Rather than have a select case statement that says if string = "Dashboard" then call Dashboard.Execute(), is there a pattern for working with commands that originate as strings?

答: You could use a hash table to map from input strings to Execute methods.</p>


问:
An XML file or Database?
I am re-writing a section of my site and am trying to decide how much of a rewrite this will be. At the moment I have a web service feed that generates an xml once per day. I then use this xml file on my website to generate the general structure. I am trying to decide if this information should be located in the database or stay in the xml file.

The file can range from 4mb - 12mb.

The files depth can go on and on so I have to recurse to find the data I want.

I use the .NET serializer classes and store the serialized file in a global variable to avoid re-serializing it each time the page is loaded.

My reasons for thinking a database would be better are:

I would know exactly where I am in the file by using an internal ID so I wouldn't have to recurse the file to get information.

I wouldn't have to load / serialize the XML and could just use my already open database connections.

Searching for the data in the file would be quicker(?) as I would just perform an SQL query rather than re-cursing the file.

Has anyone got any ideas which is better and which option uses more resources on the server or be quicker?

EDIT: The file is read every time the web page is loaded (although only serialized once). It isn't written to by standard users (only by an admin task that runs in the middle of the night).

This is my initial investigation before mocking up.

答: I've re-read your question again and had another thought. At the moment you are doing all the work on the web-server. If you use a database server then SQL Server caches execution plans. My gut feeling is that by using a database server you'll be using resources more efficiently. With databases you can add indexes onto the tables which can greatly improve performance.</p>

Title: An XML file or Database?


答:
The best way to do this in just about any app is to use an IoC container. Then your command pattern looks something like:

```<code>public static class CommandLineActionFactory
{
    public static ICommandLineAction GetAction(string actionName)
    {
        if (actionName == null) throw new ArgumentNullException(nameof(actionName));
        ICommandLineAction ret = ObjectFactory.TryGetInstance<ICommandLineAction>(actionName);
        if (ret == null)
        {
            throw new ArgumentOutOfRangeException(nameof(actionName), $"Action '{actionName}' does not exist.");
        }
        return ret;
    }
}
</code>```

[code is from a command line app but the pattern works for the web]

The huge advantage here is that you can take advantage of the IoC container to instantiate the handlers, including patching in their dependencies. Also opens the door to stunts like runtime addition of plugins.

Title: Implementing Command Pattern in Web Application

Body:
I'm looking to implement the command pattern in a web application (asp.net c#)... Since the commands come in text format from the client, what is the best way to translate the string to a command object? Should I use reflection? Currently I just assume the command that comes in matches the file name of a user control. This is a bit of a hack.

Rather than have a select case statement that says if string = "Dashboard" then call Dashboard.Execute(), is there a pattern for working with commands that originate as strings?

Body:
The best way to do this in just about any app is to use an IoC container. Then your command pattern looks something like:

public static class CommandLineActionFactory
{
    public static ICommandLineAction GetAction(string actionName)
    {
        if (actionName == null) throw new ArgumentNullException(nameof(actionName));
        ICommandLineAction ret = ObjectFactory.TryGetInstance<ICommandLineAction>(actionName);
        if (ret == null)
        {
            throw new ArgumentOutOfRangeException(nameof(actionName), $"Action '{actionName}' does not exist.");
        }
        return ret;
    }
}

[code is from a command line app but the pattern works for the web]

The huge advantage here is that you can take advantage of the IoC container to instantiate the handlers, including patching in their dependencies. Also opens the door to stunts like runtime addition of plugins.


问:
How to remove the boundary effects arising due to zero padding in scipy/numpy fft?
I have made a python code to smoothen a given signal using the Weierstrass transform, which is basically the convolution of a normalised gaussian with a signal.

The code is as follows:

```<code>#Importing relevant libraries
from __future__ import division
from scipy.signal import fftconvolve
import numpy as np

def smooth_func(sig, x, t= 0.002):
    N = len(x)
    x1 = x[-1]
    x0 = x[0]

# defining a new array y which is symmetric around zero, to make the gaussian symmetric.
    y = np.linspace(-(x1-x0)/2, (x1-x0)/2, N)
    #gaussian centered around zero.
    gaus = np.exp(-y**(2)/t)

#using fftconvolve to speed up the convolution; gaus.sum() is the normalization constant.
    return fftconvolve(sig, gaus/gaus.sum(), mode='same')
</code>```

If I run this code for say a step function, it smoothens the corner, but at the boundary it interprets another corner and smoothens that too, as a result giving unnecessary behaviour at the boundary. I explain this with a figure shown in this image

This problem does not arise if we directly integrate to find convolution. Hence the problem is not in Weierstrass transform, and hence the problem is in the fftconvolve function of scipy.

To understand why this problem arises we first need to understand the working of fftconvolve in scipy.

The fftconvolve function basically uses the convolution theorem to speed up the computation.

In short it says:

```<code>convolution(int1,int2)=ifft(fft(int1)*fft(int2))
</code>```

If we directly apply this theorem we dont get the desired result. To get the desired result we need to take the fft on a array double the size of max(int1,int2). But this leads to the undesired boundary effects. This is because in the fft code, if size(int) is greater than the size(over which to take fft) it zero pads the input and then takes the fft. This zero padding is exactly what is responsible for the undesired boundary effects.

Can you suggest a way to remove this boundary effects?

I have tried to remove it by a simple trick. After smoothening the function I am compairing the value of the smoothened signal with the original signal near the boundaries and if they dont match I replace the value of the smoothened func with the input signal at that point.

It is as follows:

```<code>i = 0
eps=1e-3
while abs(smooth[i]-sig[i])> eps: #compairing the signals on the left boundary
    smooth[i] = sig[i]
    i = i + 1
j = -1

while abs(smooth[j]-sig[j])> eps: # compairing on the right boundary.
    smooth[j] = sig[j]
    j = j - 1
</code>```

There is a problem with this method, because of using an epsilon there are small jumps in the smoothened function.

Can there be any changes made in the above method to solve this boundary problem?

答:
There are a variety of ways to try to resolve boundary conditions; it's a problem you need to deal with whether you are doing direct convolution or FFT-based convolution.  Unfortunately, it's not clear exactly what your difficulty is (your graphs don't have enough context for me to tell where they come from or what they mean); in the following, I will have to guess.

The thing you need to need to remember about FFT-based convolution is that it treats its input as a periodic loop.  Your question mentions a problem that "does not arise if we directly integrate to find convolution"; that difference is probably due to this property.

You claim that "the zero padding is responsible for the undesired boundary effects".  However, in order for FFT convolution to match the results of direct convolution, you must ensure that there is sufficient zero padding added to the original data to keep the periodic nature of the FFT from interfering with the convolution.  For this purpose, I believe that "sufficient zero padding" should be length of the filter you are convolving with.  Try splitting the zero padding for your fftconvolve() evenly between the beginning and end of your data run.

If you are unsatisfied with the boundary effects of your direct convolution, I'm not sure what to tell you, since I don't know what your application is.  I will advise that the result of your convolution will be as long as the original data plus the length of the filter, so you will need to provide for that.


问:
Interfaces: profit of using
First of all, my ubiquitous language is PHP, and I'm thinking about learning Java.

So let me split my question on two closely related parts.

Here goes the first part.

Say I have a domain-model class. It has some getters, setters, some query methods etc. And one day I want to have a possibility to compare them. So it looks like:

```<code>class MyEntity extends AbstractEntity
{
    public function getId()
    {
        // get id property
    }

    public function setId($id)
    {
        // set id property
    }

    // plenty of other methods that set or retrieve data

    public function compareTo(MyEntity $anotherEntity)
    {
        // some compare logic
    }
}
</code>```

If it would have been Java, I should have implemented a Comparable interface. But why? Polymorphism? Readbility? Or something else? And if it was PHP -- should I create Comparable interface for myself?

So here goes the second part.

My colleague told me that it is a rule of thumb in Java to create an interface for every behavioral aspect of the class. For example, if I wanted to present this object as a string, I should state this behaviour by something like implements Stringable, where in case of PHP Stringable would look like:

```<code>interface Stringable
{
    public function __toString();
}
</code>```

Is that really a rule of thumb? What benefits are gained with this approach? And does it worth it in PHP? And in Java?

答:
I know nothing of PHP, and don't really mean to answer your question, but the answer to your first part is "Polymorphism" and the second is "No".  The other answers here do a good job of explaining it all.

What I wanted to add is that you can use classes instead of interfaces.

At the extreme, you can write an abstract class with all abstract methods that works exactly like an interface.  The immediate down side is that any class that extends ("implements") this class can't extend another class, which may be a problem, now or later.  On the other hand, you can make one or more of your methods concrete and save work in all the extending (formerly implementing) classes.  All your descendant classes (subclasses, subsubclasses, etc.) can be referenced as being of this class, providing all the polymorphism of an interface.

My usual process is to start with an interface, see that I have common code in all the classes that implement it, then turn the interface into a base class and put the common code there.  Later, I find myself writing a new class that cannot extend the base class but needs to look like it.  (I need the polymorphism.)  So I write a new interface just like the old one, have the old one--now the base class--implement it, and change all the places where something is declared to be of the base class type to declaring it as the new interface type.  The new class then implements the interface also.

And I'm off to the next interface that becomes a base class that spawns an interface.

Title: Interfaces: profit of using


答:
If I understand correctly, your data changes once exactly per day.  To be honest, it doesn't matter if you have it as XML, or it store it row-by-row in a DB; what would make a big difference is if you cached it in your web application.

Basically, you should read in the file at most once per day (this can happen on-demand, just check if your cached version has expired), and store its contents in a structure optimised for quickly fetching information.  This will prevent your pages wasting CPU time parsing the file over and over again, as well as saving the garbage collector a lot of work.

Technically, a 10 MB XML file should take up a similar amount of memory as objects (accounting for the lack of bloat of a text-based encoding, but also for the overhead of having Dictionary objects for indexing), which is nothing these days.  Changes like these typically result in performance gains of a couple of orders of magnitude.

Title: An XML file or Database?

Body:
I am re-writing a section of my site and am trying to decide how much of a rewrite this will be. At the moment I have a web service feed that generates an xml once per day. I then use this xml file on my website to generate the general structure. I am trying to decide if this information should be located in the database or stay in the xml file.

The file can range from 4mb - 12mb.

The files depth can go on and on so I have to recurse to find the data I want.

I use the .NET serializer classes and store the serialized file in a global variable to avoid re-serializing it each time the page is loaded.

My reasons for thinking a database would be better are:

I would know exactly where I am in the file by using an internal ID so I wouldn't have to recurse the file to get information.

I wouldn't have to load / serialize the XML and could just use my already open database connections.

Searching for the data in the file would be quicker(?) as I would just perform an SQL query rather than re-cursing the file.

Has anyone got any ideas which is better and which option uses more resources on the server or be quicker?

EDIT: The file is read every time the web page is loaded (although only serialized once). It isn't written to by standard users (only by an admin task that runs in the middle of the night).

This is my initial investigation before mocking up.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
It always takes longer than you
  expect, even when you take into
  account Hofstadter's Law.

  — Hofstadter's Law

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Is there a resource that explains the benefits of layered programming?
Let's say we have a winform application with a buttonclick event.  The buttonclick handles everything from the UI configuration to the database call and data manipulation.  So you end up with a method that is 100's of lines of code long.  Outside the fact that this code can't be considered test-able for various reasons, this style of programming is fragile to change.

I can talk bout OO, Anti-patterns, etc.  The problem is that any distinct topic I can dream up requires a great deal of explanation to understand the potential benefits.

Outside of finding a new job (lots of businesses program this way), how can I teach these kinds of developers how to write better code?  Obviously we can't sit around a round table and discuss pro's and con's all day due to time constraints and real work that has to be done. Although, training and intense training is the only thing I can think of to fix these problems.

Not to say I write perfect code, I most certainly do not.  I do believe there are certain best practices that should be followed as a rule E.G. OO in the context of .NET.

The most common excuse I hear is "we can't write code fast enough if we do it like that".

答:
Find a suitable paradigm like Model-View-Controller, and discuss it specifically.

I think you will find that your developers will immediately see the benefits of following a pre-defined architectural standard.  You will also be talking about something concrete, rather than pie-in-the-sky abstract concepts.

ASP.NET MVC has complete code walkthroughs in their NerdDinner sample project.


答:
"I am drawing a class diagram ... Should I show the table created supplier_product ? "

The many-to-many relationship is part of your class design.  The join table is not; it is created incidentally by the OR mapping framework.  Include the relationship.  Do not include the table, or any other generated artifact.


问:
Whats the difference between a Ledger and a list of transactions?
re: algorithm and data structure concepts

When accountants talk about Ledgers they have something very specific in mind. As a programmer I'm very used to thinking about tables of information, but clearly there are specific things that make a ledger a ledger.

So, given a simple list of transactions (date, money in, money out, notes) what needs to be added/changed to make that list into something Accountants would call a ledger?

e.g. formatting considerations, does it have to be immutable, does it have to reflect something happening in a real bank account somewhere, does it have to have some sort of 'foreign key' describing which entity each transaction refers to...

答:
Ledgers are always balanced; i.e. a credit to one account/category is offset by a debit in another.

It follows that, for a "simple transaction" to be considered "ledger quality," it either has to be validated by an "encapsulating transaction" (in a similar way that a database transaction works), or  accompanied by some sort of adjustment record that accounts for the discrepancy.

The "encapsulating transaction" simply assures that either all of the necessary parts of the transaction must be executed (i.e. the debit and the credit), or none of the transaction is executed (what we call a rollback).


答:
I personally have Multiple reasons to shelve:

I want/need to go home but the current code would beak the build when it would be checked in.

it is a backup

if I would get sick, other members of my team would be able to get my changes and work on them

sometime I am making a change and want to start over but not lose all the code that I have written sofar. Something might be usefull

exchange the code with a team member without checking the code in.

Hope this helps.


答:
This is going to require a time investment.  If people are committed to practices like "duct-tape programming", avoiding unit tests, writing static-procedural code in an OO language, etc, speeches about decoupling and test seams are not going to sway them.  Speeches about anything probably won't sway them.

Keep to yourself, and do things your way, and then explain your methodology when the inevitable questions start to come your way such as "why are you able to absorb changes so much better than the rest of us?" or "why are your defect counts lower than the rest of us?"  At this point, you'll have someone's ear - either developers if they're genuinely engaged but skeptical of your ideas or managers if the developers are checked out.

To put it more succinctly: talk is cheap, but results aren't.  Get the results and you'll be asked to talk.  :)

Title: Is there a resource that explains the benefits of layered programming?

Body:
Let's say we have a winform application with a buttonclick event.  The buttonclick handles everything from the UI configuration to the database call and data manipulation.  So you end up with a method that is 100's of lines of code long.  Outside the fact that this code can't be considered test-able for various reasons, this style of programming is fragile to change.

I can talk bout OO, Anti-patterns, etc.  The problem is that any distinct topic I can dream up requires a great deal of explanation to understand the potential benefits.

Outside of finding a new job (lots of businesses program this way), how can I teach these kinds of developers how to write better code?  Obviously we can't sit around a round table and discuss pro's and con's all day due to time constraints and real work that has to be done. Although, training and intense training is the only thing I can think of to fix these problems.

Not to say I write perfect code, I most certainly do not.  I do believe there are certain best practices that should be followed as a rule E.G. OO in the context of .NET.

The most common excuse I hear is "we can't write code fast enough if we do it like that".


问:
Why is CS never a topic of conversation of the layman?
Granted, every profession has it's technicalities.  If you are an MD, you better know the anatomy of the human body, and if you are astronomer, you better know your calculus.  Yet, you don't have to know these more advance topics to know that smoking might give you lung cancer because of carcinogens or the moon revolves around the earth because of gravity (thank you Discovery Channel). There's sort of a common knowledge (at least in more developed countries) of these more advanced topics.

With that said, why are things like recursive descent parsing, BNF, or Turing machines hardly ever mentioned outsided 3000 or 4000 level classes in a university setting or between colleagues?  Even back in my days before college in my pursuit of knowledge on how computers work, these very important topics (IMHO) never seem to get the light of day. Many different sources and sites go into "What is a processor?" or "What is RAM?", or "What is an OS?". You might get lucky and discover something about programming languages and how they play a role in how applications are created, but nothing about the tools for creating the language itself.  To extend this idea, Dennis Ritchie died shortly after Steve Jobs, yet Dennis Ritchie got very little press compared to Steve Jobs.

So, the heart of my question:  Does the public in general not care to hear about computer science topics that make the technology in their lives work, or does the computer science community not lend itself to the general public to close the knowledge gap? Am I wrong to think the general public has the same thirst for knowledge on how things work as I do? Please consider the question carefully before answering or vote closing please.

答:
I think it's because the layman views computers as a black box and as a result does not care what actually happens inside as long as it works.  Add that in with a lot of people's fear of maths you don't get an environment were general discussion of the theory behind computing (computer science) occurs.

Also I think sometimes how we discuss the topic and sometimes shoot down questions (we all are guilty of this at some point) with 'it's complicated' or 'do you really want to know'


答:
Does the public in general not care to hear about computer science
  topics that make the technology in their lives work, or does the
  computer science community not lend itself to the general public to
  close the knowledge gap?

In short, no and no.

Knowledge specialization in modern society exists to such a degree that not only do most people not care about the concepts you mention, but it doesn't really make any sense for them to.  As people who understand these things, it may seem odd to us that others don't and odder still that they don't want to, but to what level of detail do we understand other professions?

Can programmers cite passages from the tax code by rote?  Can we explain the specific mechanics of how our cars' engines work?  Can we diagram up our houses' electrical systems?  Do we know the names of all of the chambers of our heart?  For some, the answer to these things may be "yes", but that's going to be the exception rather than the rule.  And, what's more, is there some specific reason we should care about the answer to these questions and dozens more?  After all, this is why we pay accountants, mechanics, electricians and doctors respectively.

The reason I rehash here what you covered in the first paragraph of your question is to emphasize matters of degrees.  A given programmer may care about the subject of taxes deeply as a matter of self interest.  It certainly affects him or her.  But there is a level of abstraction at which "I get a discount for owning a home" is sufficient without understanding all the provisions and history of the mortgage interest deduction.

The average consumer needs to know about RAM and processor because those impact them in the pocketbook and in the user experience.  Knowing how Turing machines work provides no actual benefit other than the aesthetic one relating to satisfaction in knowledge for most people.  If layperson doesn't understand what RAM is, he will potentially get ripped off by a salesman at Best Buy and have a bad user experience.  If he doesn't know some abstract concept, he'll still get his computer, his apps will still work, and he'll still be able to navigate with his GPS.

Title: Why is CS never a topic of conversation of the layman?

Body:
Granted, every profession has it's technicalities.  If you are an MD, you better know the anatomy of the human body, and if you are astronomer, you better know your calculus.  Yet, you don't have to know these more advance topics to know that smoking might give you lung cancer because of carcinogens or the moon revolves around the earth because of gravity (thank you Discovery Channel). There's sort of a common knowledge (at least in more developed countries) of these more advanced topics.

With that said, why are things like recursive descent parsing, BNF, or Turing machines hardly ever mentioned outsided 3000 or 4000 level classes in a university setting or between colleagues?  Even back in my days before college in my pursuit of knowledge on how computers work, these very important topics (IMHO) never seem to get the light of day. Many different sources and sites go into "What is a processor?" or "What is RAM?", or "What is an OS?". You might get lucky and discover something about programming languages and how they play a role in how applications are created, but nothing about the tools for creating the language itself.  To extend this idea, Dennis Ritchie died shortly after Steve Jobs, yet Dennis Ritchie got very little press compared to Steve Jobs.

So, the heart of my question:  Does the public in general not care to hear about computer science topics that make the technology in their lives work, or does the computer science community not lend itself to the general public to close the knowledge gap? Am I wrong to think the general public has the same thirst for knowledge on how things work as I do? Please consider the question carefully before answering or vote closing please.


答:
Your question is good because you are thinking of whether you need this table or not. That shows you care about the quality of your design.

The notation part has been fully answered by others, so I will focus more on the other part.

Should I show the table created supplier_product or leave it out and have the relationship many to many between supplier and product?

You need to find the answer not only from a technical perspective but also from a business perspective. For example, you need to ask a question like this:

Do I need to know when a supplier started supplying a product to the company?

Is the price of a supplied item depndent on the time or quantity supplied?

Is there a minimum quantity a supplier must supply per order that we need to know about?

Would there be associations between supplier_product to other classes in the model?

If your business has no interesting properties to place in the intersection table and there are no required associations (as in the above questions) and If you are doing the class diagram as part of high-level design from an OO perspective, you could do as @Kenvin Cline suggests and not include the class in your current version of the model.

If you want to be precise and clear and/or If you plan to implement the design at this stage in a relational database, either yourself or the application you'll use to create (forward engineer) the DLL will have to deal with the missing class representing the many-to-many relationship. Some tools could automatically create a Primary Key and FKs and RI constraints (of the tool's choice) and name all that in a way you may or may not accept. Also, your ORM mapper will have to create code to deal with this hidden table.

The effect of RI is critical and should always be checked and controlled. You need to precisely determine what happens  to the supplied item information when a supplier is deleted from a database.

If you were doing a physical database design, then I would definitely suggest you flesh out your design and not let the tools do that for you unless you are entirely familiar with how and what the tools will build for you.


答:
People in general don't care to know about how computers work as long as they do work. This is likely due to computers and related knowledge being viewed as very complicated (which is true in most cases). This may also likely be due to society viewing those that do have a lot of computer knowledge as "geeks", "nerds" and social outcasts in general and it is the fear of becoming labelled as one of these that keeps the general public from gaining too much knowledge.

I for one don't care that most people aren't interested in discussing computers and related knowledge. I myself try to discuss these things when appropriate, but I don't expect most people to be interested or to even understand what I am talking about.


答: You have two very different things.  You have academia and you have industry.  Computer science is an academic pursuit.  It's math and algorithm based.  Then you have industry.  Industry is application based.  One is theoretical the other is practical.  The public cares more about the practical, because that's what they use.  The browser, the applications, etc.  The computer science details are abstracted away (as they should be).</p>


问:
How do you encourage your organization to move from Java to Scala?
Has anybody's organization started the migration from Java to Scala? If yes, how do you do that? What can I do to encourage my colleagues to do the same?</p>

答:
A good way is to demonstrate two versions of the same program. By doing that you can  show to your colleagues (in practice) Scala's Expressiveness. Doing the same thing for other problems (XML, concurrency, etc.) can demonstrate the benefits of using Scala instead of Java for tackling specific problems.

Of course don't expect the migration to happen in one day. There are many problems that you might underestimate: The learning curve, the existing codebase, etc.


问:
What will generate an adjacency matrix file with a specified topology for me?
I am writing an application that takes some file specifying an adjacency matrix and uses this to construct a graph (in this case, a directed social network).

What I would like to do is specify the size of the matrix and then have it generate an adjacency matrix with one of these topologies: ring, hierarchical, fully-connected, random and smallworld (every node x degrees of separation from each other). Ideally a text file would be the output.

I can't create these files manually because the size is in the thousands^2...
Fully-connected and random aren't 100% required but they would be nice, I can just implement them in code.

I read a dissertation which specified it used an application located at http://ww2.cs.mu.oz.au/~tmill/graphtastic.tgz ...but it does not seem to exist anymore so I am not sure what to do. I thought there would be loads of applications such as this out there, but I can't see any.

So, is there an program out there that could generate an adjacency matrix with a configurable topology into a text file ?

答:
so you want:

```<code>graph => AM representation => textfile
</code>```

this scriptlet ought to do the trick

(relies on two python libraries, Networkx and NumPy)

```<code>>>> import numpy as NP       # import NumPy
>>> import networkx as NX    # import top-level networkx namespace
>>> # mock some data
>>> # create a graph using a built-in graph generator from networkx
>>> G = NX.navigable_small_world_graph(12, 2, 1, 2, 2, seed=542)
>>> type(G)
  <class 'networkx.classes.digraph.DiGraph'>

>>> # express the graph as an Adjacency Matrix:
>>> # (a square matrix symmetric about the main diagonal)
>>> AM = NX.to_numpy_matrix(G)

>>> # use a built-in function from NumPy
>>> # to save the Adjacency Matrix as a text file
    # import the library

>>> NP.savetxt("am.txt", AM, delimiter=',', newline="\n", fmt='%d')

>>> # to informally verify that it was saved correctly (just first 500 bytes)
>>> # read the text file back out
>>> with open("am.txt", "r") as f:
f.read(500)

  '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
   0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
   0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,
   0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,...'

>>> # assertion for a unit test would look something like this:
>>> val AM0 = NP.loadtxt("am.txt", delimiter=",")
>>> NP.assert_allclose(AM, AM0, rtol=1e-5, atol=1e-3)
</code>```

Body:
so you want:

graph => AM representation => textfile

this scriptlet ought to do the trick

(relies on two python libraries, Networkx and NumPy)

>>> import numpy as NP       # import NumPy
>>> import networkx as NX    # import top-level networkx namespace
>>> # mock some data
>>> # create a graph using a built-in graph generator from networkx
>>> G = NX.navigable_small_world_graph(12, 2, 1, 2, 2, seed=542)
>>> type(G)
  <class 'networkx.classes.digraph.DiGraph'>

>>> # express the graph as an Adjacency Matrix:
>>> # (a square matrix symmetric about the main diagonal)
>>> AM = NX.to_numpy_matrix(G)

>>> # use a built-in function from NumPy
>>> # to save the Adjacency Matrix as a text file
    # import the library

>>> NP.savetxt("am.txt", AM, delimiter=',', newline="\n", fmt='%d')

>>> # to informally verify that it was saved correctly (just first 500 bytes)
>>> # read the text file back out
>>> with open("am.txt", "r") as f:
f.read(500)

  '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
   0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
   0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,
   0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,...'

>>> # assertion for a unit test would look something like this:
>>> val AM0 = NP.loadtxt("am.txt", delimiter=",")
>>> NP.assert_allclose(AM, AM0, rtol=1e-5, atol=1e-3)


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
anything with something like this

// TODO: anything could be here!
```

Edit: I should qualify that I meant this in production code. But even in code committed to source control this still isn't good. But, that could be a personal thing in that I like to finish the day off having tied off all my loose ends :)

Edit 2: I should further qualify that I meant when I see this in established code. Like something that's a number of years old and I am fixing a bug it. I see a TODO and that's when the alarm bells start ringing. TODO's (to me) imply that the code was never finished for some reason.

Body:
anything with something like this

// TODO: anything could be here!

Edit: I should qualify that I meant this in production code. But even in code committed to source control this still isn't good. But, that could be a personal thing in that I like to finish the day off having tied off all my loose ends :)

Edit 2: I should further qualify that I meant when I see this in established code. Like something that's a number of years old and I am fixing a bug it. I see a TODO and that's when the alarm bells start ringing. TODO's (to me) imply that the code was never finished for some reason.


答:
My team shelves code when they want to share something with another developer without having to check in that code (vacation, vetting prototype, building one change set on multiple machines, etc.)

I also have some developers that use it in order to build up a few change sets (usually independent and small) so they can ask one person for multiple code reviews all at the same time.


答: People talk about computers and computer science-y things all the time, and in general they do it at about the same level of sophistication as they talk about biology, physics, etc. Most people have some idea about concepts like Moore's Law, clock speeds, gigabytes, megapixels, and algorithms just as they know something about DNA, proteins, "good" and "bad" cholesterol, and so on. If you say "recursive descent parser" even to many programmers, it's about the same as saying "mitochondrial transcription factors TFAM and TFB2M": not something most people are likely to know much about.


答:
One way you get junior developers to learn a paradigm is by not letting them touch the architecture. You design the architecture and then spell out the portions of code that they will write. Make sure they participate with all of the other developers and see how everything fits together as they write the code. Each week do a code review, and slap wrists for breaking the pattern and so on... This is a great way to learn, and they learn it by doing.

Over time, they will learn the way of thinking necessary to design things themselves.

Another way is to give them projects to do where the only way to solve the problem is to use a certain pattern. As they stumble through it, they will discover the pattern and/or see its wisdom and use.

I have tried sitting people down and explaining architecture to them, and it just flies over their head. Give them a project to do using it, and they catch on much easier.

IMHO, the best book for designing still is http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=cm_cr_pr_product_top. However, it is a book for a person who is already trying to write good code. To teach, you design, let them implement. Then over time, include your good programmers a little more in the design process.

Also,

"we can't write code fast enough if we do it like that".

is the dumbest excuse for poor work. Kindly explain to the offender that it takes exponentially more time to debug and maintain a poorly written program than it does to just write it correctly to begin with. A person who says such a thing has obviously never had to see a piece of code through from development to production to revision ad infinitum.


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
I would say having unit tests covering 100% of the code would be a good one. As that allows the excess stuff to be stripped away.

I sometimes compare software development to sculpture. It's not what you add, it's what you take away.

Obviously you can take that too far. No-one is going to say a small shiny pebble is a good sculpture :S


问:
What is a good way to comment if-else-clauses?
Whenever I'm writing a typical if-else-construct in any language I wonder what would be the best way (in terms of readability and overview) to add comments to it. Especially when commenting the else clause the comments always feel out-of-place for me. Say we have a construct like this (examples are written down in PHP):

```<code>if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}
</code>```

I could comment it like this:

```<code>// check, what kind of magic should happen
if ($big == true) {
    // do some big magic stuff
    bigMagic();
} else {
    // small magic is enough
    smallMagic()
}
</code>```

or

```<code>// check, what kind of magic should happen
// do some big magic stuff
if ($big == true) {
    bigMagic();
}
// small magic is enough
else {
   smallMagic()
}
</code>```

or

```<code>// check, what kind of magic should happen
// if:   do some big magic stuff
// else: small magic is enough
if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}
</code>```

What are your best-practice examples for commenting this?

答:
Just to complete some comments:

The proper use of comments is to compensate for our failure to express ourself in
  code. Note that I used the word failure. I meant it. Comments are always failures. We must
  have them because we cannot always figure out how to express ourselves without them,
  but their use is not a cause for celebration. (Clean Code by Robert C. Martin)

BTW: I do recommend this book.


问:
Shelving code in Team Foundation Server (TFS)
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?

答:
Amongst other uses that are already posted (backup, sharing, etc.): we use it for code reviews.

Dev shelves code that you want to check in

Dev creates code review with shelveset name

Reviewer unshelves code into latest, reviews/runs

Reviewer approves code review

Dev unshelves code into latest

Dev checks in

So when I fix a bug or a feature or whatnot, I shelve it and create a code review for my lead, then I undo pending changes on the sln and work on the next task until the review comes back. Then I shelve what I'm working on, unshelve my reviewed code (change whatever I need to depending on my lead's comments) and check in. I then unshelve what I was working on and continue.

Once you're used to it, it's a pretty smoothe process.


答:
Reading an XML file of that size every time the web page is loaded may become of course a performance bottleneck. Storing the file in a session variable of type XmlDocument (see http://msdn.microsoft.com/en-us/library/ms178581.aspx) reduces this to "one load per user session", which may be a lot faster. Utilizing xpath/xslt query syntax will give you a flexibility comparable to SQL.

Making use of a database as a cache makes only sense if the livetime of your database process is longer than the lifetime of your ASP.NET web page process, so you cannot use an in-memory database like SQL server compact edition. That means, you will have interprocess communication between your web page process and your database process, which is the main performance risk of that solution. Querying a loaded XMLDocument runs completely in-process. So, if it really pays using a database you will only know if you test it, and it is absolutely possible that the database solution will run a lot slower than the cached XML solution. Of course, if your amount of data increases to a size of several hundred MB or more, then there will be some point where a solution which does not load all the available data will be faster.

Disclaimer: I have never programmed an ASP.NET site on my own, so please excuse if I misunderstood something of that architecture.

Title: An XML file or Database?


问:
What is the proper jargon to refer to a variable wrapped inside a function closure?
In JavaScript, there is no such thing as a "private" variable.  In order to achieve encapsulation and information hiding in JavaScript, I can wrap a variable inside a function closure, like so:

```<code>var counter = (function() {
    var i = 0;
    var fn = {};
    fn.increment = function() { i++; };
    fn.get = function() { return i; };
    return fn;
{)();
counter.increment();
counter.increment();
alert(counter.get()); // alerts '2'
</code>```

Since I don't call i a private variable in JavaScript, what do I call it?

答:
According to wikipedia they're called "upvalues".

A closure allows a function to access variables outside its immediate
  lexical scope. An upvalue is a free variable that has been bound
  (closed over) with a closure. The closure is said to "close over" its
  upvalues.

Although it's probably better to wrongly call them private variables so people will understand what you mean.


问:
CI tests to enforce specific development rules - good practice?
The following is all purely hypothetical and any particular portion of it may or may not accurately describe real persons or situations, whether living, dead or just pretending.

Let's say I'm a senior dev or architect in charge of a dev team working on a project. This project includes a security library for user authentication/authorization of the application under development. The library must be available for developers to edit; however, I wish to "trust but verify" that coders are not doing things that could compromise the security of the finished system, and because this isn't my only responsibility I want it to be done in an automated way.

As one example, let's say I have an interface that represents a user which has been authenticated by the system's security library. The interface exposes basic user info and a list of things the user is authorized to do (so that the client app doesn't have to keep asking the server "can I do this?"), all in an immutable fashion of course. There is only one implementation of this interface in production code, and for the purposes of this post we can say that all appropriate measures have been taken to ensure that this implementation can only be used by the one part of our code that needs to be able to create concretions of the interface.

The coders have been instructed that this interface and its implementation are sacrosanct and any changes must go through me. However, those are just words; the security library's source is open for editing by necessity. Any of my devs could decide that this secured, private, hash-checked implementation needs to be public so that they could do X, or alternately they could create their own implementation of this public interface in a different library, exposing the hashing algorithm that provides the secure checksum, in order to do Y. I may not be made aware of these changes so that I can beat the developer over the head for it. An attacker could then find these little nuggets in an unobfuscated library of the compiled product, and exploit it to provide fake users and/or falsely-elevated administrative permissions, bypassing the entire security system.

This possibility keeps me awake for a couple of nights, and then I create an automated test that reflectively checks the codebase for types deriving from the interface, and fails if it finds any that are not exactly what and where I expect them to be. I compile this test into a project under a separate folder of the VCS that only I have rights to commit to, have CI compile it as an external library of the main project, and set it up to run as part of the CI test suite for user commits. Now, I have an automated test under my complete control that will tell me (and everyone else) if the number of implementations increases without my involvement, or an implementation that I did know about has anything new added or has its modifiers or those of its members changed. I can then investigate further, and regain the opportunity to beat developers over the head as necessary.

Is this considered "reasonable" to want to do in situations like this? Am I going to be seen in a negative light for going behind my devs' backs to ensure they aren't doing something they shouldn't?

答: This isn't unreasonable, because it is a very good idea to do code reviews for security-based code. You could mandate that developers do code-reviews before checking in code, but this doesn't protect you if they forget and check in anyway.</p>


问:
As a tooling/automation developer, can I be making better use of OOP?
My time as a developer (~8 yrs) has been spent creating tooling/automation of one sort or another. The tools I develop usually interface with one or more API's. These API's could be win32, WMI, VMWare, a help-desk application, LDAP, you get the picture. The apps I develop could be just to pull back data and store/report. It could be to provision groups of VM's to create live like mock environments, update a trouble ticket etc.

I've been developing in .Net and I'm currently reading into design patterns and trying to think about how I can improve my skills to make better use of and increase my understanding of OOP. For example, I've never used an interface of my own making in anger (which is probably not a good thing), because I honestly cannot identify where using one would benefit later on when modifying my code. My classes are usually very specific and I don't create similar classes with similar properties/methods which could use a common interface (like perhaps a car dealership or shop application might).

I generally use an n-tier approach to my apps, having a presentation layer, a business logic/manager layer which interfaces with layer(s) that make calls to the API's I'm working with. My business entities are always just method-less container objects, which I populate with data and pass back and forth between my API interfacing layer using static methods to proxy/validate between the front and the back end.

My code by nature of my work, has few common components, at least from what I can see. So I'm struggling to see how I can better make use of OOP design and perhaps reusable patterns.

Am I right to be concerned that I could be being smarter about how I work, or is what I'm doing now right for my line of work? Or, am I missing something fundamental in OOP?

EDIT: Here is some basic code to show how my mgr and api facing layers work. I use static classes as they do not persist any data, only facilitate moving it between layers.

```<code>public static class MgrClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Perform logic to validate or apply biz logic
        // call APIClass to do the work
        return APIClass.PowerOnVM(VMName);
    }
}

public static class APIClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Calls to 3rd party API to power on a virtual machine
        // returns true or false if was successful for example
    }
}
</code>```

答:
If you're never using interfaces and are using a layered approach, it seems fairly likely that you could be missing an opportunity for some decoupling and/or reuse, but it's really impossible to say without seeing the code.

One thing I might consider is asking whether or not you write automated tests (unit tests).  Interfaces are often quite helpful with this and tend to emerge sort of naturally as you look for ways to isolate testable units.  If you're not unit testing, you're missing not only a potential part of OOP, but a fundamental part of writing good reliable software.  So, if you're not doing that, I'd suggest giving it a try, and seeing if some interface use (and perhaps even design pattern use) don't emerge 'organically' as you do it.

OwnerDisplayName: Tom Pickles

OwnerDisplayName: Erik Dietrich


答:
Sounds like you might be missing a lot. Development patterns have been around for a long time and they really help with OOP. I would suggest reading about these patterns.

For a start have a look at SOLID - http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
There are 5 basic development patterns.

With regards to interfaces, they are really usefull. Interface defines the methods available and the concrete class provides the implementation. If you use interfaces you can easily swap classes to provide different functionality (without having to change the rest of the application).
An example of that would be data access layer. Imagine if you develope your application which uses LINQ to SQL. Some time later the requirement is to change the data provider to something else.
Now, if that was running of an interface with properly implemented Command Pattern http://en.wikipedia.org/wiki/Command_pattern , this would be very easy. You would only have to create new data access layer, implement the interface and that's it.

It's worth reading about the design patterns and all features given by OOP.

Hope that helps.

UPDATE

Based on your example, your APIClass already follows single responsibility pattern.

The way you could implement interface would be :

```<code>public interface IVMManager
{
    bool PowerOnVM(string VMName);
    bool PowerOffVM(string VMName);
}

public class MgrClass
{
    private IVMManager _vmManager;

    public MgrClass(IVMManager vmManager)
    {
        _vmManager = vmManager;
    }

    public bool PowerOnVM(string VMName)
    {
        // Perform logic to validate or apply biz logic
        // call APIClass to do the work
        return _vmManager.PowerOnVM(VMName);
    }
}

public class APIClass : IVMManager
{
    public bool PowerOnVM(string VMName)
    {
        //IMPLEMENTATION
    }
}
</code>```

REMEMBER : static methods cannot be exposed via interface !

This example also follows the command pattern. VM Manager is easily swapable with different implementation. You can also unit test this class.

Hope that gives you an idea how design patterns can be used and how powerfull OOP is.

Title: As a tooling/automation developer, can I be making better use of OOP?

Body:
My time as a developer (~8 yrs) has been spent creating tooling/automation of one sort or another. The tools I develop usually interface with one or more API's. These API's could be win32, WMI, VMWare, a help-desk application, LDAP, you get the picture. The apps I develop could be just to pull back data and store/report. It could be to provision groups of VM's to create live like mock environments, update a trouble ticket etc.

I've been developing in .Net and I'm currently reading into design patterns and trying to think about how I can improve my skills to make better use of and increase my understanding of OOP. For example, I've never used an interface of my own making in anger (which is probably not a good thing), because I honestly cannot identify where using one would benefit later on when modifying my code. My classes are usually very specific and I don't create similar classes with similar properties/methods which could use a common interface (like perhaps a car dealership or shop application might).

I generally use an n-tier approach to my apps, having a presentation layer, a business logic/manager layer which interfaces with layer(s) that make calls to the API's I'm working with. My business entities are always just method-less container objects, which I populate with data and pass back and forth between my API interfacing layer using static methods to proxy/validate between the front and the back end.

My code by nature of my work, has few common components, at least from what I can see. So I'm struggling to see how I can better make use of OOP design and perhaps reusable patterns.

Am I right to be concerned that I could be being smarter about how I work, or is what I'm doing now right for my line of work? Or, am I missing something fundamental in OOP?

EDIT: Here is some basic code to show how my mgr and api facing layers work. I use static classes as they do not persist any data, only facilitate moving it between layers.

```<code>public static class MgrClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Perform logic to validate or apply biz logic
        // call APIClass to do the work
        return APIClass.PowerOnVM(VMName);
    }
}

public static class APIClass
{
    public static bool PowerOnVM(string VMName)
    {
        // Calls to 3rd party API to power on a virtual machine
        // returns true or false if was successful for example
    }
}
</code>```

Body:
Sounds like you might be missing a lot. Development patterns have been around for a long time and they really help with OOP. I would suggest reading about these patterns.

For a start have a look at SOLID - http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
There are 5 basic development patterns.

With regards to interfaces, they are really usefull. Interface defines the methods available and the concrete class provides the implementation. If you use interfaces you can easily swap classes to provide different functionality (without having to change the rest of the application).
An example of that would be data access layer. Imagine if you develope your application which uses LINQ to SQL. Some time later the requirement is to change the data provider to something else.
Now, if that was running of an interface with properly implemented Command Pattern http://en.wikipedia.org/wiki/Command_pattern , this would be very easy. You would only have to create new data access layer, implement the interface and that's it.

It's worth reading about the design patterns and all features given by OOP.

Hope that helps.

UPDATE

Based on your example, your APIClass already follows single responsibility pattern.

The way you could implement interface would be :

public interface IVMManager
{
    bool PowerOnVM(string VMName);
    bool PowerOffVM(string VMName);
}

public class MgrClass
{
    private IVMManager _vmManager;

    public MgrClass(IVMManager vmManager)
    {
        _vmManager = vmManager;
    }

    public bool PowerOnVM(string VMName)
    {
        // Perform logic to validate or apply biz logic
        // call APIClass to do the work
        return _vmManager.PowerOnVM(VMName);
    }
}

public class APIClass : IVMManager
{
    public bool PowerOnVM(string VMName)
    {
        //IMPLEMENTATION
    }
}

REMEMBER : static methods cannot be exposed via interface !

This example also follows the command pattern. VM Manager is easily swapable with different implementation. You can also unit test this class.

Hope that gives you an idea how design patterns can be used and how powerfull OOP is.

OwnerDisplayName: Sebastian Siek


答:
I'd recommend you take a look at SOLID (here's a link) and from those start with interface segregation, dependency injection principle and single responsibility principle. They are all good, but I can immediately see that IS and DI could help you.

Next take a look at unit testing and test driven development. When you look at TDD (Test Driven Development) remember there is also TAD (After instead of driven). That just means you code as you always have and write tests afterwards. You lose the benefits of TDD, but it still helps you start to think in terms of outcomes and units.

When you are looking at testing you'll start seeing reference to mocking. Mocking means taking a bit of code you want to test that is dependent on bits of code you don't want to test and mocking out (replacing with a functional fake) the bits you don't want to test.

There are then loads of patterns which are useful, and you almost certainly already use a lot of them. Take a look at strategy pattern. That's a nice one.

Finally look at anti patterns. It might just be interesting to get the idea that just as there are commonly accepted good patterns of code reuse, there are also bad ones that you shouldn't fall into.

That isn't suppose to be an all in tutorial, but it will nudge you into the right direction to start seeing the benefits on your own I think.

OwnerDisplayName: Ian


问:
When not to use ORM and prefer stored procedures?
I am using PetaPoco micro-ORM. It is indeed very easy and secure to work with databases using ORM tools, but the only thing I hate is extra code. I used to put most of the code in the database itself and use all the RDBMS features like Stored Procedures, Triggers etc.,  which it is built to handle better.

I want to know when not to use ORM over Stored Procedures/Triggers and vice-versa.

答: Disagree. ORM query only simpler if you know ORM better than you know SQL. ORM results in far more code, far more-difficult to maintain IMO. The only people who benefit from ORM are the shareholders of the company selling the ORM (e.g. Microsoft).</p>


问:
What to answer to a customer who asks which one of two equivalent technologies must be used?
As a freelancer, I am often asked by my customers what they must choose between similar elements, neither of which being better than another. Examples:

“Do I need my e-commerce website be in PHP or ASP.NET?”

“Do I need to host this ordinary web service in Cloud or use an ordinary hosting service?”

“Which one is better for my new website: MySQL or Oracle?”

etc.

There is maybe at most 1% of cases where the choice is relevant, and there is a real, objective reason to use one over another, based on the precise metrics and studies. In all other cases, it doesn't matter at all. It is totally, completely irrelevant, either because there are no implications¹, or because those implications are too small to be taken in account², or, finally, because it's impossible to predict those implications³.

If you know one thing and not another one, the answer to those questions is easy:

“You can either write the application in C# or Java, both being probably equivalent in your case. Note that I'm a C# developer, so if you choose Java, I would not be able to work on your project and you would need to find another freelancer.”

When you know both technologies, you can't answer that.

In this case, how to explain to the customer that the question he asks is subject to flamewar and has no real consequences on his project?

In other words, how to explain that you've chosen to use one technology rather than an equivalent one for the reasons related to human resources, without giving the impression to be unprofessional or to not care about the project?

¹ Example: Is MySQL better (worse?), performance-wise, compared to Oracle, for a personal website which will be accessed by, oh, let's be optimistic, two people per day?

² Example: for a given project, I was asked to asset if Windows Azure hosting would be cheaper than the hosting of the same application on a well-known ASP.NET hosting provider. The cost revealed to be exactly the same.

³ Example: your customer have an idea of a future application (the idea itself being extremely vague). There is no business plan, no requirements, nothing at all. Just an idea. You are asked if Java is better than C# for this app. What do you answer?

答:
how to explain that you've chosen to use one technology rather than an equivalent one for the reasons related to human resources, without giving the impression to be unprofessional or to not care about the project?

Well. You say just that:

In terms of the requirements for this project, technology X and technology Y are equally suited to the task, so technical considerations do not come into it.

It is easier to find talented people with knowledge of the chosen technology (or problem domain), which is why it was selected.

Or - for the purpose of this project, using technology Y is going to be more cost effective.

Tell it like it is.

You may want to find an analogy that the customer can relate to. Something like - for the purpose of getting from Europe to the US, you can go on a Boeing 747 or an Airbus 380. Does it matter which one? Not to the customer, so long as they get there and the technologies are equally suited to the requirements :)

Which one was selected? Whichever one the airline operates...


答:
"Would you rather drive a Ford or a Chevy?" would be the driving analogy I'd toss out to see if they can pick up the idea that the question isn't going anywhere.  A similar question could be, "Which is better a hamburger or a pizza?" where without adding more constraints the question has a variety of possible answers one could give.

The other way to view this is to ask why is this important to know and depending on what additional material may be found by clarifying the question this may lead to a better answer.  Some people may just wonder, "What was used to build my e-commerce site?" though they would rather try to be impressive and throw in a couple of buzz words.

Title: What to answer to a customer who asks which one of two equivalent technologies must be used?

Body:
As a freelancer, I am often asked by my customers what they must choose between similar elements, neither of which being better than another. Examples:

“Do I need my e-commerce website be in PHP or ASP.NET?”

“Do I need to host this ordinary web service in Cloud or use an ordinary hosting service?”

“Which one is better for my new website: MySQL or Oracle?”

etc.

There is maybe at most 1% of cases where the choice is relevant, and there is a real, objective reason to use one over another, based on the precise metrics and studies. In all other cases, it doesn't matter at all. It is totally, completely irrelevant, either because there are no implications¹, or because those implications are too small to be taken in account², or, finally, because it's impossible to predict those implications³.

If you know one thing and not another one, the answer to those questions is easy:

“You can either write the application in C# or Java, both being probably equivalent in your case. Note that I'm a C# developer, so if you choose Java, I would not be able to work on your project and you would need to find another freelancer.”

When you know both technologies, you can't answer that.

In this case, how to explain to the customer that the question he asks is subject to flamewar and has no real consequences on his project?

In other words, how to explain that you've chosen to use one technology rather than an equivalent one for the reasons related to human resources, without giving the impression to be unprofessional or to not care about the project?

¹ Example: Is MySQL better (worse?), performance-wise, compared to Oracle, for a personal website which will be accessed by, oh, let's be optimistic, two people per day?

² Example: for a given project, I was asked to asset if Windows Azure hosting would be cheaper than the hosting of the same application on a well-known ASP.NET hosting provider. The cost revealed to be exactly the same.

³ Example: your customer have an idea of a future application (the idea itself being extremely vague). There is no business plan, no requirements, nothing at all. Just an idea. You are asked if Java is better than C# for this app. What do you answer?


问:
"// ..." comments at end of code block after } - good or bad?
I've often seen such comments be used:

```<code>function foo() {
   ...
} // foo

while (...) {
   ...
} // while

if (...) {
   ...
} // if
</code>```

and sometimes even as far as

```<code>if (condition) {
   ...
} // if (condition)
</code>```

I've never understood this practice and thus never applied it. If your code is so long that you need to know what this ending } is then perhaps you should consider splitting it up into separate functions. Also, most developers tools are able to jump to the matching bracket. And finally the last is, for me, a clear violation to the DRY principle; if you change the condition you would have to remember to change the comment as well (or else it could get messy for the maintainer, or even for you).

So why do people use this? Should we use it, or is it bad practice?

答:
This is largely a holdover from the old days of working in 80x24 character terminal windows, especially if you were using a windowed editor like EVE.  Even now, I do most of my work in a terminal session using vim, and I may split the session into three or four subwindows, so I can only really view a few lines at any one time.  </p>

<p>That said, I never really warmed to the convention, even though it would have saved my bacon on more than one occasion.  I just see it as noise.  If your loops or conditionals are getting that big, yeah, you might want to look into refactoring.    </p>

Body:
This is largely a holdover from the old days of working in 80x24 character terminal windows, especially if you were using a windowed editor like EVE.  Even now, I do most of my work in a terminal session using vim, and I may split the session into three or four subwindows, so I can only really view a few lines at any one time.

That said, I never really warmed to the convention, even though it would have saved my bacon on more than one occasion.  I just see it as noise.  If your loops or conditionals are getting that big, yeah, you might want to look into refactoring.


答:
I would give the customer an objective comparison matrix on the feasibility of using that technology.  For example:

“Which one is better for my new website: MySQL or Oracle?”

In your matrix:

Cost

In House Use

Scalability

Experience/Familiarity

Supportability

Tooling

Already In Use (Deployed)

Development Ease

Development Familiarity

Etc.

Depending on how many items in your matrix, one should quickly come up with score and determines the feasiblity of using that technology versus the other one.  IN some cases MySQL maybe better, in others Oracle.


答:
I think your premise, that the decision is largely arbitrary, is worth questioning. I agree you don't want to end up in analysis paralysis where you have months of committee meetings, but it's worth some consideration. Viewed from a high level, technology choice is rarely arbitrary. It's key to business strategy as it strongly influences where a company can go in the future, and it's the developer's role to guide the company through the decision process.

The specifics of the technology, such as MySQL's use of B-trees versus those of Oracle, or PHP's syntax versus that of ASP.NET, are of course open to much religious debate among programmers and will really come down to your own taste. Since a similar consultant to yourself could easily have a radically different opinion, those things are indeed rather arbitrary. And it's fairly well-established that any developer who's competent in a given technology will do a good job anyway. So the more important issues for the business are not language minutia, but higher-level questions such as:

What's the deployment scenario? Certain technologies lend themselves to a more hands-off approach, especially if there are cloud hosting services like Heroku in place. Some companies will like that, others will need to host themselves, have a stronger presence of system administrators, etc.

What's the project lifetime and scope? PHP, for example, is arguably easier than Java to get a project started, but it is harder to scale and maintain for many years.

What kinds of developers will the technology attract? For Java, you'll more likely get those with enterprise experience. For PHP, you may get more crossover designer or system administrator types. For Node.js, you'll get more front-end and experimental developers, for Haskell, an academic crowd, etc. All stereotypes I know, but it gives the business some clues. Each of these groups have their own cultures, expectations about payment and work environment, and ways of working with each other and the rest of the organisation.

What's the availability of developers? Assuming developers have to be physically present, certain locales have particular ecosystems. In a city full of startups, there will be a lot of Ruby on Rails and PHP developers, in a city full of government departments, there will be a lot of Java/MS, etc. The vast majority of programming languages in the world must be ruled out simply on this basis.

Those are just a few examples. Which factors are most important will depend on the situation, but the main point here is that companies need to consciously adopt the technologies which fit their strategy, culture, and circumstances.


问:
How to deal with tautology in comments?
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

答:
In my own code, I will frequently leave comment tautologies in place, including the particularly egregious ones like:

<?php
// return the result
return $result;
?>
```

<p>... which obviously contribute little in terms of making the code more comprehensible from an explanatory perspective.</p>

<p>In my mind, though, these comments still have value, <strong>if they help to maintain the visual consistency of the color patterns in your syntax highlighter</strong>.</p>

<p>I think of code as having a structure that is very similar to the English language, in that there are "sentences" and "paragraphs" (even though a "paragraph" may consist entirely of a single "sentence"). I usually include a line-break and one-line summary above each "paragraph". For example:</p>

<pre class="lang-php prettyprint-override"><code><?php
//get the id of the thing
$id = $_POST['id'];

//query the things out of the the database
$things = array();
$result = mysql_query("SELECT * FROM Things WHERE `id` = $id");
while ($row = mysql_fetch_assoc($result)) {
    //create a proper Thing object or whatever
    $things[] = new Thing($row);
}

//return the things
return $things;
?>
</code>```

(Ignore the incomplete code, SQL injections, etc. You get the idea.)

To me, the final comment genuinely adds value to the code, simply because it helps to visually delineate one "paragraph" from another by maintaining a consistent coloring scheme.

Title: How to deal with tautology in comments?

Body:
In my own code, I will frequently leave comment tautologies in place, including the particularly egregious ones like:

<?php
// return the result
return $result;
?>

... which obviously contribute little in terms of making the code more comprehensible from an explanatory perspective.

In my mind, though, these comments still have value, if they help to maintain the visual consistency of the color patterns in your syntax highlighter.

I think of code as having a structure that is very similar to the English language, in that there are "sentences" and "paragraphs" (even though a "paragraph" may consist entirely of a single "sentence"). I usually include a line-break and one-line summary above each "paragraph". For example:

<?php
//get the id of the thing
$id = $_POST['id'];

//query the things out of the the database
$things = array();
$result = mysql_query("SELECT * FROM Things WHERE `id` = $id");
while ($row = mysql_fetch_assoc($result)) {
    //create a proper Thing object or whatever
    $things[] = new Thing($row);
}

//return the things
return $things;
?>

(Ignore the incomplete code, SQL injections, etc. You get the idea.)

To me, the final comment genuinely adds value to the code, simply because it helps to visually delineate one "paragraph" from another by maintaining a consistent coloring scheme.


答:
Maybe not the worst but clearly shows the implementers level:

if(something == true)
```</li>
<li><p>If a language has a for loop or iterator construct, then using a while loop also demonstrates implementers level of understanding of the language: </p>

<pre class="lang-cpp prettyprint-override"><code>count = 0;
while(count < items.size()){
   do stuff
   count ++;
}

for(i = 0; i < items.size(); i++){
  do stuff
}
//Sure this is not terrible but use the language the way it was meant to be used.
</code>```

Poor spelling/grammar in documentation/comments eats at my almost as much as code itself.  The reason for this is because code was meant for humans to read and machines to run.  This is why we use high level languages, if your documentation is hard to get through it makes me preemptively form a negative opinion of the codebase without looking at it.

Title: Which things instantly ring alarm bells when looking at code?

Body:
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

Body:
Maybe not the worst but clearly shows the implementers level:

if(something == true)

If a language has a for loop or iterator construct, then using a while loop also demonstrates implementers level of understanding of the language:

count = 0;
while(count < items.size()){
   do stuff
   count ++;
}

for(i = 0; i < items.size(); i++){
  do stuff
}
//Sure this is not terrible but use the language the way it was meant to be used.

Poor spelling/grammar in documentation/comments eats at my almost as much as code itself.  The reason for this is because code was meant for humans to read and machines to run.  This is why we use high level languages, if your documentation is hard to get through it makes me preemptively form a negative opinion of the codebase without looking at it.


答: Explain it in terms they understand - money.  You can tell them you picked X over Y because, even though they both would have been suitable for the project, you are more familiar with X than Y.  And thus you'll be able to deliver the application at a lower cost to them when using X than if it was written using Y.</p>


问:
Books or guides regarding secure key storage and database encryption
I have an idea for a SaaS product I want to create, however, this product will store extremely sensitive data that needs to be encrypted at rest. The trouble is not so much the encryption, but the problem of securely storing the keys so that in the event the server was somehow compromised, the keys couldn't just be recovered and used to decrypt the database.

Are there any decent books to guides regarding database encryption, and in particular secure key storage? This seems to be a less than straightforward topic and something that is difficult to get right. I'm seeing multiple ways to attack such a system, but unable to come up with one that is secure enough to store highly confidential information.

答: The bible is Applied Cryptography by Bruce Schneier, however, I suggest starting with "Secrets and Lies" and "Beyond Fear".</p>


问:
Strategy for backwards compatibility of persistent storage
In my experience, trying to ensure that new versions of an application retain compatibility with data storage from previous versions can often be a painful process.

What I currently do is to save a version number for each 'unit' of data (be it a file, database row/table, or whatever) and ensure that the version number gets updated each time the data changes in some way. I also create methods to convert from v1 to v2, v2 to v3, and so on. That way, if I'm at v7 and I encounter a v3 file, I can do v3->v4->v5->v6->v7.

So far this approach seems to be working out well, but I haven't had to make use of it extensively yet so there may be unforseen problems. I'm also concerned that if the objects I'm loading change significantly, I'll either have to keep around old versions of the classes or face updating all my conversion methods to handle the new class definition.

Is my approach sound? Are there other/better approaches I could be using? Are there any design patterns applicable to this problem?

答: You're doing it right.  You're stamping data with its version, which means you have a definite interpretation of it.  The only open question is how to handle "old" data.  Your choices are essentially between upgrading data where it lives, having your code adapt the data in realtime, or having the code handle multiple data versions.  From 30+ years experience, I can tell you the former is the only sane way to go.  Bite the bullet and write a conversion routine for each step along the history, and run them in sequence.  If you find that a later step obviates an earlier one (e.g., why upgrade the rows in a table if a later step deletes the table?), resist the temptation to short-circuit things unless there is a large, demonstrable performance gain in the update process.


问:
Why Is it better to use unreadable bytes for client server communication?
I'm composing communication lyrics for client-server and what am I thinking about:

"authme username passord" (maybe encrytped)

"accept"

"get archive of H2O from 03.02.2005 to 20.12.2064"

transferring binary structure or "error descrtiption"

why I always need to do something like

0x0FA52FD + CRC

0x0D34423 + CRC

...

I can see some secure reasons but I think it's not the real reason so why I can't use strings in client-server communication?

答:
The Internet has lots of experience with binary and textual protocols.  Textual protocols are the norm, not because "we always do it that way", but because over 40 years experience has shown that textual protocols are significantly easier to work with, and because bandwidth considerations rarely pan out in the long run.

Don't conflate "binary" and "secure".  There's nothing inherently secure about a binary protocol.  Even undocumented binary protocols have been reverse-engineered.  Similarly, there's nothing inherently insecure about a textual protocol.  Security arises from well-thought-out plans against attacks, not from simple obscurity.


问:
Is it safe to install TortoiseSVN on production servers?
Small shop, few production servers, no test or development servers, all Win2k3 WEB based.

There is a need to keep versioned files on one of the machines. Is TortoiseSVN safe against exploitability, does it need extra hardening? Any known license problems, incompatibilities?

答:
It's not good practice. Every bit of software increases the scope for vulnerabilities. Generally, you should have as little software on your server as possible. Also, unless you're sending traffic over HTTP, it involves another port bring opened.

Licensing-wise, you're fine, it's open source.

I think a much better approach would be to version the files on the development machine before they are deployed to the server.