问:
What is the advantage of little endian format?
Intel processors (and maybe some others) use the little endian format for storage.

I always wonder why someone would want to store the bytes in reverse order. Does this format have any advantages over the big endian format?

答:
When only storage and transfer with variable lengths are involved, but no arithmetics with multiple values, then LE is usually easier to write, while BE is easier to read.

Let's take an int-to-string conversion (and back) as a specific example.

```<code>int val_int = 841;
char val_str[] = "841";
</code>```

When the int is converted to the string, then the least significant digit is easier to extract than the most significant digit. It can all be done in a simple loop with a simple end condition.

```<code>val_int = 841;
// Make sure that val_str is large enough.

i = 0;
do // Write at least one digit to care for val_int == 0
{
    // Constants, can be optimized by compiler.
    val_str[i] = '0' + val_int % 10;
    val_int /= 10;
    i++;
}
while (val_int != 0);

val_str[i] = '\0';
// val_str is now in LE "148"
// i is the length of the result without termination, can be used to reverse it
</code>```

Now try the same in BE order. Usually you need another divisor that holds the largest power of 10 for the specific number (here 100). You first need to find this, of course. Much more stuff to do.

The string to int conversion is easier to do in BE, when it is done as the reverse write operation. Write stores the most significant digit last, so it should be read first.

```<code>val_int = 0;
length = strlen(val_str);

for (i = 0; i < length; i++)
{
    // Again a simple constant that can be optimized.
    val_int = 10*val_int + (val_str[i] - '0');
}
</code>```

Now do the same in LE order. Again, you'd need an additional factor starting with 1 and being multiplied by 10 for each digit.

Thus I usually prefer to use BE for storage, because a value is written exactly once, but read at least once and maybe many times. For its simpler structure, I usually also go the route to convert to LE and then reverse the result, even if it writes the value a second time.

Another example for BE storage would be UTF-8 encoding, and many more.

Body:
When only storage and transfer with variable lengths are involved, but no arithmetics with multiple values, then LE is usually easier to write, while BE is easier to read.

Let's take an int-to-string conversion (and back) as a specific example.

int val_int = 841;
char val_str[] = "841";

When the int is converted to the string, then the least significant digit is easier to extract than the most significant digit. It can all be done in a simple loop with a simple end condition.

val_int = 841;
// Make sure that val_str is large enough.

i = 0;
do // Write at least one digit to care for val_int == 0
{
    // Constants, can be optimized by compiler.
    val_str[i] = '0' + val_int % 10;
    val_int /= 10;
    i++;
}
while (val_int != 0);

val_str[i] = '\0';
// val_str is now in LE "148"
// i is the length of the result without termination, can be used to reverse it

Now try the same in BE order. Usually you need another divisor that holds the largest power of 10 for the specific number (here 100). You first need to find this, of course. Much more stuff to do.

The string to int conversion is easier to do in BE, when it is done as the reverse write operation. Write stores the most significant digit last, so it should be read first.

val_int = 0;
length = strlen(val_str);

for (i = 0; i < length; i++)
{
    // Again a simple constant that can be optimized.
    val_int = 10*val_int + (val_str[i] - '0');
}

Now do the same in LE order. Again, you'd need an additional factor starting with 1 and being multiplied by 10 for each digit.

Thus I usually prefer to use BE for storage, because a value is written exactly once, but read at least once and maybe many times. For its simpler structure, I usually also go the route to convert to LE and then reverse the result, even if it writes the value a second time.

Another example for BE storage would be UTF-8 encoding, and many more.


问:
Fast set indexing data structure for superset retrieval
I am given a set of sets:

```<code>{{a,b}, {a,b,c}, {a,c}, {a,c,f}}
</code>```

I would like to have a data structure to index those sets such that the following "lookup" is executed fast: find all supersets of a given set.

For example, given the set {a,c} the structure would return

```<code>{{a,b,c}, {a,c,f}, {a,c}}
</code>```

but not {a,b}.

Any suggestions? Could this be done with a smart trie-like data structure storing sets after a proper sorting?

This data structures is going to be queried a lot. Thus, I'm searching for a structure that might be expensive in build but rather fast to query.

UPDATE: I have finally used a prefix Trie as described in the paper "A New Method to Index and Query Sets", by Jorg Hoffmann and Jana Koehler.

答:
If the different kinds of elements are limited, you could build a table of flags. Each set is an array of bools where each position represents a word. The words are kept in a list, where their index is equal to the index of the bool that represents them. To find the supersets, you compare the values of the flags; to be a superset, every position with value True in the subset should contain True in the candidate set. All this can be done in O(n), which is not bad in my opinion.

Python:

WORDS = (
    'a',
    'b',
    'c',
    'f',
)

def values_to_words(s):
    return set(WORDS[i] for i, v in enumerate(s) if v)

def words_to_values(s):
    return tuple(True if w in s else False for i, w in enumerate(WORDS)) # Unoptimized

SETS = tuple(words_to_values(s) for s in (
    ('a','b',),
    ('a','b','c',),
    ('a','c',),
    ('a','c','f',),
))

def get_supersets(q):
    values = words_to_values(q)
    is_superset = lambda s: all(v1 or not v2 for v1, v2 in zip(s, values))
    return (values_to_words(s) for s in SETS if is_superset(s))

print list(get_supersets(('a','c',)))
# [set(['a', 'c', 'b']), set(['a', 'c']), set(['a', 'c', 'f'])]
```

Be of course careful not to build your own SQL engine. You could in fact use one for this pattern.

Also, you'll find https://stackoverflow.com/questions/1263524/superset-search useful - I just found it.

ContentLicense: CC BY-SA 3.0

Body:
If the different kinds of elements are limited, you could build a table of flags. Each set is an array of bools where each position represents a word. The words are kept in a list, where their index is equal to the index of the bool that represents them. To find the supersets, you compare the values of the flags; to be a superset, every position with value True in the subset should contain True in the candidate set. All this can be done in O(n), which is not bad in my opinion.

Python:

WORDS = (
    'a',
    'b',
    'c',
    'f',
)

def values_to_words(s):
    return set(WORDS[i] for i, v in enumerate(s) if v)

def words_to_values(s):
    return tuple(True if w in s else False for i, w in enumerate(WORDS)) # Unoptimized

SETS = tuple(words_to_values(s) for s in (
    ('a','b',),
    ('a','b','c',),
    ('a','c',),
    ('a','c','f',),
))

def get_supersets(q):
    values = words_to_values(q)
    is_superset = lambda s: all(v1 or not v2 for v1, v2 in zip(s, values))
    return (values_to_words(s) for s in SETS if is_superset(s))

print list(get_supersets(('a','c',)))
# [set(['a', 'c', 'b']), set(['a', 'c']), set(['a', 'c', 'f'])]

Be of course careful not to build your own SQL engine. You could in fact use one for this pattern.

Also, you'll find https://stackoverflow.com/questions/1263524/superset-search useful - I just found it.


问:
How can I get my own encryption algorithm tested?
I've just developed a block cipher symmetric-key algorithm and I am using it in some of my products. I want to put it to real test.

How would one go about entering their encryption algorithm into an international encrytption contest?

答:
I want to put it to real test.

Use it to control access to non-trivial amounts of money, in public. Wait some time. If you still have your money, it's strong enough.


问:
Android Application(Client) and Server(C#.Net) Communication
I am confused which approach to choose - Poll (which waste battery), GCM or any other approach which suits best?

Scenario is: my client is Android and server is C#.Net. Server sends Invitation to client. Server can choose whom to send (Regionwise, Particular, To All). Client can accept or reject the invitation.which sends result back to server

答: The Google Cloud Messaging will be definitely nicer to the users, because not only the application does not need to keep a foreground service (which implies status bar icon) running to keep a network connection open, it does not even need to be started at all. The GCM subsystem will start it itself.</p>


问:
When to open source a project under development?

Possible Duplicate:

  Is it OK to push my code to GitHub while it is still in early development?

I've been working on a hobby project for a few months now; it's clocking in at over 15000 source lines of code. A number of people have expressed interest in joining development, and I have full intentions of going open source, since it would not be feasible for me to complete the project alone. I'm just not sure when to open-source it.

For context, I've notice many successful open source projects, such as the Linux kernel, had considerable work done before they were open-sourced.

In my case, I'd been planning on open-sourcing it after I complete all the underlying libraries and overall architecture. Is this a mistake; should I just release it right now?

I'm worried that since certain critical underlying components haven't been finalized, if people build a large codebase around them, it will be very difficult to change or fix things later. On the other hand, it's a very large project that will require multiple developers to complete in a reasonable time.

So when is the right time during development to go open source?

Preferably, I'd like to hear from some folks who have started their own projects.

答: You should open source early (yesterday) and commit often.</p>

OwnerDisplayName: QuasarDonkey

OwnerDisplayName: Skylar Saveland


答:
I started JStock - Free Stock Market Software few years ago. My advice is, Open source when you get started. Don't wait!

By open sourcing it early, you will have the following expectations.

You are given chance to publish your project at a high traffic website like SourceForge.net. (I would recommend SourceForge over GitHub, as it focuses on publishing open source project. GitHub is more focusing on code collaboration) It helps to gain visibility. Your project starts to attract more end users, without too much cost.

End users will be more forgiving, and trust your software, if it is open source, compared to closed source. With that, you will attract more end users.

There are some catcha. Open source early doesn't mean you will attract more contributors. Working on open source doesn't have direct monetary reward. What open source contributors are really looking for is

A software platform, with good number of end users, which can demonstrate their software development skill. Open source developers don't work for free either. They need something in return. If not monetary, they need recognition and honor. An open source project with good number of end users able to deliver those.

Hence, attract end users first with a reasonable good product, then attract good contributors to build amazingly great product.

Title: When to open source a project under development?

Body:
Possible Duplicate:

  Is it OK to push my code to GitHub while it is still in early development?

I've been working on a hobby project for a few months now; it's clocking in at over 15000 source lines of code. A number of people have expressed interest in joining development, and I have full intentions of going open source, since it would not be feasible for me to complete the project alone. I'm just not sure when to open-source it.

For context, I've notice many successful open source projects, such as the Linux kernel, had considerable work done before they were open-sourced.

In my case, I'd been planning on open-sourcing it after I complete all the underlying libraries and overall architecture. Is this a mistake; should I just release it right now?

I'm worried that since certain critical underlying components haven't been finalized, if people build a large codebase around them, it will be very difficult to change or fix things later. On the other hand, it's a very large project that will require multiple developers to complete in a reasonable time.

So when is the right time during development to go open source?

Preferably, I'd like to hear from some folks who have started their own projects.

OwnerDisplayName: Yan Cheng CHEOK


答:
It seems you're searching for a standard Information Retrieval algorithm. Instead of giving you the answer (which depends on factors such as frequency and cardinality of terms and the number of documents, the type of queries asked), I forward you to the excellent introductory treatise on the topic called: Introduction to Information Retrieval: http://nlp.stanford.edu/IR-book/html/htmledition/irbook.html

Probably the chapter 'Index Construction' contains an algorithm suitable for your needs.

Title: Fast set indexing data structure for superset retrieval

Body:
I am given a set of sets:

```<code>{{a,b}, {a,b,c}, {a,c}, {a,c,f}}
</code>```

I would like to have a data structure to index those sets such that the following "lookup" is executed fast: find all supersets of a given set.

For example, given the set {a,c} the structure would return

```<code>{{a,b,c}, {a,c,f}, {a,c}}
</code>```

but not {a,b}.

Any suggestions? Could this be done with a smart trie-like data structure storing sets after a proper sorting?

This data structures is going to be queried a lot. Thus, I'm searching for a structure that might be expensive in build but rather fast to query.

UPDATE: I have finally used a prefix Trie as described in the paper "A New Method to Index and Query Sets", by Jorg Hoffmann and Jana Koehler.


问:
thick client migration to web based application
This query is related to application design the technology that I should consider during migration.
The Scenario: I have a C#.net Winform application which communicates with a device. One of the main feature of this application is monitoring cyclic data(rate 200ms) sent from the device to the application. The request to start the cyclic data is sent only once in the beginning and then the application starts receiving data from the device until it sends a stop request.
Now this same application needs to be deployed over the web in a intranet.
The application is composed of a business logic layer and a communication layer which communicates with the device through UDP ports.

I am trying to look at a solution which will allow me to have a single instance of the application on the server so that the device thinks that it is connected as usual and then from the business logic layer I can manage the clients. I want to reuse the code of the business layer and the communication layer as much as possible.
Please let me know if webserives/WCF/ etc what i should consider to design the migration.

Thanks in advance.

答:
Personally I would be tempted to modify the existing program and add a web request handling layer to it. The application would then run on the server and maintain a constant connection to the device. A website could then be constructed which communicates with this application via AJAX/Json calls every 200ms to retrieve the latest data from the application.

While creating a web service may work, it would run as a separate instance per user request, depending on how many users are trying to connect to the device, this may overload the device with multiple connections.

I faced a similar dilemma recently with an application I developed, except my decision was further enhanced by the fact I needed to receive data even when no users were connected. Also I had previously written a Web server DLL that I could plug straight in.


答:
I'm going to go against the consensus here and suggest that now is not a good time for open-sourcing this project.

The reason why is that the project is quite clearly not yet in a "fit for stated purpose" condition; if you open-source it now you will be inundated with requests along the lines of "component XYZ is not working, fix it please".  It doesn't really matter if you've stated this up-front, you're still going to get these, and they're going to detract from whatever work you're currently completing on it.

Other requests you're going to get will be of the "plz send codez" variety, as well as a fair mixture of "your project is great but it would be better if it included component ABC and this is so easy to implement it'll only take you 5 minutes and everything will be better then" (ha!) - you'll get these anyway even after you release a full product, but they will be especially annoying now.

None of this is denying that open-sourcing early is a good thing; just that for your project where it's currently at, that boat has already sailed.  So if you're already past the point at which you can open-source as early as possible, then it's better to hold off a little more.

Options available to you now would include battening down your hatches and bringing things to a reasonable working state before going public (but be careful this doesn't take too long), doing some source-code-only releases, or inviting interested parties (and you've already got some - that's great!) to join in a private development effort until such a time as it's ready to go public.


问:
Is using something other than XML advisable for my configuration file?
I have a small tool I'm designing which would require a configuration file of some sort. The configuration file in my case is really more of a database, but it needs to be lightweight, and if needed the end-user should find it easily editable. However, it also will contain a lot of things in it. (depending on certain factors, could be 1Mb or more)

I've decided I'd rather use plain ol' text, rather than trying to use SQLite or some such. However, with using text, I also have to deal with the variety of formats. So far, my options are

XML

JSON

Custom format

The data in my file is quite simple consisting for the most part of key-value type things. So, a custom format wouldn't be that difficult... but I'd rather not have to worry about writing the support for it. I've never seen JSON used for configuration files. And XML would bloat the file size substantially I think. (I also just has a dislike of XML in general).

What should I do in this case?

Factors to consider:

This configuration file can be uploaded to a web service(so size matters)

Users must be able to edit it by hand if necessary(ease of editing and reading matters)

Must be able to generate and process automatically (speed doesn't matter a lot, but not excessively slow)

The "keys" and "values" are plain strings, but must be escaped because they can contain anything. (unicode and escaping has to work easily)

Multiple configuration files. Basically, each config file is tied to one "project"

答:
A "properties" file is good for key/value as the format itself is key/value.  It's simply 1 line per key/value. The first = sign in the line splits the key and value.

It will be smaller than an equivalent XML file since the only formatting is the "=" separator and the newline character. In an XML file the markup could take as much space as the content itself. It could literally mean the difference between a 1MB and 2MB upload. Compression helps but you are still ahead if you start small.

Existing libraries can handle access to property files. But it's so trivial you can make your own in a few minutes. Bells and whistles in under an hour.

```<code>IP=11.22.33.44
BuildNumber=5.02.004
MaxFrameRate=50
</code>```

Body:
A "properties" file is good for key/value as the format itself is key/value.  It's simply 1 line per key/value. The first = sign in the line splits the key and value.

It will be smaller than an equivalent XML file since the only formatting is the "=" separator and the newline character. In an XML file the markup could take as much space as the content itself. It could literally mean the difference between a 1MB and 2MB upload. Compression helps but you are still ahead if you start small.

Existing libraries can handle access to property files. But it's so trivial you can make your own in a few minutes. Bells and whistles in under an hour.

IP=11.22.33.44
BuildNumber=5.02.004
MaxFrameRate=50


问:
Is it a common practice to minimize JavaScript usage when building a website?
I've been a web developer for almost 10 years and I've gotten into the habit of trying not to use JavaScript whenever possible. I'm not talking about building web apps here, but database driven websites.

Is this a good/respected approach?

答:
"Database driven websites" is the key to the answer. There are two ways to create websites, and the amount of Javascript allowed depends on which one you're using, really. You can build:

Content-centric websites. In the first case, the magic words are "progressive enhancement"; limit javascript to redundant functions that can be supplied with classic accesss to content through plain HTTP.

Web applications. For applications, you're using the web as a software platform instead. Apps rely on some assumptions on the software available - modern browsers, latest versions of popular javascript libraries, desktop accesss with mouse and/or tablets with multi-touch.

The web as a software platform

Minimum accesss requirements are OK if you're really building an application - you target some specific platform to gain advanced features that couldn't be built otherwise. It's just like developing for Python or Java or .Net. Don't let buzzwords like HTML5 and the promise of "run anywhere" fool you; you can have portable code between devices only as long as the whole platform is supported on those. Any change to the development stack, and the software will break.

Thus the price to pay is that you're following a moving target, as new versions of the platform are released; you'll have to play catch-up to keep your app working as the platform evolves. The only benefit you get is a semi-universal delivery mechanism for your app that doesn't depend on packages nor application stores; but you lose the main feature that differentiates the web from previous networked computer systems.

The web as content delivery

Content-centric websites are a different beast; they are in the tradition of the classic World Wide Web. Content is loosely interpreted by the client, which can made any desired transformation before presentation. The site is expected to be accessed by an ecosystem of different platforms that may or may not support the current standards:

Mobile devices supporting less than the latest and most expensive bells and whistles

Old browser users who can't (at the enterprise) or don't know (at home) how to update

Future versions of popular engines that deprecate their old APIs

You'll lose them all if you require the current breed of javascript, which is always evolving. In this context, broken javascript that prevents accessing the content is a sin.

Everyone saying that "javascript usage should be minimized" is advocating this style. It's OK to include some JS, mind you, but all functions should be redundant with basic accesss to content that could be achieved server-side:

Data entry validation

AJAX updates of content for quickest navigation (that nevertheless works without JS)

The benefit to this approach is less testing and upgrading required, and more shelf-life. The first static webpages from 20 years ago are still browsable in any web client, but the first web applications are forever broken. If your site has any archiving value at all, you'll benefit in the long run from using the web as a content delivery system, not an application platform.


问:
Software patterns for frameworks
I am currently doing some research about software patterns and about architectural patterns for frameworks specifically.

Google is not really showing off for this topic, so I am curious which patterns would you consider specificially important for the architecture of frameworks? I am focusing on frameworks for web, mobile and desktop software, such as Rails, UIKit, etc.

答:
I'm hard pressed to think of a GoF design pattern that's either inappropriate for use in a framework or most appropriate for use in a framework. Patterns and frameworks are orthogonal issues -- if a pattern is useful, it can be useful in a framework. Conversely, if a pattern is useful in a framework, there's no reason that it can't also be put to use outside a framework.  Frameworks are just a way to package your code.

Patterns and frameworks are both meant to be reusable, so there's some common purpose in the two ideas and frameworks often make heavy use of patterns. Indeed, a great deal of the benefit of understanding design patterns is that it makes it much easier to understand new frameworks as you encounter them. That said, I don't know of any design patterns that are intended specifically for frameworks.

Title: Software patterns for frameworks


答:
My first question would be "why are you building a framework?"

Surely there has to be something sub-optimal, missing, broken, or otherwise defective in the existing frameworks even if that something is just that they don't look at the world the way you do (and there is nothing wrong with building a framework to solve a problem domain "your way"--that can lead to a lot of illumination in how to approach problems both for the authors and the users of the framework).

Assuming there is an answer to that question (if there isn't, there is no reason to build the framework at all), then the answer should guide your architecture decisions. There is a lot of wrong-headedness in terms of how design patterns are viewed. They are no panacea. They do not solve problems. They are a way for software engineers to discuss common implementation strategies--but the implementation strategy is derived from what is being implemented.

Perhaps a good way to make this more clear would be to break down some common design patterns.

For an MVC framework, the guiding pain point is that you want a clear division of code--a good separation of concerns. Maintainability and refactorability. For an ActiveRecord ORM, the idea would be to abstract away as much of the database dealings as possible, allowing the users to think in purely object-oriented terms. And so on.

Title: Software patterns for frameworks

Body:
I am currently doing some research about software patterns and about architectural patterns for frameworks specifically.

Google is not really showing off for this topic, so I am curious which patterns would you consider specificially important for the architecture of frameworks? I am focusing on frameworks for web, mobile and desktop software, such as Rails, UIKit, etc.


问:
How to manage product backlog/user stories
We're about to start a new project using Agile (using TFS), and I have a couple of "good practice" questions regarding the product backlog:-

When we first start adding users stories, is it a good idea to put them in (say) a "Backlog" iteration, or just leave their iteration blank? Obviously when the time comes to start work on a US it would be moved into the appropriate iteration backlog.

When breaking an epic down into smaller USs, would I simply close the original epic, as it's no longer required? Or should I create the new USs as children of the epic? (it's then someone's responsibility to close the epic once all child USs have been completed).

Lastly, should the product backlog list all USs regardless of status, or only those that have not been started (i.e in my proposed "Backlog" iteration)?

I realise these questions aren't life-or-death, but it would be nice to know how other people manage their product backlogs so we can organise things properly from the start.

答:
An iteration in Agile isn't so much a container for user stories as it is a minature software release following the SDLC for a small and easily manageable amount of time.

The Backlog is not an iteration, it is essentially a container for user stories, epics and tasks that you do not currently have the time to address in the current sprint.  In planning ahead for the next sprint you should re-evaluate the current priorities of items in the backlog, versus the level of effort to deliver each in determining what belongs or does not belong in the next iteration.

Do not plan more than one iteration ahead

This is not Agile and defeats the whole purpose of iterative development in its entirety.  Business needs and requirements are typically too volatile to make long term plans on strict software requirements, which is why we keep ourseleves focused only on the current iteration, and the one that we will work on as soon as we deliver this iteration.

If management wishes for long term estimates (based on the current backlog as it exists at this moment) then one can look at the size of the current backlog items to give an estimated date of completion.

Your question about what iteration to put the backlog stories into tells me that you are probably trying to plan your iterations too far ahead.

When breaking an epic down into smaller USs, would I simply close the original epic, as it's no longer required? Or should I create the new USs as children of the epic? (it's then someone's responsibility to close the epic once all child USs have been completed).

An epic should be accepted when it satisfactorily achieves its stated business goal.  This is essentially when all of its children user stories have been completed and accepted.


问:
Demonstrate bad code to client?
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.

答:
Code structure, style, technical debt are one thing that - at least initially, until the client trusts you - you're going to need to live with.

Security vulnerabilities are another matter.

Personally, I would do an estimate based on the work required using the existing structure and style while making it clear that there are significant issues with the codebase. I'd raise the security implications separately: do a demonstration of a hack on the database to drive the point home during a meeting.

I had great joy doing this with a previous client with a loyalty gift card system when I put £5000 on "my" card and had him check the card on his till.

Title: Demonstrate bad code to client?


问:
What is the politically correct way of refactoring other's code?
I'm currently working in a geographically distributed team in a big company. Everybody is just focused on today's tasks and getting things done, however this means sometimes things have to be done the quick way, and that causes problems... you know, same old, same old.

I'm bumping into code with several smells such as: big functions pointless utility functions/methods (essentially just to save writing a word), overcomplicated algorithms, extremely big files that should be broken down into different files/classes (1,500+ lines), etc.

What would be the best way of improving code without making other developers feel bad/wrong about any proposed improvements?

答:
Part of the solution is changing the way people see the code. Any piece of code belongs to the whole team, not just the person who wrote it. If you start to think of the code base this way, you won't have to think about who wrote the original code, because it belongs to everyone.

Creating this sort of environment goes a long way to making feel people comfortable changing any part of the code.


问:
Should I expect my team to have more than a basic proficiency with our source control system?
My company switched from Subversion to Git about three months ago.  We had weeks of advance notice prior to the switch.  Since I'd never used Git before (or any other DVCS), I read Pro Git and spent a little time spinning up my own repositories and playing around, so that when we switched I'd be able to keep working with minimal pain.  Now I'm the 'Git guy' by default.

With a couple of exceptions, most of my team still has no idea how Git works.  For example, they still think of branches as complete copies of the source code, and even go so far as to clone the repo into multiple folders (one per branch).  They generally look at Git as a scary black box.

Given the fundamental nature of source control in our daily work (not to mention the ridiculous amount of power Git affords us), I'm of the opinion that any dev who doesn't achieve a certain level of proficiency with it is a liability.

Should I expect my team to have at least some understanding of how Git works internally, and how to use it beyond the most basic pull/merge/push operations?  Or am I just making something out of nothing?

答:
Professionalism would naturally dictate that a developer become familiar with their team's standard tools, even if they are new and unfamiliar (or even unwanted).

However, a few things in your post give me pause.

We had weeks of advance notice prior to the switch.

Weeks? Swapping out source control is a big deal. There should have been months of notice leading up to a change like that.

With a couple of exceptions, most of my team still has no idea how Git works.

So, your company switched to a source control system that few, if anyone, understood at the time?

Unless there is some other context, it seems like the whole move was ill thought out (the move, not the choice--I'm a huge git fan).


答:
Remember that the client is going to you for help with maintaining their application. It is your job as a professional to point out any issues you find with their application. The client likely has no idea these issues exist and they should be made aware of them. Explain these issues in a manner that they can understand and let them decide how they want to proceed.

Use real world examples to illustrate these issues, such as a car breaking down or a washing machine needing repair. To point is to use examples they are already familiar with. For explaining SQL injection, I would simply demonstrate what that is and why it's an issue.

In the end you want to convey that you care about the success of the application you are being asked to work on.

Title: Demonstrate bad code to client?

Body:
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.


问:
Alternative to "inheritance versus composition?"

Possible Duplicate:

  Where does this concept of “favor composition over inheritance” come from?

I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go.

I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes.

For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?

答: I think the difference between the two things is in their intent. Is the class you are writing really meant to be used as replacement / specialisation of its Base class or is it just using some functionality? If the First Case is true you should go with inheritance. If the latter is true go for composition. In my experience using inheritance where composition would be appropriate creates a more complex, less understandable and meanigful codebase. </p>


答:
A codebase in a distributed team environment is a lot like Wikipedia; as they say, "If you don't want your posts to be ruthlessly edited by the rest of the world, don't submit it".

If there's a better way for a particular piece of code to be written, and you need it written in that way, then write it that way. If someone complains, listen to the complaint, but if it's primarily along the lines of "that's MY code", explain that he is a member of a team that is working on the codebase as a whole, and nobody really gets to claim ownership. Also point out that, legally speaking due to the paperwork he signed when he was hired, it's not "his" code, it's the company's, and you also work for that company.

Now, there can be legitimate gripes about changing the "interface" of code (the way code objects appear and interact with other code) without first consulting the team. If someone has a working copy they're making their own set of large changes to, heavily based on the older interface, and you come in and change that under their nose, they have a lot of refactoring to do. There's a simple solution to that; send a team e-mail saying "hey I need to change this code, is anyone working on something locally that would break the build if I changed it?". Wait a few minutes, and if anyone raises an objection, work it out in a more personal channel of communication. If not, refactor away.

Title: What is the politically correct way of refactoring other's code?

Body:
I'm currently working in a geographically distributed team in a big company. Everybody is just focused on today's tasks and getting things done, however this means sometimes things have to be done the quick way, and that causes problems... you know, same old, same old.

I'm bumping into code with several smells such as: big functions pointless utility functions/methods (essentially just to save writing a word), overcomplicated algorithms, extremely big files that should be broken down into different files/classes (1,500+ lines), etc.

What would be the best way of improving code without making other developers feel bad/wrong about any proposed improvements?


问:
Why is NoSQL faster than SQL?
Recently I was asked:

Why is NoSQL faster than SQL?

I didn't agree with the premise of the question... it's just nonsense for me personally. I can't see any performance boost by using NoSQL instead of SQL. Maybe SQL over NoSQL, yes but not in that way.

Am I missing something about NoSQL?

答: You're right, it would be nonsense to state that in a blanket statement. Which is probably the whole point; instead of a single answer, the interviewer is probably expecting you to reply with questions to help you figure out what the context of the problem is (what kind of data, how much of it, in what operating environment etc), the particular NoSQL solution. They'll try to find out how you analyse problems and along the way get an idea how much you know about the different solutions that are out there.</p>

Title: Why is NoSQL faster than SQL?


答:
We've been introducing Git where I work and there has naturally been resistance. It was for a new project so we are now maintaining two repositories.

Part of the problem is that people won't see the benefits of switching to a different SCM when the one they've been using works for them. It helped when we sat down with our team for a couple one-hour sessions where we would just show use cases from our projects and how Git made it easier. For example, the things that helped us:

Local branches to encourage experimentation

Git bisect to easily track down bugs

frequent commits without interrupting others

Fast switching between branches

etc. Each of these solved a problem that we had encountered with our previous SCM and so people could appreciate Git more.

The other thing is that you can't expect people to go off and read books about it because very few will. Maybe they need to get work done, have other responsibilities, or any number of reasons.

So, as the 'Git expert' you have to sit down and make it as easy as possible for people to use it. They want to be writing code, not messing with their SCM system.

Git's CLI is cryptic and trivial problems (to you and I) will block people from working. Here's what happened on our team (mind you, these are fairly competent developers):

Git with SSH on Windows was a common issue.

People would pull, merge, but not push the merge. So the graph would be a huge confusing mess

Performance problem on Windows made "git status" take 15 seconds

Couldn't figure out how to pull a new branch. They would do a "git checkout -b " which would branch off of whatever they were working on

EGit in eclipse had an overwhelming menu. Ended up telling everyone to use command line at first

Based off the previous item, merging and setting up git mergetool

Confused about differences between "git add" and "git commit" and "git push."

We still get some resistance but people can definitely see the benefits. It is vital to have a few Git people for guidance and be willing to help out. Also I would avoid teaching cool things like reset/rebase/--amend/etc. because most people will use Git like SVN, it's better to let them discover it if they so desire.

Title: Should I expect my team to have more than a basic proficiency with our source control system?

Body:
My company switched from Subversion to Git about three months ago.  We had weeks of advance notice prior to the switch.  Since I'd never used Git before (or any other DVCS), I read Pro Git and spent a little time spinning up my own repositories and playing around, so that when we switched I'd be able to keep working with minimal pain.  Now I'm the 'Git guy' by default.

With a couple of exceptions, most of my team still has no idea how Git works.  For example, they still think of branches as complete copies of the source code, and even go so far as to clone the repo into multiple folders (one per branch).  They generally look at Git as a scary black box.

Given the fundamental nature of source control in our daily work (not to mention the ridiculous amount of power Git affords us), I'm of the opinion that any dev who doesn't achieve a certain level of proficiency with it is a liability.

Should I expect my team to have at least some understanding of how Git works internally, and how to use it beyond the most basic pull/merge/push operations?  Or am I just making something out of nothing?


问:
C++ - Constructor or Initialize Method to Startup

Possible Duplicate:

  Avoid having an initialization method

I want to determine when to do non-trivial initialization of a class. I see two times to do initialization: constructor and other method.  I want to figure out when to use each.

Choice 1:

Constructor does initialization

```<code>MyClass::MyClass(Data const& data) : m_data()
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
   // cleans up here
}
</code>```

Choice 2:

Defer initialization to an initialize method

```<code>MyClass::MyClass() : m_data()
{}

MyClass::Initialize(Data const& data)
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
    // cleans up here
}
</code>```

So to try and remove any subjectivity I want to figure out which is better in a couple of situations:

Class that encapsulates a resource (window/font/some sort of handle)

Class that composites resources to do something (a control/domain object)

Data structure classes (tree/list/etc.)

[Anything else you can think of]

Things to analyze:

Performance

Ease of use by other developers

How error-prone/opportunities for bugs

[Anything else you can think of]

答:
Always use the constructor unless there is a good reason not to. It's "The C++ Way" (tm).

Regarding your points to consider:

Constructors are always more or equally efficient as having code outside in separate init() functions.

Constructors tend to be easier to use for other developers. Without looking at your source or docs, I would expect new YourClass(stuff) to work. Having to call a yourClass->init(stuff) afterwards is not enforced by the compiler and it's an easy slip up to make.

As per number 2 - a lot of caveats about constructors are fleshed out by compilers for you, in terms of order of initialization etc. When you move things out of constructors you face the danger of reinventing the wheel, sometimes as a square.


问:
Is it okay to use a language that isn't supported by your company for some tasks?
I work for a company that supports several languages: COBOL, VB6, C#, and Java. I use those languages for my primary work, but I often find myself coding some minor programs (e.g. scripts) in Python because I find it to be the best tool for that type of task.

For example: an analyst gives me a complex CSV file to populate some DB tables, so I use Python to parse it and create a DB script.

What's the problem?

The main problem I see is that a few parts of these quick and dirty scripts are slowly gaining importance and:

My company does not support Python

They're not version controlled (I back them up in another way)

My coworkers do not know Python

The analysts have even started to reference them in emails ("launch the script that exports..."), so they are needed more often than I initially thought.

I should add that these scripts are just utilities that are not part of the main project; they simply help to get trivial tasks done in less time. For my own small tasks they help a lot.

In short, if I were a lottery winner to be in a accident, my coworkers would need to keep the project alive without those scripts; they would spend more time fixing CSV errors by hand, for example.

Is this a common scenario? Am I doing something wrong? What should I do?

答:
I suppose that you're not in a position to decide (or else you would not ask the question).  What does your boss think about this issue?  You should talk to him and try to convince him that Python is the way to go...

Of course, the issue is about what will happen when you leave.  Not being able to maintain the code is probably a reason that's good enough to stop using Python.  Or you can start educating your colleagues to this language...

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
Use an Init() when you have to supply parameters to your object that you don't/can't know when you create the object.

You could also use it if your class's functionality could take along time to construct, e.g. initialising the playback of a video file involves file parsing, video codec matching and loading, audio codec matching and loading, resource acquisition. In this case you might to break up the creation into asynchronous steps so your user's app remains responsive and also allows then to cancel the operation.

Title: C++ - Constructor or Initialize Method to Startup

Body:
Possible Duplicate:

  Avoid having an initialization method

I want to determine when to do non-trivial initialization of a class. I see two times to do initialization: constructor and other method.  I want to figure out when to use each.

Choice 1:

Constructor does initialization

```<code>MyClass::MyClass(Data const& data) : m_data()
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
   // cleans up here
}
</code>```

Choice 2:

Defer initialization to an initialize method

```<code>MyClass::MyClass() : m_data()
{}

MyClass::Initialize(Data const& data)
{
    // does non-trivial initialization here
}

MyClass::~MyClass()
{
    // cleans up here
}
</code>```

So to try and remove any subjectivity I want to figure out which is better in a couple of situations:

Class that encapsulates a resource (window/font/some sort of handle)

Class that composites resources to do something (a control/domain object)

Data structure classes (tree/list/etc.)

[Anything else you can think of]

Things to analyze:

Performance

Ease of use by other developers

How error-prone/opportunities for bugs

[Anything else you can think of]


答:
You're sort of looking at it backwards.  Composition isn't preferred because of some unseen benefit of composition, it's preferred because it avoids the drawbacks of inheritance.  Inheritance adds the significant benefit of substitutability.  However, that benefit comes with the significant cost of tight coupling.  Inheritance is the strongest coupling relationship possible.  If you don't need the substitutability, the coupling cost isn't worth it.

Your restricted version of inheritance addresses its other cost, a loss of encapsulation, but does nothing about the much more significant cost of coupling.

Title: Alternative to "inheritance versus composition?"

Body:
Possible Duplicate:

  Where does this concept of “favor composition over inheritance” come from?

I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go.

I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes.

For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?


答:
One option that no one seemed to touch on is instead of constructing then Init, using a private constructor and a static Initialize function. Indeed this is a powerful technique because in theory the static initialize function might construct different subclasses based on context.

I would choose one or the other. As others have mentioned, having a constructor followed by an Initialize call is error prone.


答:
Non-techies aren't idiots (for the most part).  They can understand a technical argument if you keep it high-level enough.  Pick a task you thought should be simple, and walk them through why it's not.

I expected this change to be one word in one file.  The most likely
  place to change it seemed to be here, but when I changed it there, it
  only worked in one place, and it broke these 7 other places.  When I
  fixed one, it broke two more places, causing a domino effect, so a
  change I thought should have taken 10 minutes ended up taking 2 hours.
  That's just one example.  There are a lot more unexpected 2 hour tasks in there.

Title: Demonstrate bad code to client?


问:
What is the best C++ source code to read for a beginner?
I'm trying to improve my c++ coding technique by reading c++ source code. Which open source project would you recommend? Is the code of Boost C++ Libraries a good one?</p>

答:
Try reading the C++ PDF.
It's free, and I learned C++ from it, even though I had no other programming experience, and I'm only 14. Amazing.</p>


问:
Licensing Options for a dead project
I'm currently working on a project  where the original author informally told me that he didn't want to publish the source.

Since then, the original author has gone leaving me to be the sole developer on the project. I've tried to contact him several times about making the project open source so that I can have other developers assist me but he is not responding to any communications.

I'm not planning on trying to make money of the software, I just want a general license that allows me to put the code on GitHub or BitBucket so that other people in the community can assist me with the development.

Can I do this since he is gone and not responding to any form of communication? Is there a time period I need to wait? I know what I asking for is legal advice, I just have no idea where to start looking to find the answer so I decided to start here.

答:
Can I do this since he is gone and not responding to any form of communication?

No. Changing and/or issuing a license can only be done by a unanimous decision by all copyright holders. If you can't reach him, then he can't give his consent, ergo you cannot change the license.

Note: there are exceptions to this rule. If there is a decision that benefits the vast majority of copyright holders, but a small minority of copyright holders objects without any reasonable arguments, then the majority can sue the minority for compliance. For example, if translating a movie and releasing it to an international audience will likely generate a great amount of revenue, but a couple of minor extras object to their lines being translated, the rest of the copyright holders can force them to comply. (Although it might be easier to just cut their scenes!)

Is there a time period I need to wait?

70 years after his death his portion of the code will become public domain, i.e. you won't need a copyright license anymore because there is no copyright.

I know what I asking for is legal advice, I just have no idea where to start looking to find the answer so I decided to start here.

The person you are looking for is called a "lawyer".

All of this applies to German Author's Rights Law. You didn't specify a jurisdiction, so I am assuming the one I am most knowledgeable about.

Title: Licensing Options for a dead project


答:
I started this as a comment, because at first I thought it was an aside, but it probably really isn't.

I would fully document everything that you feel is should be redesigned, and why (what happens if they don't make the change), and an estimate on fixing the issue.  I would be particularly meticulous with anything you perceive as a security risk.

I would do this before touching any code, and make sure that your client has a copy of this report, preferably with some kind of timestamp.  It may take some time, but it will also cover you if one of these security risks ever comes to fruition.  Even better if you can get something signed that says they received the document.

Sure, you can point to source control of the original code you inherited if it ever does happen, but it will be much easier to point to this document and say, in a more professional manner, "See?  I told you so."

This document can be the launching point of further discussions, and it may even be used by your client to get the "right people" to give the permission to make some or all of the changes.

That being said, once the client undestands the risks, grin and bear it if they say to do the work anyway, or walk away.

Title: Demonstrate bad code to client?


答:
I would recommend any of Google's open source C++ code, such as the following:

Google Test

Protocol Buffers

Chromium

Advantages of using Google code:

It's written to high standards and is peer reviewed (unlike some open source code).

It has good developer documentation (which makes it easier to pick up and understand).

It uses some moderately advanced C++ techniques (and thus is good for learning).

It's probably easier to understand than Boost because it doesn't rely so much on advanced template metaprogramming and preprocessor metaprogramming and isn't weighed down as much with countless compiler compatibility hacks and special cases.

The Google C++ Style Guide that Google's C++ code uses is generally good, but it does have some fairly unusual bits (such as some of their naming guidelines or their disallowing exceptions), so keep in mind that their C++ code will differ in those respects from what you'll see in the field.

Title: What is the best C++ source code to read for a beginner?

Body: I'm trying to improve my c++ coding technique by reading c++ source code. Which open source project would you recommend? Is the code of Boost C++ Libraries a good one?</p>


答:
Ideally, just use a constructor.  It is usually a bad thing when a constructor returns a not-quite-usable object.

However, as people have pointed out, you often have situations where the data needed to fully initialize an object is not available at construction time. You can deal with a situation like that by using the Builder Pattern.

Let's say you have a class Foo, which requires some non-trivial initialization. You create a class FooBuilder, which simply stores all the data needed to initialize an object of Foo.  FooBuilder would have a member function (aka method) Foo  *build() or maybe Foo build(), which you would call when all the data is collected.  It might also have setters for various items that need to be passed to Foo's constructor, and it might supply defaults for some of those.

This solves the problem of "late initialization" without requiring an initialize() member function. For example, if you need to create an array of Foo objects before you have all the stuff to initialize them, you would instead create an array of FooBuilders.  Then you would call the appropriate setters on the builders as data becomes available. Finally, when all the data are safely stored in the builders, you create an array of Foo's, by calling build() on each builder.


问:
Forbidding or controlling "Hidden IT..." Who should write and maintain ad-hoc software applications?
Bigger companies usually have the problem, that it is not possible to write all programs employees want (to save time and to optimize processes) due to a lack of staff and money.

Then hidden programs will be created by some people having (at least some) coding experience (or by cheap students/interns...). Under some circumstances these applications will raise in importance and spread from one user to a whole department.

Then there is the critical point: Who will maintain the application, add new features, ...? And this app is critical. It IS needed. But the intern has left the company. No one knows how it works. You only have a bunch of sources and some sort of documentation.

Does it make sense to try and control or forbid application development done ad-hoc outside of the IT department (with the exception of minor stuff like Excel macros)?

答:
There almost aways is a valid need for these special tools, be they applications or spreadsheets.  An IT department has two choices.  They can be enablers or disablers.  In my experience, the disablers lose because they get in the way of valid business needs and become a common enemy. Enablers on the other hand genuinely help a business.

This does not mean that department funded development should be given free reign.  Some requirements should be enforced, such as the following:

All code must be regularly committed to a version control system run by IT.  IT should freely create accounts and directories to make this possible.  IT may even want to provide some instruction.

Anything involving PII (Personally Identifiable Information), authentication, authorization, cryptography, data protected by law, or data the business deems critical must involve and be approved by a consultant from IT.  IT/the consultant should provide assistance, libraries, etc to properly protect the business while enabling app development.

Primary databases should be protected.  Depending on the database, read access should be relatively easy to get and write access harder.  IT may need to provide accounts, logging, or auditing.

Enabling has many benefits.

IT learns more about meeting the needs of their clients.  This leads to better prioritization and sharing.

IT is seen as a friend and a benefit, rather than a problem.

Real business needs are met.

Business data is adequately protected because IT was involved, preventing the need for back doors.

Deparment tools are not lost due to turnover and can more easily be moved into IT, if needed.


答:
GIT is a just tool to do a job, and one of it's biggest problems is that many GIT evangelists expect all GIT users to become under the bonnet experts understanding the finest points of how it works. This is GIT's biggest weakness - to use it you need to know how it works. There are no recipes with GIT, you are expected to be a GIT expert or not use it. It's great that you read Pro-GIT your organization needs a "goto" GIT guru ( or two ) to maximize the investment in it, because not every developer wants to become a GIT Guru - and that is OK.

The team need to know how use GIT (In fact they only need to know how to use the parts of GIT that the workflow requires them to use), not how GIT works. It is detrimental to expect every developer to know every detail about every tool they use. If you have not got a recipe book that supports your workflow, you have not deployed GIT, you have dumped it on the developers.

I don't give a monkeys how GIT works, as long as I know how to make git work for me.


答:
I like to use analogies the client can relate to.  The amount of work I put in upfront in winning the job would depend on the amount of money the client was intending to spend ($100 is far different from $20,000).  Notice I said "intending".  Your personal estimate of the value involved doesn't mean much if you don't get what you're asking.

In your situation - again depending on the money - I might draw a box with one line coming out from each side and say to the client "This is how you visualize the software now.  Data goes in one end and comes out the other, all looks nice and clean and simple".  "This is what you think the software looks like on the inside" and then draw a third line connecting the two lines inside the box.

Then I'd draw another box just like the first with the input and output lines on the outside, except this time I'd say "Here's what the software really looks like inside the box right now."  and then to connect the two lines this time I'd draw a random pile of spaghetti mess, possibly with breaks and joins and scribbles.

Finally I'd say, "Now what you're asking me to do is this..." and draw a simple shape inside the first box  perhaps a small half circle touching the line and then say "but to do that, I'd have to do this..." and draw a tornado looking kind of spiral shape around the line and continue ... "in order to get around all this....." and point to the spaghetti in the other box.

I would think that would drive the point home in about 2 minutes time.  If they insist you do it anyway, then document it as others mention above.

Title: Demonstrate bad code to client?


答:
Yes.

No matter what tool the "company" has decided on, your development team should spend some time learning how to properly use the tool.  Nothing hurts productivity more than a bunch of developers afraid or ignorant of a tool.  If they are using it wrong or working against it, problems will arise and as the go to guy, you will be tasked with cleaning up the mess.

Git is a tough transition for many, so a mandatory sit down training session may be in order.  This should help hammer out a lot of the issues people are having.


答:
Review and Annotate the Code

DO review, preferably using a code review tool. (Otherwise e-mails, but... meh).

DO justify your remarks and comments.

DO NOT bitch about it.

Fix the Code

DO fix it:

if they don't have time to do it themselves,

after having discussed it with the author, or formally told some members about your desire to go about fixing some things.

DO test for things you fix (preferably with unit and integration tests)

DO justify yourself.

DO prioritize:

At first Start with a few minor things to get into the habit and show that you are careful;

But then DO absolutely fix the big things first rather than hundreds of small things.

DO NOT fix unclear code paths that you do not fully comprehend.

DO NOT fix untested code paths that you may break unknowingly.

DO NOT fix code paths blindly. Simple fixes are simple, but mistyping a symbol or having a brainfart and inverting a boolean condition happens all the time. Test your stuff.

DO NOT bitch about it, again.

DO NOT annoy others and preach self-righteously.

DO NOT fix irrelevant or inconsequential problems (at first). If it doesn't matter too much, you're likely to have better things to do.

DO NOT sacrifice consistency.

In essence, DO NOT become this annoying guy we all know who just changes whitespaces or brace styles based on a personal preference but without regard for the consistency with the rest of the codebase, and who even goes so far as to break builds while fixing minor code violations by introducing simple but deeply hidden bugs.

Communicate

DO contact the authors.

DO discuss your changes with others (not necessarily authors).

DO request review for your own changes from others; this:

shows humility,

invites others to jump onto the bandwagon,

shows that this is a fluid process.

DO establish rules and conventions with your co-workers to avoid this issue expanding and crippling the codebase over time.

DO tackle the matter quickly.

Ask

DO ask. Rather than saying "I'm fixing this because X", ask directly "why did you do it this way, and how do you think we can improve it?" If they come up with something better, then start with that and work together on something even better. If they don't, then make a suggestion. If they come up with something better, or don't see why it was wrong, then explain and ask the second question again.

Make it a Team Effort

Your team is more likely to jump onto the bandwagon if they actually take part to this. If this is a large project with a somewhat aging codebase, it's likely that they also dislike the state of rot the code is in, but maybe never bothered to do something about it.

If you have the power (or support of the ones who do), it can be a good idea to organize small sprints dedicated to enhancing code quality. Setting up code analyzers to detect code smells and monitoring their steady decrease while you refactor is also fairly motivational for a team.

Of course, that might be a bit harder for remote teams, as it's a bit more difficult to convey enthusiasm about such things without actually working together.

It pretty much all comes down to that.

Semantics

Also, don't confuse "politically correct" with "diplomatic":

The former is about beating around the bush to not offend people while saying something most likely to be negative.

The latter is about tackling issues while not offending people because there might be some emotional context.

They're very different things.

Related Questions

How Can I Tactfully Suggest Improvements to Others Badly Designed Code?


答:
Here's an analogy I've used (though I do not vouch for it's effectiveness): Imagine their website is a physical machine, like a mechanical printing press that somehow accepts input.

They probably think of the machine as having on component that does X and another that does Y.  In reality, it's 20 or so mostly-similar machines.  Some of them no longer do anything, all of them attempt to preform functions the others do already and no one besides the previous consultant has ever seen anything exactly like them before.

"See this gizmo here that parses the post variables and then sends
  this component down a rabbit-hole of if-elses?  There isn't just one
  of these, there is one of these in every page (or whatever), some of
  them sanitize the input and some don't (or all don't) and without
  reading the entire thing I can't know which."

Title: Demonstrate bad code to client?


答:
Talk First!

There is no point in making changes that someone-else is just going to get upset about and undo.  It's a waste of your political capital and your time.  If you are the boss and can enforce new standards, then talk to your team about the new standards and implement them.  If not, talk your co-workers and maybe your boss before making changes.

If you talk to each team member one-on-one, you can decide how much political capital you are willing to spend before lighting yourself on fire in front of the whole team.  You may still want to have a team meeting as public acknowledgement of the private consensus you achieved through one-on-one meetings, and as a chance for people to comment on the new coding policies before implementing them.

With a group consensus, everyone is tasked with making the code better.  It's not just you against the world.  If agreement is unattainable, then you won't waste your time fighting the inevitable.


答:
Some great suggestions here on how to convey and communicate this to the client. Hopefully they will pay off for you.

Major red flag here!

If the client asks you not to make any changes other than what you've agreed to (HTML and CSS) I'd pass on this project and withdraw my bid.

Even with a written and well communicated overview of all of the flaws and security issues, the potential liability is just too great for me to be comfortable with. Even if the client never took any legal action or demanded fixes after a hack or breach; your name and reputation are still attached to the work!

You may well lose far more than you stand to gain.

Title: Demonstrate bad code to client?


答:
There are so many details that you don't mention in your question that could have an impact on how you could proceed with this. Best bet is to talk with an intellectual property attorney and get their input.

Your solution may be as simple as small filing fee in your local small claims court. But only an attorney can tell you for sure.

Title: Licensing Options for a dead project

Body:
I'm currently working on a project  where the original author informally told me that he didn't want to publish the source.

Since then, the original author has gone leaving me to be the sole developer on the project. I've tried to contact him several times about making the project open source so that I can have other developers assist me but he is not responding to any communications.

I'm not planning on trying to make money of the software, I just want a general license that allows me to put the code on GitHub or BitBucket so that other people in the community can assist me with the development.

Can I do this since he is gone and not responding to any form of communication? Is there a time period I need to wait? I know what I asking for is legal advice, I just have no idea where to start looking to find the answer so I decided to start here.


问:
What is the correlation between programming language and experience/skills of their users?
I'm sure there is such a correlation, because

experience and skill leads good programmers to picking languages that are better for them, in which they're more productive, and

working in a language forms how programmers think and influences their methods and skills.

Is there any research or some statistical data of this phenomenon?

Perhaps this is not a purely academic question. For example, if someone is starting a new project, it could be worth considering a language (among other criteria of course) for which there is a higher chance of finding or attracting experienced programmers.

Update: Please don't fixate on the last paragraph. It's not my intention to choose a language based on this criterion, and I know there are other far more important ones. My interested is mostly academic. It comes from the (subjective) observation and I wonder if someone has researched it a bit. Also, I'm talking about a correlation, not about a rule. Sure there are both great and terrible programmers in every language. Just that in general it seems to me there is a correlation.

答:
My interested is mostly academic. It comes from the (subjective) observation and I wonder if someone has researched it a bit. Also, I'm talking about a correlation, not about a rule.

Firstly, no I am not aware of any such research.

The problem is that it is would be hard to conduct this kind of (objective) research in a scientifically meaningful way.

How do you objectively measure an individual programmer's "experience" and "skill"?  Self reporting is obviously going to give you unreliable answers, so you have to (somehow) test these things.

How do you do it in a way that doesn't conflate these two measures with the other variables - specifically, the number of languages known and/or used?

How do you do this in a way that involves real experienced programmers?  (You can't use the typical undergraduate CS student test cohort ... who are typically not experienced in any meaningful way.)

If you were a serious academic, you may be able to figure out a way to do this kind of thing.  But you would first need to justify the expense of conducting the research to a funding body.  And they would probably ask "What is the value of knowing the answer?".  And that is a hard question to answer ... IMO.


答:
It's tough to describe what to do in a situation like this.  Most people who are good at refactoring already know the answer, and don't have to ask the question.  I'm guessing you are still learning, and if that's the case then you're in for a longer, character-building journey.

Start small.  Boil the frog, not the ocean.

You should not be refactoring just to refactor.  You will certainly learn a lot faster by randomnly refactoring things, but your environment is not nurturing in that way.  Instead you're 'changing my code for no good reason', and it'll only serve to get you branded as a divisive person - a jerk.  I would wager you're already learning about this, and that's why you asked.

Refactor code that is actively in your way.  "I changed this because I had to fix a bug/add a feature."  Once that is going okay for you, once they understand that this is how you work, switch to refactoring code that's arguably in the way.   "I changed this because it was easier to fix a bug/add a feature." This is when you start getting into the Campsite Rule, and explaining it to others, and why you think this is the way THEY should work (pretty please with sugar on top).  Look for collaborators, people who'll let you fiddle with their code to make it shinier.

Just those three tasks will keep you busy for a good long while.

Some day, in the far flung future, you may get to explain the Broken Windows phenomenon, but I recommend you don't get your hopes up.  Don't assume this team will ever get there, for your own sanity.  Instead you should just plan to save that conversation for your next job, or even the one after that.  Be an informed consumer during the interview process.  It'll help you avoid this scenario, and they'll see you're serious about your craft.

Good luck!


答:
The accepted answer sums up the legal position.  If he owns substantial copyright, you can only change the license with his explicit permission ... in most legal jurisdictions.  (IANAL, TTAL)

My advice would be to consider starting again from scratch.  You could possibly use salvageable bits that you can prove that you own copyright for.  This sounds wasteful, but a project may actually benefit from a ground-up rewrite.  Provided that you resist scope creep, you should be able to build the new version quicker than the old one, and you get the chance to revisit a lot of design decisions with the benefit of hindsight ...

It would help if you have people interested in pitching in effort from day 1 of your rewrite.

Title: Licensing Options for a dead project


问:
Is it Considered Good SQL practice to use GUID to link multiple tables to same Id field?
I want to link several tables to a many-to-many(m2m) table.

One table would be called location and this table would always be on one side of the m2m table.

But I will have a list of several tables for example:

Cards

Photographs

Illustrations

Vectors

Would using GUID's between these tables to link it to a single column in another table be considered 'Good Practice'? Will Mysql let me to have it automatically cascade updates and delete? If so, would multiple cascades lead to an issues?

UPDATE

I've read that GUID (a hex number)
Generally takes up more space in a database and slows queries down. However I could still generate 'unique' ids by just having the table initial's as part of the id so that the table card's id would be c0001, and then Illustrations be I001. Regardless of this change, the questions still stands.

答:
a GUID is usually represented as a hexadecimal string, but it's more appropriate to store it in a binary format (rather than varchar) if space is a consideration; it usually is in an RDBMS.

There's nothing wrong with using a GUID as a foreign key, or primary key, for that matter. If you ensure that your tables have the correct indices, it shouldn't affect performance at all.


答:
By default databases don't support this kind of relationship (as you've drawn it).  I have used it before without enforcing the foreign key that goes to multiple different tables.  I had to take care of all the relationships in code.  Generally it's considered a bad idea.

The "right" way is to have a CardLocation, PhotographLocation, etc. tables each with its own Guid primary key (e.g. CardLocationId).  If you happen to need to hang common data off each relationship, then you create another table called LocationRelationship and you make the primary key of the relationship tables (e.g. CardLocationId) also a foreign key that references the LocationRelationshipId.  So, each record in CardLocation has a corresponding record in LocationRelationship.  That way you can enforce all the relationships in the relational database.  Unfortunately it's a lot more complicated.

Edit

After thinking a bit more, the other way to do it is to have Card, Photograph, etc., all derive from a common base (let's call it Locatable).  So you create a new table called Locatable with primary key LocatableId.  Then CardId is both a primary key and should also be a foreign key that references LocatableId, and PhotographId is a foreign key to LocatableId as well.  Then you just have one many-to-many table called LocatableLocation with foreign keys to LocatableId and LocationId.

That's fewer tables and seems to imply the intent better.

Title: Is it Considered Good SQL practice to use GUID to link multiple tables to same Id field?

Body:
I want to link several tables to a many-to-many(m2m) table.

One table would be called location and this table would always be on one side of the m2m table.

But I will have a list of several tables for example:

Cards

Photographs

Illustrations

Vectors

Would using GUID's between these tables to link it to a single column in another table be considered 'Good Practice'? Will Mysql let me to have it automatically cascade updates and delete? If so, would multiple cascades lead to an issues?

UPDATE

I've read that GUID (a hex number)
Generally takes up more space in a database and slows queries down. However I could still generate 'unique' ids by just having the table initial's as part of the id so that the table card's id would be c0001, and then Illustrations be I001. Regardless of this change, the questions still stands.


答:
I don't see anything inherently wrong with this design, but you need to note that you are implicitly associating a Card, Illustration, Photograph and Vector by having them share a key.

Your location will have multiple sets of attributes. Each set will contain zero or one Card, Illustration, etc. Are these Card and Illustration any more related than any other card or illustration that is linked to the location? If not then your schema does not model your data accurately.

What you've got here isn't a 'many-to-many' relationship. The Location can correctly have many Vectors (and so on), but each Vector can only have one Location. That's just a many-one relationship. If that is what you need, then you can do it far simpler: the Location table has the primary key, and the other tables simply have a foreign key back to the Location table, without a unique constraint on that foreign key column.

Finally, if you are collecting a number of attributes about a location, why not just have a LocationAttribute table which stores

LocationId

AttributeTypeId

Value (varchar or whatever)

and then a defined set or table of attribute types - 1 = Card, 2 = Photograph and so on.


答:
How can I explain to my client just how bad this code is?

Perhaps you can use an analogy like plumbing in a house that over time, after fixes and remodels, becomes so fickle and coupled that when fixing one thing, affects and possibly breaks something else that then needs fixing and there's just no way for you to know all the places that this will occur.

It's my word against the previous consultant, so how can I actually give simple, concrete examples that a non-technical client would understand?

You're right, it's word against whatever visual the previous consultant has created in their heads. My suggestion is to do just what you're asking, give simple, concrete examples. Since this is a redesign, show how an HTML fragment defined in the compiled code is displayed with the rest of an HTML page and how changing that affects or doesn't, the rest of the page. Perhaps that same compiled code renders markup after applying some "business" rule. Show the difference.

This is a hard and VERY common problem. Good luck with it.

Title: Demonstrate bad code to client?


答:
I have comments on your current data model.

1 - You should have a separate m-m to each relationship and not 1 table as you currently show in the model. One reason is that an occurence of the m-m table could be for one or more FK values. A cascade delete may delete several rows in the m-m table that hold FK values you don't want to delete.

2 - Your relationship from the one-side to junction table is probably optional from the one-side not mandatory as you model it. Optional relationship causes a nullable FK to be created and this prevents cascading from taking place by removing the non-null value and replacing it with null  (if this is what you want).

3- Your relationship from the m-m to the Location table should probably not be mandatory as this would delete locations on the delete of a Card for example. You may want this to be optional (see 2 above).

4 - Do you really need m-m? Are you sure? Your business is not clear from the question, but maybe you only need a 1-m. Prove it to yourself by an example before you model it.

5 - You may avoid having 4 tables that would probably have the same columns by creating 1 Resource table with a type column. The type would be:Card, Illustration, etc. This way you save 3 tables and 3 junction tables.

6 - It is not good to use plural table names. Microsoft used to do this, but it is not good! Prefer singular table names. Plural names are good for naming collections.

Now as per your question about GUID, you can use GUID but it will make testing very difficult. It would also make finding a row using GUID a nightmare for the user if that is an expected function in your system. Performance may suffer for huge databases. Consider using int type when possible. Coding Horor - GUID as a PK Pros and Cons.


答:
Be honest and be direct.

But most importantly do not take on a job that will not meet your expectations.  Most people do not realize that a contractor can fire a client, they can and should if the job is more trouble than it is worth.

Title: Demonstrate bad code to client?


问:
How to show code samples in an interview?
There have been questions similar to this, but my question is HOW exactly do you showcase your code when going to an interview? Do you show screenshots, or do you bring the actual code? Do you take the whole project with you, or just that bit of code? </p>

答:
Strange as it may seem most interviewers are not interested in seeing your code! The guy interviewing you is probably a project leader or from a similar career stream and may not even understand any code you show him.

Even if the interviewer is a techie and understands the code, he/she does not know how long you took to write it, does not know if you really covered the spec/use case, does not know how you tested and debugged the code, in reality the interviewer cannot even be sure its "your" code.

If the interviewer is really interested in how you code then he/she will set you a coding, code comprehension or debugging task and see how you cope. Otherwise you can safely assume they do not want to know.


答:
Proficient vs. Git-mania

A term like basic proficiency may mean different things to different people.  A lot of people seem to have git-mania (not that there is anything wrong with that).  Many of us have been burned really badly by our own and other people's sloppiness with source control.

Why it Matters (So Much)

Source control tools are critical because misuse can slow not just one person, but a whole team. Misusing Git should be less problematic than misusing SVN, CVS, and other systems. Historically, inept use of systems that locked files was particularly problematic, and companies hired discrete build teams so that when someone got into trouble, there was a fluent expert who did almost nothing but source control who could come cure the wound to the repository. This partially explains some of the passion you find behind git.

What does basic proficiency look like?

Some concrete criteria include:

Without reference to documentation:

Can add files, commit changes, push and pull updates.

Can view status and revision activity.

Can branch and merge quickly and without introducing errors.

Can use checkout appropriately.

Create commit comments that meet the group's criteria for comments.

Diff changes between working copy and archive.

With documentation:

Add users and credentials for local repo.

init a local repo.

Administer remote repo.

Configure ignored files, generate PKI public/private key pairs.

Move and delete files.

Use bisect to find the change that introduced a particular bug.

A solid mental model of git and the code being managed is critical to avoid mistakes.

What would you add for advanced proficiency / expertise?

Fluent use is essential for developers and possibly some other members of your team.  Tools like Git are overhead and should be learned to a level where they can be nearly automatic.  Minimizing time and distraction produced by using git commands that are repeated thousands of times per year has high value.

There will always be some members of your team who will be power users and use almost every command with almost every option.  My recommendation is that team members be encouraged to keep learning git (and other tools) until the ROI for learning drops below the value of doing something else on the project, with the main limitation being keeping on pace with assigned burn down items from the current sprint.


问:
What are some good End-User Programming solutions you have seen?
End-User Programming is where regular end users, i.e. non-programmers, are able to customize a program, or create a new one, with minimal training or instruction.

App Inventor for Android is one recent example, but perhaps the most popular example of end-user programming is the spreadsheet.

What examples of end-user programming have you seen used, or believe to be useful? What's the philosophy of the system? What challenges remain?

答:
I've heard good things about Kodu, from Microsoft. It was developed to allow kids to build their own games without already knowing how to program.
http://fuse.microsoft.com/project/kodu.aspx</p>


问:
Assignment of roles in communication when sides could try to cheat
Assume two nodes in a peer-to-peer network initiating a communication.

In this communication, one node has to serve as a "sender", another as a "receiver" (role names are arbitrary here).

I'd like the nodes to assert either role with approximately equal probability. That is, in N communications with various other nodes a given node would assume the "sender" role roughly N/2 times. Since there's no third-party arbiter available, nodes should agree on their roles by exchanging messages.

The catch is that we can encounter a rogue node which would try to become the "receiver" in most or all cases, and coax the other side to always serve as a "sender".

I'm looking for an algorithm to assign roles to sides of communication so that no side could get a predetermined role with high probability. It's OK for the side which is trying to cheat to fail to communicate.

答:
It so happens that's a variation on a problem for which someone asked a question in the game programming site: "Can adversarial agents flip coins?"

The solution to that problem would also solve this problem nicely.


答:
The arrogance of Geeks!

In many cases business users can use the tools to do things that the IT people don't understand. This is not because they are inherently bad but because they know the business, how it works and how they would like it to work.

For example a software company developed an application to optimize (for cost) access to market data feeds. As an afterthought they provided an Excel plugin so users could access the latest share price via a spreadsheet.  Fast forward one year and nearly every trader in the company I worked for had one or more incredibly complex spreadsheets to support their trading strategy. Every now and then they would have a problem with the macro's and ask one of the IT guys for help, most refused (and they wonder why the business hates us!). I however had a go and while I could fix technical problems with various function parameters and circular references I can honestly say I did not have the slightest clue what the whole spreadsheet actually did. Not because they were badly put together or poorly programmed but because I did not have the knowledge or experience to appreciate the subtlety of what the traders were trying to achieve. Furthermore I would estimate a 5 man year plus IT project to replicate the functionality of one of these spreadsheets in a "proper" programming language as a standard IT project.

Title: Forbidding or controlling "Hidden IT..." Who should write and maintain ad-hoc software applications?

Body:
Bigger companies usually have the problem, that it is not possible to write all programs employees want (to save time and to optimize processes) due to a lack of staff and money.

Then hidden programs will be created by some people having (at least some) coding experience (or by cheap students/interns...). Under some circumstances these applications will raise in importance and spread from one user to a whole department.

Then there is the critical point: Who will maintain the application, add new features, ...? And this app is critical. It IS needed. But the intern has left the company. No one knows how it works. You only have a bunch of sources and some sort of documentation.

Does it make sense to try and control or forbid application development done ad-hoc outside of the IT department (with the exception of minor stuff like Excel macros)?


答:
Explain and possibly demonstrate the flaw

When it's your word against his, everything you say could just be hot air as far as they're concerned. Once you show them how their app can be abused via SQL injection, then suddenly you're a person to be trusted. You're going to need credibility in order to renegotiate. And this is enough of a game-changer to give it to you.

Be charitable with respect to your predecessor

That doesn't mean pretend the mistakes aren't there, but if you come across condescending then you lose credibility. Don't say a word about the programmer except perhaps to give him the benefit of the doubt. Focus on the code, not the coder. Making them feel like you're the "good guy" will give you a lot more leeway in negotiations. And "good guys" never say mean things. When explaining existing security mistakes (such as SQL injection vulnerabilities) to the client, I prefer to say something like this:

Web application security is a rapidly-evolving field. Many of the development tools and techniques that people learn even today evolved before most of these exploits were well-understood. In order to stay ahead of security developments, you have to follow the field very closely and occasionally even change your whole development style. Most programmers don't do this.

There we go. Not a word of evil spoken about the developer; he's just "most programmers" which means he's in pretty good company. And now you've demonstrated that you're not "most programmers" which give you a bit more credibility and perhaps a reason for them to pay you more money.

Negotiate a new arrangement

Once the client understands that his app is open to abuse by the public, he's going to want it to be fixed. You are probably the person he's going to ask to fix it. You may or may not want that job, so think it over carefully before you talk to them.

At the very least, you want more time to finish the work they've already given you. You've set them enough off-guard with the vulnerability stuff that they probably won't hold you to your original estimate. But make sure the client knows what you are and are not going to be fixing as part of this arrangement.

Typically the developer (you) would prefer to redo the whole thing from scratch. And in cases like this, that might even be an option. But even then, the client is going to want something that can keep his business running until the new app is built. This means that even though you're starting over, you're probably still going to have to update the old app a bit.

Title: Demonstrate bad code to client?


问:
Python Forgiveness vs. Permission and Duck Typing
In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking).  In regards to enforcing duck typing in Python, is this

```<code>try:
    x = foo.bar
except AttributeError:
    pass
else:
    do(x)
</code>```

better or worse than

```<code>if hasattr(foo, "bar"):
    do(foo.bar)
else:
    pass
</code>```

in terms of performance, readability, "pythonic", or some other important factor?

答:
In python you often get better performance doing things the Python way. With other languages, using exceptions for flow-control is generally regarded as a terrible idea because exceptions typically impose an extraordinary overhead. But because this technique is explicitly endorsed in Python, the interpreter is optimized for this type of code.

As with all performance questions, the only way to be certain is to profile your code. Write both versions and see which one runs faster. Though in my experience, the "Python way" is typically the fastest way.


问:
ISO 12207: Verification of integration and Unit test validation
I have received comments from the supervisor reviewing my thesis. He asked two questions I cannot answer right now:

If ISO 12207 says under "Integration verification" that it "checks that components are correctly and completely integrated into a system", how this can be verified without testing, if all testing is validation? How without testing can I know that system is integrated correctly and fully?

If unit testing is validation, how does it match the ISO definiton of validation "that requirements for intended use were fulfilled" if its so low level?

答:
There's a reason ISO standards have the reputation of being impractical beaurocratic nonsense. Theoretically, it's possible to check that the artifacts that represent the components are all present, complete and configured the way they should be, by inspecting directories, file contents, perhaps comparing checksums, all without actually running the system. In practice, that's a lot of work and does very little to prove that the system actually works. The closest thing that is done in practice is to check that the automated build script has not produced an error. Perhaps the solution to the puzzle is that ISO 12207 was written to cover integration processes that are not automated (in which case you better have a reason why it cannot be automated, otherwise automate that damn build already instead of wasting time on ISO standards).

Requirements can be very low level, e.g. business rules.