问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
This depends wildly on the situation, the bug, the customer, and the company. There is always a trade-off to consider between correcting the implementation and potentially introducing new bugs.

If I were to give a general guideline to determining what to do, I think it'd go something like this:

Log the defect in tracking system of choice. Discuss with management/coworkers if needed.

If it's a defect with potentially dire consequences (e.g. your example #2), run, scream, jump up and down till someone with authority notices and determine an appropriate course of action that will mitigate the risks associated with the bug fix. This may push your release date back, save lives, wash your windows, etc.

If it's a non-breaking defect, or a workaround exists, evaluate whether the risk of fixing it outweighs the benefit of the fix. In some situations it'll be better to wait for the customer to bring it up, since then you know you aren't spending time fixing/retesting things when it's not 100% required.

Mind you, this only applies when you're close to a release. If you're in full development mode, I'd just log the defect so it can be tracked, fix it, and call it done. If it's something that takes more than, say, half an hour to fix and verify, I'd go to the manager/team lead and see whether or not the defect should be fit into the current release cycle or scheduled for a later time.


问:
SS7(M3UA, SCCP, TCAP, MAP) Stack
I'm building an open source SMSC from scratch; it's almost finished, The SRI and the forwardSM operations are working, but I still have few things to do for the receiving part.
I've built the SS7 stack already, but I'm using DB for saving the TCAP transactions IDs to be updated later to get/generate responses.
My approach is this: I created memory table (heap table), saved the TCAP TID in the database, then compared the received TCAP TID with the TIDs saved in the database and then decide whether to end the TCAP session or continue.

What is the best way to implement it? I'm thinking of doubly linked list that holds the TCAP TID. Am I going towards the right direction, or should I use another technique other than database or D-linked list? Should I leave it as it is, and let the database do the job for saving the TIDs?

Please note that I'm using SCTP implementation available on Linux (lsctp) as a transport protocol, the language I'm using is C and the DB is MYSQL.

答:
Your question about appropriate choice of data structure doesn't provide quite enough detail about the problem you are trying to solve.   Questions I would have asked in-person when trying to help you include:

How many active sessions do you expect on average and maximum?  That is, what's the N-value we need to worry about for the asymptotic complexity of operations?

What are your response latency and memory consumption constraints?

What is the relative mix of add/remove/query operations?

Can you make a reasonably reliable estimate of which order TIDs will arrive in?  (If yes, most operations on our data structure will be at the beginning or end, with little need for searching operations)

Do you know for sure that all the TIDs you are holding will eventually receive an update?  (Alternative: some items in your in-memory data structure correspond to TIDs you will never see again, because you're not always guaranteed to see an "end-session" event).

Not knowing these things (I'm not familiar with the application domain or the "size" if your planned system) I can only make what I think are reasonable guesses, but please forgive me if I guess wrong.

I'm going to guess:

Many; allow the resulting data structure to fill memory if necessary.

Latency requirements are in the 1ms-100ms range, meaning that we should ideally avoid disk accesses - in this case, avoidable database operations.  Memory consumption requirements are much vaguer but let's assume we can't use a sparse data structure (for example a hash table).   The rationale here is that if we have some amount of memory, there are probably other kinds of data it's more useful to keep in it than this information (again, if I knew more about your application domain this would help...)

add:remove:query ratios are close to 1:1:1.

Assume we can't predict the TID arrival order

Assume that we can't be sure that we'll see all sessions neatly closed (so we need to adopt a data structure which allows some kind of separate housekeeper process to occasionally delete stale TIDs).

If these guesses are more or less right, I'd probably use a heap.  Heaps are denser than linked lists and much denser than hash tables.  Each heap entry would contain the TID as the key and whatever other payload data your have (you didn't say; but if there is no additional payload, that's fine too).

Using a heap means that all the operations (insert, delete, lookup) are O(log(N)).   If queries are much more common than insert/delete, then we should consider paying memory to get speed (for example using a hash table; the operations are O(1) but more memory is used).  Contrariwise, if your data structure might get very large, you should consider using a B-heap instead of a regulat binary heap, because it's kinder to the virtual-memory system.  See You're Doing It Wrong by Poul-Henning Kamp, which describes a cache system with some (rather small) degree of similarity to what you're doing.

If your heap is represented as an array, you may have trouble growing it beyond the initial size of the array.  Using the traditional scheme of doubling the size of the array when it fills will amortize the overhead of the copying operation so that we can maintain logarithmic performance.   But it would mean that occasionally, one of the insert operations will take much, much longer than others.   The other property of a heap is that most implementations are designed for single-threaded use.  If either of these two issues are going to be a problem for you, consider using a balanced tree instead of a heap.

ContentLicense: CC BY-SA 3.0

Title: SS7(M3UA, SCCP, TCAP, MAP) Stack


问:
How does team development work?
This is a pretty generic question but one I've been wondering about for a while: is there a standardized, generally accepted, or even just systematic way that people write code as a group?

For example, in a project written in C++, does one developer write one class, which he passes off to the next developer with a quick explanation of what each method does?

答:
I'm making this a separate answer because while it has some of Bevan's answer at its core, I'm expanding on it a bit.  I, too, have never seen a formalized way of doing this.

Mine is an Agile shop building a SaaS app, with a team of 4 developers and a tester, working on 2-weeks sprints.  When the team decomposes stories, we create a parent ticket and children tickets that roughly work out to be model changes, view changes, and controller changes (broadly speaking) to achieve the goals of that story.

When it comes time to work, one developer grabs the parent ticket, and for the life of that work within the sprint, they become the "owner" of the code that goes into realizing that story.  However, it is quite common that other people on the team work on the child stories depending on personal strengths (e.g. UI, database, an extra dose of business logic knowledge).  The "owner" of the parent ticket is the go-to for questions about that feature or component (whatever the case may be) until all the children are completed and the owner works through the whole item at the parent level and is ready to send it as a bundle to the code review status.

When items go through code review, they do so at the individual child level as well, and the only rule is that no one reviews their own code (obviously).  So, while Developer A might be the owner of the parent ticket, he could have worked on Piece 1, 2, 3 while Developer B worked on Piece 4, 5, and Developer C on piece 6, 7.  Developer A would be able to code review 4, 5, 6, 7, Developer B could code review 1, 2, 3, 6, 7, Developer C could code review 1, 2, 3, 4, 5.  When the code makes it through Code Review, it goes to test.

The tester tests each child independently if it has its own acceptance criteria, and the parent as a whole (which definitely has its own acceptance criteria).  Here's where "ownership" comes into play again -- the owner of the parent is responsible for any fixes in the parent or its children.  "Responsible" in this case may mean "having a conversation with whomever worked on a problematic child" but it is the parent owner's to get right.

The thought with all of this, and it's worked ridiculously and shockingly well with my team, is that everyone is always both an owner and a helper, everyone practices collaboration and communication constantly, and everyone is then familiar enough with every piece of the system that after the release anyone can be an owner of anything for the short period of time that owners have a role (e.g. within a sprint).

Title: How does team development work?


答:
The short answer - No, there are no standard ways of doing anything, but one thing which nearly all projects start out with in common is that almost everything will be 'unknown' near the beginning.

With reference specifically to your question about delegating responsibility for individual classes (or any other implementation details for that matter) - those kinds of decisions can't always be made up-front because developers often don't have enough information at the time the work is divided.  It's fairly common to have no idea what classes are going to be created until development has begun and there exists some kind of working baseline/prototype.

More typically, developers might just agree upon periphery details for whichever part of the system they are responsible for, so that other developers have an idea of how the bits will integrate together, without worrying about how it's actually going to work.

In practice, it usually means defining communication boundaries (internal or external) which will be used to connect the features/components/modules - e.g. interface types, message structures, data formats, input/output streams, shared data types etc.    The final split of responsibility may or may not mean that multiple developers work on the same classes/functions; it may also mean that classes which featured in the original design are scrapped and overall architecture is later changed (but hopefully the basic interfaces and communication mechanisms will still be largely usable)

Title: How does team development work?

Body:
This is a pretty generic question but one I've been wondering about for a while: is there a standardized, generally accepted, or even just systematic way that people write code as a group?

For example, in a project written in C++, does one developer write one class, which he passes off to the next developer with a quick explanation of what each method does?


问:
What options are there for splitting UI layout from code logic using a markup language?
What tools similar to GWT's UIBinder exist in other languages? By this I mean a system where you can define your UI layout in a markup language (preferably html+css) and attach the functionality to the layout using the code. I'm most interested in anything for python, but answers in other languages would interest me as well.

I'm interested because the benefits of having a non-programmer work directly on the layout without needing to touch the code and adjust a bunch of UI toolkit method calls is very productive.

I'm aware of Flex for flash, but is there anything else out there?

What search terms might I use to find such frameworks? I've looked around but I haven't found anything concrete.

Edit: I'm not only interested in web frameworks, but desktop applications as well.

Edit2: My question appears to be close to a duplicate of https://stackoverflow.com/questions/2962874/what-are-the-open-source-alternatives-to-wpf-xaml

答:
WPF (and all other XAML-based systems) do separation of UI and logic thanks to DataBinding (more like property synchronization) and templating. This resulted in pattern called MVVM that depends of DataBinding and Commands.

This allows two things:

Efficient UnitTesting of UI logic without being dependent on the UI framework itself

Ability to have different people working on different aspects of the UI. Eg. separation of design and logic

The advantages are many. Main one allows both designer and developer to work on same use case at the same time. Before it was either designer creating the UI before developer or other way around. Second is that XAML in general is much more suited for designers than code. There is even separate tooling for XAML development (Expression Blend) that works on same solution and project files as Visual Studio. This allows designers to work on the application itself instead of creating "mockups" and then leaving it to programmers to put design into applications.


问:
Should I modify an entity with many parameters or with the entity itself?
We have a SOA-based system. The service methods are like:

UpdateEntity(Entity entity)

For small entities, it's all fine. However, when entities get bigger and bigger, to update one property we should follow this pattern in UI:

Get parameters from UI (user)

Create an instance of the Entity, using those parameters

Get the entity from service

Write code to fill the unchanged properties

Give the result entity to the service

Another option that I've experienced in previous experiences is to create semantic update methods for each update scenario. In other words instead of having one global all-encompasing update method, we had many ad-hoc parametric methods. For example, for the User entity, instead of having UpdateUser (User user) method, we had these methods:

ChangeUserPassword(int userId, string newPassword)

AddEmailToUserAccount(int userId, string email)

ChangeProfilePicture(int userId, Image image)

...

Now, I don't know which method is truly better, and for each approach, we encounter problems. I mean, I'm going to design the infrastructure for a new system, and I don't have enough reasons to pick any of these approaches. I couldn't find good resources on the Internet, because of the lack of keywords I could provide. What approach is better? What pitfalls each has? What benefits can we get from each one?

答:
The second approach to updates provides more semantic meaning to the update. It is similar to CQRS (Command Query Responsibility Separation) where you provide a different service for Commands (changes to the model) versus Queries against the model. Using this approach, you can mitigate the need to handle optimistic concurrency because instead of one global "this object was updated" operation, you provide distinct operations that modify specific pieces of information.

This approach also provides a good entry point for more detailed auditing. Instead of just seeing User A updated Customer X, you can say User A changed Customer X's primary billing address.

I'd also recommend using an O/RM that provides change tracking out of the box so that you just load the entity, make the change and save it. You can also leverage domain driven design and put these operations directly on the entity. So instead of having a ServiceOperation that manipulates the entity, the Service Layer becomes a façade that delegates the operation to the entity directly.

Using this approach, the details of your underlying model can change without requiring the Service Layer or its clients to change.


答:
Your question amounts to picking the right abstraction level for your service's interface.   Every real-world system has different requirements, but as a general rule I strongly prefer service interfaces having a high level view.  That is, the second approach you describe, not the first.

However, this is just a guideline and to make a sound choice you will need to be able to justify it with more than "some guy said it was better this way" or "it's the usual approach".

So let's dig down to the relevant issues here.

Coupling

Your design should allow the service implementation and its clients to be loosely coupled.  The client should not need to know how the service is implemented, or how it stores (often, even how it represents) its data.   It should be possible to (greatly) change the implementation of the service without needing to rebuild or modify the clients.  The use of the word "Entity" in your description seems to imply that the objects exposed via the service interface correspond exactly to the entities into which the application's data has been decomposed.  If so this may indicate that there is tight coupling between the client interface and the service implementation.   Sometimes this is allowable though, where the service itself uses data definitions defined in its own interface (this can help with decomposition, which I will mention again later).

Think about how you would roll out a change to the data structures used in the interface; that is, if the data structures carried across your service interface need to change, must you perform a big-bang change (awkward!) or can your service design accomodate clients some of which expect the new representation and some the old?   (interface versioning is a common way to allow this)

Decomposition

The service's interface design should generally allow enough flexibility that the service implementation can be split up in order to allow part of the service implementation  to migrate to a different design.   For example, it should be possible for the maintenance of people's attributes to be moved out of the old service implementation and into an LDAP database.   While I suppose this is always possible, I mean that the design should work in such a way that the clients don't necessarily need to care that this happened, and that the implementation of only a reasonable amount of the service's interfaces should need to be changed to allow this.  Phrasing this differently, this kind of refactoring should not require changes to be made in unrelated parts of the service implementation.

Indirection

Your service's level of abstraction should be chosen in such a way that it will interact in an easy-to-explain way with layered systems.   For example, it should be straightforward to create a caching service which front-ends this service and caches data to reduce load on the back-end.   Likewise with modifications to the authorisation scheme.   Equally, it should be reasonably simple to create a mock back-end (often only offering a subset of interfaces) to facilitate testing of clients.   Likewise, artificial clients for load-testing.

Other Issues

There are other issues to bear in mind for some systems which aren't always important, but can make life very hard if you don't think of them ahead of time.   A big one here is the question of how to shard the service.  That is, split the existing system into several parts, each of which deals with some of the data objects in the system.   For example if your system accepts email, you may need to split it into multiple backends, each accepting email for a subset of users (e.g. "a"-"f" on shard 1, "g"-"p" on shard 2, "q"-"t" on shard 3, "u"-"z" on shard 4, "Â"-"Ͱ" on shard 5, and so on).   In order to allow the clients to remain unchanged, this kind of change would also usually be accompanied by the introduction of a proxy layer, whose only job is to forward requests to the relevant backend (it should be possible to deploy as many proxies as are needed to cope with the load; their task is not computationally hard and it shouldn't require hitting a disk to identify the right backend).

Title: Should I modify an entity with many parameters or with the entity itself?

Body:
We have a SOA-based system. The service methods are like:

UpdateEntity(Entity entity)

For small entities, it's all fine. However, when entities get bigger and bigger, to update one property we should follow this pattern in UI:

Get parameters from UI (user)

Create an instance of the Entity, using those parameters

Get the entity from service

Write code to fill the unchanged properties

Give the result entity to the service

Another option that I've experienced in previous experiences is to create semantic update methods for each update scenario. In other words instead of having one global all-encompasing update method, we had many ad-hoc parametric methods. For example, for the User entity, instead of having UpdateUser (User user) method, we had these methods:

ChangeUserPassword(int userId, string newPassword)

AddEmailToUserAccount(int userId, string email)

ChangeProfilePicture(int userId, Image image)

...

Now, I don't know which method is truly better, and for each approach, we encounter problems. I mean, I'm going to design the infrastructure for a new system, and I don't have enough reasons to pick any of these approaches. I couldn't find good resources on the Internet, because of the lack of keywords I could provide. What approach is better? What pitfalls each has? What benefits can we get from each one?


问:
Why is there no service-oriented language?
Edit:

To avoid further confusion: I am not talking about web services and such. I am talking about structuring applications internally, it's not about how computers communicate. It's about programming languages, compilers and how the imperative programming paradigm is extended.

Original:

In the imperative programming field, we saw two paradigms in the past 20 years (or more): object-oriented (OO), and service-oriented (SO) aka. component-based (CB).

Both paradigms extend the imperative programming paradigm by introducing their own notion of modules. OO calls them objects (and classes) and lets them encapsulates both data (fields) and procedures (methods) together. SO, in contrast, separates data (records, beans, ...) from code (components, services).

However, only OO has programming languages which natively support its paradigm: Smalltalk, C++, Java and all other JVM-compatibles, C# and all other .NET-compatibles, Python etc.

SO has no such native language. It only comes into existence on top of procedural languages or OO languages: COM/DCOM (binary, C, C++), CORBA, EJB, Spring, Guice (all Java), ...

These SO frameworks clearly suffer from the missing native language support of their concepts.

They start using OO classes to represent services and records. This leads to designs where there is a clear distinction between classes that have methods only (services) and those that have fields only (records). Inheritance between services or records is then simulated by inheritance of classes. Technically, its not kept so strictly but in general programmers are adviced to make classes to play only one of the two roles.

They use additional, external languages to represent the missing parts: IDL's, XML configurations, Annotations in Java code, or even embedded DSL like in Guice. This is especially needed, but not limited to, since the composition of services is not part of the service code itself. In OO, objects create other objects so there is no need for such facilities but for SO there is because services don't instantiate or configure other services.

They establish an inner-platform effect on top of OO (early EJB, CORBA) where the programmer has to write all the code that is needed to "drive" SO. Classes represent only a part of the nature of a service and lots of classes have to be written to form a service together. All that boiler plate is necessary because there is no SO compiler which would do it for the programmer. This is just like some people did it in C for OO when there was no C++. You just pass the record which holds the data of the object as a first parameter to the procedure which is the method. In a OO language this parameter is implicit and the compiler produces all the code that we need for virtual functions etc. For SO, this is clearly missing.

Especially the newer frameworks extensively use AOP or introspection to add the missing parts to a OO language. This doesn't bring the necessary language expressiveness but avoids the boiler platform code described in the previous point.

Some frameworks use code generation to produce the boiler plate code. Configuration files in XML or annotations in OO code is the source of information for this.

Not all of the phenomena that I mentioned above can be attributed to SO but I hope it clearly shows that there is a need for a SO language. Since this paradigm is so popular: why isn't there one? Or maybe there are some academic ones but at least the industry doesn't use one.

答:
Functional languages are very service oriented at their core. Instead of creating objects and calling functions on them, you create functions and pass messages to them. Erlang is a prime example of this technique because even beyond the functional aspects of the language it does have inter-process and even inter-machine communication built into its core framework allowing you to send messages to a remote process as if it were a local process.

Other languages such as Scala, Clojure, and F# also provide "service-oriented" semantics. The problem isn't that they don't exist, it's that the general populace is afraid of them and so they aren't as popular.


答:
Customers will ALWAYS find bugs. There's no hiding bugs from customers, ever. In the end bugs you introduce will always come back to you. Not fixing them is simply a bad professional practice. Professionals don't do this.

When customers find bugs, the company looks bad, not an individual developer. This is much worse for the company, so there's your case for making the change. If you really are not sure about making this change in fear of introducing other bugs, talk to a more senior developer, project technical lead or whoever else is in the position to make a decision on such change and subsequently handle consequences.

Title: Fix bugs, or wait for the customer to find them?

Body:
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

ContentLicense: CC BY-SA 2.5


问:
Security of logging people in automatically from another app?
I have 2 apps. They both have accounts, and each account has users.

These apps are going to share the same users and accounts and they will always be in sync.

I want to be able to login automatically from one app to the other.

So my solution is to generate a login_key, for example: 2sa7439e-a570-ac21-a2ao-z1qia9ca6g25 once a day. And provide a automated login link to the other app... for example if the user clicks on:

https://account_name.securityhole.io/login/2sa7439e-a570-ac21-a2ao-z1qia9ca6g25/user/123

They are logged in automatically, session created.

So here we have 3 things that a intruder has to get right in order to gain access; account name, login key, and the user id.

Bad idea? Or should I can down the path of making one app an oauth provider? Or is there a better way?

答:
If done correctly, it's a good idea and improves overall user experience.

I would read up on the Kerberos protocol and get some ideas on how to implement.  You won't need to reinvent the wheel in this case, as several folk have already implemented exactly what you're suggesting.


答:
Unless you are using an ORM to track changes, it would be difficult to pass only the changed columns simply because there are many permutation of parameters. You'd need to write a separate method for each permutation. This is clearly not possible.

Example:

Customer (id, firstName, lastName)

To update a customer record, you could have the following parameters passed to UpdateCustomer (and its overloads):

A-firstName

B-firstName, LastName

C-LastName

This is not an acceptable approach specially with large number of columns.

Passing the entire entity also has its drawbacks however, those can be tolerated:

It is error prone. You must ensure that each column holds correct data.

It passes data not needed and will require an update statement with unnecessary SET statements. Also, you may need to perform unnecessary lookups to other tables to populate values in FKs and do unnecessary validations.

In some applications, it is not OK to update all data in an entity, since some users don't have the privilege to do so. This is true for banking applications for example. In this case, you have to pass the changed columns only otherwise the update for non-privileged users will not go through.

So, unless you are willing to write a layer that would detect changes and generate SQL for it, the best approach (in my opinion) is to use an ORM that track changes for you.


问:
How to get feedback from the community on large chunks of code?
Code Review.SE is great when you need feedback on a precise, short piece of code.

But where to get similar feedback about the code itself when:

you have thousands of LOC,

don't have colleagues in your workplace ready or willing to review the code¹,

don't have thousands of dollars to spend for a professional review by a third party developer?²

Places like CodePlex are a good idea to get your project known³, but from what I've seen, the feedback you get on known projects are consumer feedback, i.e. concerns the bugs and feature requests, not the quality of the source code itself.

What are the social way to get the community involved in the code review of the codebase of a certain size for an open source project which doesn't have the scale of Firefox or similar products?

¹ Which is the case for most personal and open source projects, or projects done in companies where the practice of regular and complete code review is nonexistent.

² Which is, again, the case for most personal and open source projects.

³ Even if too many projects published on CodePlex never get known, either because nobody cares or because they are presented not very well.

答:
Tough question; not sure there's a solid answer.

I think there are two parts to your question -

First, where can you post the advertisement requesting the review.

Second, how to find folk that are willing to put in the amount of time to perform the review.

They are related, but subtly different.

The second might be easier than the first to answer - both the P.SE and CR.SE communities ought to have folk that would be willing to step up and help out with that.  Personally, I find that I almost always learn something from a review, so I find them rewarding.  Motivations vary, so if it's an interesting area of code that may help in identifying someone or several folk.

The first is not as easy to answer.  P.SE is out as the request doesn't meet the Q&A format.  CR.SE doesn't seem well suited for things either unless you broke things up into smaller chunks (modules / functions) and had a helluva lot of posts.  Offhand, I don't know of any sites where you could post that sort of a request.  If the SE system had an person-to-person mailing system, that might be one way of recruiting, but I'm riffing there.

Given that an out-of-band review of several thousand loc will take a while, I would encourage patience in the process.

In short, you just have to find a fellow developer who is willing to perform the review.


问:
How to generate "language-safe" UUIDs?
I always wanted to use randomly generated strings for my resources' IDs, so I could have shorter URLs like this: /user/4jz0k1

But I never did, because I was worried about the random string generation creating actual words, eg: /user/f*cker. This brings two problems: it might be confusing or even offensive for users, and it could mess with the SEO too.

Then I thought all I had to do was to set up a fixed pattern like adding a number every 2 letters. I was very happy with my 'generate_safe_uuid' method, but then I realized it was only better for SEO, and worse for users, because it increased the ratio of actual words being generated, eg: /user/g4yd1ck5

Now I'm thinking I could create a method 'replace_numbers_with_letters', and check that it haven't formed any words against a dictionary or something.

Any other ideas?

ps. As I write this, I also realized that checking for words in more than one language (eg: english and french, spanish, etc) would be a mess, and I'm starting to love numbers-only IDs again.

UPDATE

Some links everyone should read:

http://thedailywtf.com/Articles/The-Automated-Curse-Generator.aspx

Link

答:
In many situations (email spam, ip blocking, etc), a blacklist is a losing game -- you'll never be able to make a "complete" blacklist of every possible bad thing that could ever occur.
a b c d e f

Many people use a whitelist of acceptable words and string them together in some random order.
(Perhaps with a dash or dot or space between each word).

Some popular dictionaries that are used for converting arbitrary numbers to a pronounceable series of words include:

a list of fruits a b

the PGP word list, also called a biometric word list

the DialDice list

the Diceware list

the S/KEY dictionary from RFC1760

ContentLicense: CC BY-SA 4.0

Title: How to generate "language-safe" UUIDs?


问:
How do you find partners for open source projects?
I've created a few open-source projects in the past, and had some success. The process was generally the following: I'd start alone, create something that works, promote it, and finally (maybe) get some contributions.

I have less that to contribute to open-source now, but I still have ideas and can still code :) So I wonder if there is a place or a way to meet people (online), discuss ideas and design, and then start working together on the project?

The reason I'm thinking about an online way to do this, with strangers, is that while I do have programmer friends, we only very rarely have the same needs and interests at the same time. It seems to me that it would be easier to find such in match in the online global community.

Any insight?

答:
One of the approaches to find interested developers to your project, might be meeting and speaking (some call it networking) with the actual developers who are local to you. Question is where to find them?

There is a number of local user groups where you can meet people/developers who are passionate about things that they do. Depending in which area are you living, there are different interest groups.
Here you are some info that might be helpful.

Community Megaphone

User Groups: Meet and learn with your peers


问:
Git: Fixing a bug affecting two branches
I'm basing my Git repo on A successful Git branching model and was wondering what happens if you have this situation:

Say I'm developing on two feature branches A and B, and B requires code from A. The X node introduces an error in feature A which affects branch B, but this is not detected at node Y where feature A and B were merged and testing was conducted before branching out again and working on the next iteration.

As a result, the bug is found at node Z by the people working on feature B. At this stage it's decided that a bugfix is needed. This fix should be applied to both features, since the people working on feature A also need the bug fixed, since its part of their feature.

Should a bugfix branch be created from the latest feature A node (the one branching from node Y) and then merged with feature A? After which both features are merged into develop again and tested before branching out?

The problem with this is that it requires both branches to merge to fix the issue. Since feature B doesn't touch code in feature A, is there a way to change the history at node Y by implementing the fix and still allowing the feature B branch to remain unmerged yet have the fixed code from feature A?

Mildly related: Git bug branching convention

答: Arguably, there is no bug in A or X.  Fix the bug in branch B where it was found.  The fix will propagate to X and A in the normal course of events.</p>


答:
You first need to consider the definition of a bug:

The code as read doesn't match with what you percieve to be right

The software does not properly perform its tasks

You appear to be focusing on #1, where #2 is the best place to sit.  Sure, we programmers want our code to be right (#1), but people pay us for it to work (#2).

What you may or may not do to the code base that could accidentally introduce new bugs is irrelevant to #2's view of the current software.  However, #1 matters for yourself or the maintenance programmer that follows.  It's sometimes difficult to decide, but when #2 and #1 conflict, you have to know that #2 is clearly more important.


问:
C Flexible Arrays: When did they become part of the standard?
I learned to program in C many years ago, and used C steadily for about 10 years.

These days, I occasionally have to look at C code, because our Informix 4GL RDS customized runners also contain C code, but it is fairly simplistic code.

When I was using C a lot, I never remember hearing about of flexible arrays. I am asking this question, because I came across this SO question. Thanks.

答:
C99 standardised them. However, they were used long prior with 1-element arrays, a trick known as the struct hack.

It's not clear if it's legal or portable, but it is rather popular. An implementation of the technique might look something like this:

```<code>    #include <stdlib.h>
    #include <string.h>

    struct name *makename(char *newname)
    {
        struct name *ret =
            malloc(sizeof(struct name)-1 + strlen(newname)+1);
                    /* -1 for initial [1]; +1 for \0 */
        if(ret != NULL) {
            ret->namelen = strlen(newname);
            strcpy(ret->namestr, newname);
        }

        return ret;
    }
</code>```

This function allocates an instance of the name structure with the size adjusted so that the namestr field can hold the requested name (not just one character, as the structure declaration would suggest).

Despite its popularity, the technique is also somewhat notorious: Dennis Ritchie has called it ``unwarranted chumminess with the C implementation,'' and an official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.)

Another possibility is to declare the variable-size element very large, rather than very small...

Body:
C99 standardised them. However, they were used long prior with 1-element arrays, a trick known as the struct hack.

It's not clear if it's legal or portable, but it is rather popular. An implementation of the technique might look something like this:

    #include <stdlib.h>
    #include <string.h>

    struct name *makename(char *newname)
    {
        struct name *ret =
            malloc(sizeof(struct name)-1 + strlen(newname)+1);
                    /* -1 for initial [1]; +1 for \0 */
        if(ret != NULL) {
            ret->namelen = strlen(newname);
            strcpy(ret->namestr, newname);
        }

        return ret;
    }

This function allocates an instance of the name structure with the size adjusted so that the namestr field can hold the requested name (not just one character, as the structure declaration would suggest).

Despite its popularity, the technique is also somewhat notorious: Dennis Ritchie has called it ``unwarranted chumminess with the C implementation,'' and an official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.)

Another possibility is to declare the variable-size element very large, rather than very small...


答:
It is defined in ISO C99; I don't really know if it has been defined before, but I doubt it.

Traditionally, structures with now-specified flexible arrays were declared with arrays of size 1 at the end, and then allocated according to the desired size, a trick known as the "struct hack". Examples of this may be seen eg. in the Windows API.

Title: C Flexible Arrays: When did they become part of the standard?

Body:
I learned to program in C many years ago, and used C steadily for about 10 years.

These days, I occasionally have to look at C code, because our Informix 4GL RDS customized runners also contain C code, but it is fairly simplistic code.

When I was using C a lot, I never remember hearing about of flexible arrays. I am asking this question, because I came across this SO question. Thanks.


问:
MIT License in a referenced library: legal implications?
I'm trying to determine what my legal obligations are if I use an MIT-licensed library (JAR file) in my program. Do I need to include the library's source code when I distribute my program? Do I need to include a README explaining the licensing of the packaged JAR? If I'm simply including the unedited JAR file, do I even need to include anything additional?</p>

答:
When the license ask you for including the license itself in your software, this does not mean "put a giant alert in the GUI of your program with this text in it", this simply means put this license in your source files, or, at least, in the biggest and most important source files.

for example at first you program or the portion/libraries that is MIT licensed is:

```<code>#include stuff

void foo();

int main(){
...
...
...
}
</code>```

to respect the license you have to include the license itself

```<code>/************************
* Here is the full text
* interesting stuff
* bla bla bla
************************/
#include stuff

void foo();

int main(){
...
...
...
}
</code>```

if you do not want to generate too much entropy in your code you can place the license at the bottom of your file, the important thing is just including license, of course the text of the license should be commented since they are not instructions for your compiler; just for the sake of clarity some people put the license at the bottom and just a reminder on top, a short phrase like "You will find the Terms of Use at the bottom of this file".

Done.

Body:
When the license ask you for including the license itself in your software, this does not mean "put a giant alert in the GUI of your program with this text in it", this simply means put this license in your source files, or, at least, in the biggest and most important source files.

for example at first you program or the portion/libraries that is MIT licensed is:

#include stuff

void foo();

int main(){
...
...
...
}

to respect the license you have to include the license itself

/************************
* Here is the full text
* interesting stuff
* bla bla bla
************************/
#include stuff

void foo();

int main(){
...
...
...
}

if you do not want to generate too much entropy in your code you can place the license at the bottom of your file, the important thing is just including license, of course the text of the license should be commented since they are not instructions for your compiler; just for the sake of clarity some people put the license at the bottom and just a reminder on top, a short phrase like "You will find the Terms of Use at the bottom of this file".

Done.


问:
De-facto standards for customer information record
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)

答: There is a thread in the DBA stack on best practices for common person fields that discusses the issues.  It matters a great deal what you are planning to do with the data and how thorough you need to be.  If you actually need to support all valid email addresses or all valid names, your columns are going to need to be much bigger than if you merely want to support whatever your organization and application consider a reasonable subset of the valid values.</p>


答:
There isn't a social-media way to get people to drop hours of their time into reviewing code for some random project... or to do anything else, for that matter. Minutes you can have, hours not so much.

So, you've got two possiblities:

1) Break it into minutes-long chunks. You do NOT need ALL of your thousands of lines of code reviewed. Extract the bits that matter most and ask for review of one or two of those. You'll probably get some kind of general style/don't-do-that/name-things-like-this comments, which you can then apply to the whole of the codebase. If you have a LOT of bits... well, prune more, and maybe ask for review of one or two per week, and iterate based on the commentary you get back. When all the comments are things you've seen before and decided not to change anyway, you're done.

2) Make the project important to people. I don't think you can actually do this, but if you have code that really will solve the Greek financial crisis, you win.

Title: How to get feedback from the community on large chunks of code?

Body:
Code Review.SE is great when you need feedback on a precise, short piece of code.

But where to get similar feedback about the code itself when:

you have thousands of LOC,

don't have colleagues in your workplace ready or willing to review the code¹,

don't have thousands of dollars to spend for a professional review by a third party developer?²

Places like CodePlex are a good idea to get your project known³, but from what I've seen, the feedback you get on known projects are consumer feedback, i.e. concerns the bugs and feature requests, not the quality of the source code itself.

What are the social way to get the community involved in the code review of the codebase of a certain size for an open source project which doesn't have the scale of Firefox or similar products?

¹ Which is the case for most personal and open source projects, or projects done in companies where the practice of regular and complete code review is nonexistent.

² Which is, again, the case for most personal and open source projects.

³ Even if too many projects published on CodePlex never get known, either because nobody cares or because they are presented not very well.


答: I would take a first stab using something like stylecop and fxcop or equivalents for your language.  Next, you can document the architecture and get feedback on that very quickly.  Finally you could take some troublesome snippets or a few classes and ask a dev to go over it with you instead of the entire code base.    Provided you didn't change code style all over, a few classes should give some insight into the code base as a whole.</p>


答:
Fix the bug

We're professionals here.  If you find a failing path in the code that will cause a crash or incorrect behavior, you need to fix it.  Depending upon your team's procedures, you likely need to file a defect, perhaps write a regression test, and check in the fix at the right time of the ship cycle.  If it's a low priority bug, checking in the fix near the beginning of a milestone is always a good time because if you do cause a regression you won't affect the release cycle of the milestone.

Don't confuse this with refactoring or making performance improvements that are not related to a performance bug.

A distributed source control system where you can keep a separate repository of 'little bug fixes' and then easily merge at the beginning of a milestone is a great help here.


问:
Is there a Javascript library for creating vintage photos?
I'm working on a Canvas object in HTML5, and I am attempting to make some photos look "better".

I tried VintageJS, an existing photo-retouching Javascript library, and Picozu, a web application cloning some Adobe Photoshop functionalities, but I'm still not happy.

Can you help me with an algorithm or point to an existing Javascript library that would allow me to make my photos look like the following example?

http://i46.photobucket.com/albums/f137/thanhtu_zx/Untitled-1.jpg

答:
I saw this post here for sometime without any action, so  I took a gander on the web to see what was there. I also found VintageJS, for vintage photos.

Go figure. Here is the code.

```<code>$('img.vintage').click(function () {
    $(this).vintage({
        vignette: {
            black: 0.8,
            white: 0.2
        },
        noise: 20,
        screen: {
            red: 12,
            green: 75,
            blue: 153,
            strength: 0.3
        },
        desaturate: 0.05
    });
});
</code>```

Here are two other similar photo manipulation frameworks: Paintbrush.js and Caman.js, in a nice tutorial with Vintage.js.

It seems to me that it is all in the implementation.

Try:

vignette:{ black: 0.3, white: .7 },
           noise: 40, screen: { red: 120, green: 65, blue: 133, strength: 0.5 },
           desaturate: 0.15 });

This is a good question; I didn't know these before. Now we do.

Body:
I saw this post here for sometime without any action, so  I took a gander on the web to see what was there. I also found VintageJS, for vintage photos.

Go figure. Here is the code.

$('img.vintage').click(function () {
    $(this).vintage({
        vignette: {
            black: 0.8,
            white: 0.2
        },
        noise: 20,
        screen: {
            red: 12,
            green: 75,
            blue: 153,
            strength: 0.3
        },
        desaturate: 0.05
    });
});

Here are two other similar photo manipulation frameworks: Paintbrush.js and Caman.js, in a nice tutorial with Vintage.js.

It seems to me that it is all in the implementation.

Try:

vignette:{ black: 0.3, white: .7 },
           noise: 40, screen: { red: 120, green: 65, blue: 133, strength: 0.5 },
           desaturate: 0.15 });

This is a good question; I didn't know these before. Now we do.


问:
What are the barriers to adopting best practice? How can they be overcome?
We've all seen (and most of us have written) plenty of poorly written code. Why? What makes us adopt poor practices rather than good ones?

The most obvious answer (to me) is "ignorance", but I'm sure that isn't the only reason. What others are there? What can we do to overcome the temptation to write bad code?

答:
(Lack of) Knowledge and Skills + Time To Invest

I'm surprised no one else has put this one out, but maybe it's obvious to me because so much of my work has been as a singleton programmer, with no one (other than stack) to go to when I struggle on something.  I know 'of' better techniques -- such as TDD -- but all to often I don't understand them well enough to use them and have a hard time finding good information to help me start using them.  Again, using TDD as an example, I understand the basic meaning of it -- build tests that assert your code outputs a specific result -- but actually implementing it?

Other than the fact that XCode has built-in unit-testing these days, I don't have a clue where to start.  Do I assert that view has X buttons on it after I run a routine to make them?  How about asserting that my UIViews have been re-arranged appropriately after I call the rotate tag?

Heck, how do I even write a unit test in XCode?  That's something else I need to spend time learning.


问:
iOS and Server: OAuth strategy
I'm trying to working how to handle authentication when I have iOS clients accessing a Node.js server and want to use services such as Google, Facebook etc to provide basic authentication for my application. My current idea of a typical flow is this:

User taps a Facebook/Google button which triggers the OAuth(2) dialogs and authenticates the user on the device. At this point the device has the users access token. This token is saved so that the next time the user uses the app it can be retrieved.

The access token is transmitted to my Node.js server which stores it, and tags it as un-verified.

The server verifies the token by making a call to Facebook/google for the users email address. If this works the token is flagged as verified and the server knows it has a verified user. If Facebook/google fail to authenticate the token, the server tells iOS client to re-authenticate and present a new token.

The iOS client can now access api calls on my Node.js server passing the token each time. As long as the token matches the stored and verified token, the server accepts the call.

Obviously the tokens have time limits. I suspect it's possible, but highly unlikely that someone could sniff an access token and attempt to use it within it's lifespan, but other than that I'm hoping this is a reasonably secure method for verification of users on iOS clients without having to roll my own security.

Any opinions and advice welcome.

答:
Yes somebody could potentially see this token in the packet, which is why it is also a good idea to use SSL encryption of all network traffic before and after authentication and distribution of a token.

Someone on an unencrypted wireless network, like at a Starbucks use this method all the time to pick up packets to services like Facebook that do not require SSL encrypted traffic.  They then can use this token in their own requests to spoof another users session.

Likewise if I am a hacker and I were to compromise a particular machine behind a firewall where network traffic passes through, lets say a load balancer, I can then use that information to determine credentials and session tokens on unencrypted traffic that passes through.

The appropriate way to handle this is to utilize SSL encryption, even if it is a self-signed certificate then you are ensured that third parties cannot listen in on user requests.

Title: iOS and Server: OAuth strategy


问:
Is it possible to develop apps with Kendo UI to submit to iOS App Store?
The number of platforms I have to develops apps for is increasing and It brings me lots of stress to learn new technologies for each target platform. I found out that Telerik's Kendo UI is very good to build websites that look and feel native on mobile platforms (e.g. iOS and Android). My question is, is it possible to build HTML5 apps to deploy them on iTunes App Store and Google Play? Please note that I am eager to know the possibility of creating apps (complete apps bundled in standard format of Apple and Google for distribution in their respective mobile app markets) but not websites.</p>

答: Yes, you can build applications with Kendo UI Mobile and PhoneGap and publish them to an app store (i.e. Apple App Store).</p>


答:
Sometimes, you'll find that habit is also a major contributor to writing awful code.

You might be a very experienced programmer and you might know all about present industry best practices. Hell, you could even be the expert about such things.  Experience tells me that such people don't often write awful code, and yet it can be easy to fall back on old habits and do something that you know will break the rules, simply because it feels safe and convenient. In such cases, ignorance and arrogance and all of the other finger-pointing adjectives you might think up don't really matter. It's not necessarily that such programmers are specifically bad at what they do (although this is more often the case), or even that they want to be creating an awful mess.

It's unfortunate that I have personally witnessed this happening more times than I would like to count, where some truly talented people have churned out sheer rubbish because their fingers and brains were operating on auto for a couple of months. Most often this is where you see evidence of burn-out, grief and stress piling up. Sometimes it really is just blind habit carrying them through the daily motions. It's something I've learned to keep a careful eye out for in order to avoid risking labeling vulnerable people unnecessarily.

Just some food for thought for those of us who find it easier to simply leap to the negative conclusion... even though sadly you'll be right more often than not.

Title: What are the barriers to adopting best practice? How can they be overcome?

Body:
We've all seen (and most of us have written) plenty of poorly written code. Why? What makes us adopt poor practices rather than good ones?

The most obvious answer (to me) is "ignorance", but I'm sure that isn't the only reason. What others are there? What can we do to overcome the temptation to write bad code?


答:
If you are including the library unmodified, you have absolutely no obligations.

The license asks you to include it's text in all copies or substantial portions of the Software. That you have to do with any license anyway, because you are obliged to tell the recipient the terms under which you give the software to them.

However since the license also allows you to sublicense, you can ship the complete bundle under any license you want (and you have to put it in documentation somewhere), but if you don't mention the library is under MIT license, it will be covered by your license for the whole bundle and that does not violate the MIT license terms.

The common practice is to not bother mentioning MIT license in binary-only distributions, because the user can't do much with the library anyway and simply keep the license notice (and more importantly copyright notice) in sources it applies to if you ever distribute them.

Title: MIT License in a referenced library: legal implications?

Body: I'm trying to determine what my legal obligations are if I use an MIT-licensed library (JAR file) in my program. Do I need to include the library's source code when I distribute my program? Do I need to include a README explaining the licensing of the packaged JAR? If I'm simply including the unedited JAR file, do I even need to include anything additional?</p>


答:
In many cases the JAR file itself will contain a copy of the license, you can check for that by opening it in a ZIP file utility. In that case, you don't have to do anything.

However, I think it's good practice to document all used libraries and their licenses (by name) somewhere in the project's documentation.


问:
Python and only Python for almost any programming tasks!
Am I wrong if I think that Python is all I need to master, in order to solve most of the common programming tasks?

EDIT
I'm not OK with learning new programming languages if they don't teach me new concepts of programming and problem solving; hence the idea behind mastering a modern, fast evolving, with a rich set of class libraries, widely used and documented, and of course has a "friendly" learning curve programming language.

I think that in the fast evolving tech industry, specialization is key to success.

答:
You are right and wrong.

Right:  Knowing a single tool very well is very marketable and to be desired.  And Python is good for OO, for scripts, for functional-ish programming, and it has excellent mathematical and scientific libraries.

Wrong:  Python doesn't teach you everything a good developer should know.  Sometimes you will need JavaScript to provide some client-side functionality.  Sometimes you need to understand what's happening at a more fundamental level, such as the C underneath the Python.  And sometimes you need to learn to think in different ways, as you would with Haskell or Clojure.


问:
Unit and Integration testing: How can it become a reflex
All the programmers in my team are familiar with unit testing and integration testing. We have all worked with it. We have all written tests with it. Some of us even have felt an improved sense of trust in his/her own code.

However, for some reason, writing unit/integration tests has not become a reflex for any of the members of the team. None of us actually feel bad when not writing unit tests at the same time as the actual code. As a result, our codebase is mostly uncovered by unit tests, and projects enter production untested.

The problem with that, of course is that once your projects are in production and are already working well, it is virtually impossible to obtain time and/or budget to add unit/integration testing.

The members of my team and myself are already familiar with the value of unit testing (1, 2) but it doesn't seem to help bringing unit testing into our natural workflow. In my experience making unit tests and/or a target coverage mandatory just results in poor quality tests and slows down team members simply because there is no self-generated motivation to produce these tests. Also as soon as pressure eases, unit tests are not written any more.

My question is the following: Is there any methods that you have experimented with that helps build a dynamic/momentum inside the team, leading to people naturally wanting to create and maintain those tests?

答:
Getting an entire team to all actually want the same thing can be quite difficult. It's often the case that seeing the value in something isn't enough in itself to encourage people to change ingrained behavior.  Even those who value the change and who specifically want it can sometimes also be responsible for subconsciously fighting it.

The issue is really one of individual motivation and not team motivation as such.  There comes a time when a moment of clarity reaches you, either as a result of something you felt you finally understood, or because of some new tool or some other subjective thing that makes the average programmer throw everything in and completely change the process. Your job - should you choose to except it - is to see if there is a way for you or the team to find out which things will be the triggers of clarity for each individual team member.

For me personally, it was simply discovering the StoryQ framework for BDD in DotNet, which made it too easy to ignore, and got me completely over the test-first vs test-simultaneously "barrier". Later I had my choices reaffirmed when I found NCrunch for Visual Studio. Half the battle sometimes isn't in selling the idea, but rather in simply lowering the effort required to introduce radical change in habits... and even then it can take a little time and work. These same personal triggers however weren't enough to sway the approach of my colleagues at the time, who are still writing as much of their test code simultaneously or even after their implementation code.

Sometimes also, there is a reluctance to change the way things are done, due to an inherent fear, distrust, or distasteful view of the effort required to learn to do something differently, even when the reasoning for the change is sound.  If your entire test platform is tooled to work in a specific manner, it can be hard to justify changing the way things are done, and potentially changing the tooling, especially when old and new tests will need to continue to coexist for the lifetime of the project - and you certainly wouldn't want to need to rewrite every test you ever created. The strange thing is that sometimes people feel that this is the only way to adopt a new testing methodology, and that in itself makes it harder for those people to accept sensible change for the better.

Really, the only way something becomes reflexive is to force yourself to do it over and over again until you no longer notice yourself needing to concentrate overly much on how to do it. Sometimes, the only way to do this in a team is to set policies which may seen a little draconian, and to practice pair-programming and code-reviews, and anything else that can help team members back each other up and literally force the change in behaviour to occur. However, for such a strategy to really be successful, it still requires a firm and honest commitment from each and every individual team member to accept such measures as necessary, and to participate in the process... and a lot of patience from all involved.


答:
None of us actually feel bad when not writing unit tests at the same time as the actual code.

This is the point you need to address. The culture of your team needs to change such that not writing tests during the sprint (or whatever unit of time you use) becomes just as much a code smell as hard-coding values. Much of that involves peer pressure. Nobody really wants to be viewed as substandard.

Do the tests yourself. Visibly berate yourself when you don't do them. Point out where a "good" programmer would've caught that bug if they'd written unit tests. Nobody wants to be bad. Make it that this undesireable behavior is bad and people will follow.

Title: Unit and Integration testing: How can it become a reflex

Body:
All the programmers in my team are familiar with unit testing and integration testing. We have all worked with it. We have all written tests with it. Some of us even have felt an improved sense of trust in his/her own code.

However, for some reason, writing unit/integration tests has not become a reflex for any of the members of the team. None of us actually feel bad when not writing unit tests at the same time as the actual code. As a result, our codebase is mostly uncovered by unit tests, and projects enter production untested.

The problem with that, of course is that once your projects are in production and are already working well, it is virtually impossible to obtain time and/or budget to add unit/integration testing.

The members of my team and myself are already familiar with the value of unit testing (1, 2) but it doesn't seem to help bringing unit testing into our natural workflow. In my experience making unit tests and/or a target coverage mandatory just results in poor quality tests and slows down team members simply because there is no self-generated motivation to produce these tests. Also as soon as pressure eases, unit tests are not written any more.

My question is the following: Is there any methods that you have experimented with that helps build a dynamic/momentum inside the team, leading to people naturally wanting to create and maintain those tests?


问:
Is it any good to use binary arithmetic in a C++ code like "C style"?
I like the fact that the C language lets you use binary arithmetic in an explicit way in your code, sometimes the use of the binary arithmetic can also give you a little edge in terms of performance; but since I started studying C++ i can't really tell how much i have seen the explicit use of something like that in a C++ code, something like a pointer to pointer structure or an instruction for jumping to a specific index value through the binary arithmetic.

Is the binary arithmetic still important and relevant in the C++ world?
How i can optimize my arithmetic and/or an access to a specific index?
What about the C++ and the way in which the bits are arranged according to the standard?

... or i have taken a look at the wrong coding conventions ... ?

答:
In short: No, it is not any good to use "binary arithmetic"(in sense the question asks it) or "C style" in C++.

What makes you believe bitwise arithmetic would be any faster really? You can throw your bitwise operations all over the code, but what would make it any faster?

The thing is, almost whatever trivial thing you're trying to solve, can be solved easier by the standard high-level features(including the standard library, STL and STL algorithms). In some specific cases you might indeed want to switch the individual bits, for example when working with bitmasks. Or storing very compact data, for example when writing a compression algorithm, a dense file format or working for example with embedded systems.

If you are concerned with performance, always write a simple and trivial algorithm first. Just make it work. Then, measure the time your algorithm takes with typical input. Now, if you at this point feel that it is too slow, only then you can try optimizing it by hand with these "bitwise arithmetic" tricks. And after done, measure if your code is any faster. The chances are that it is not, unless you really know what you are doing in that specific situation/case.

Frankly, the best way to understand about this kind of low-level constructs which deal with performance is to study assembly language. It really makes you realize that no, writing some bit-manipulating wizzcode is not any faster than using that sort(begin(v),end(v)). Just because you operate at low level doesn't mean you operate fast. In general, Algorithms are more important than implementation details!

Basically whatever the "C style" means, please, stay away from it when writing C++. They are two completely different languages. Don't mix them.

Bjarne Stroustrup gave a great talk about C++ style in Microsoft's GoingNative 2012 conference this February, please take a look: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style

Especially the parts between around 10 and 15 minutes are great, when he talks about old C-style code compared to modern C++ style.


答:
Binary arithmetic is bound to the implementation. You must be careful about implementation details such as endianness. Therefore, using binary operators isn't automatically faster than using elementary operators. Often, the compiler will perform more relevant optimizations, and a natural code can be better for performance as well as easier to read for both the compiler and the programmer.

Of course, there are some cases (such as Base64 encoding), where you must use those operators. But optimizing code with binary operators should be the last optimization, coming after perfecting your algorithms. For personal programming, some pretty tricks (like this) may be faster, but with serious programming, readability should come first.

And, like zxcdw said, C and C++ are both very different languages. C++ has more high-level libraries, so binary tricks are less famous.

Title: Is it any good to use binary arithmetic in a C++ code like "C style"?

Body:
I like the fact that the C language lets you use binary arithmetic in an explicit way in your code, sometimes the use of the binary arithmetic can also give you a little edge in terms of performance; but since I started studying C++ i can't really tell how much i have seen the explicit use of something like that in a C++ code, something like a pointer to pointer structure or an instruction for jumping to a specific index value through the binary arithmetic.

Is the binary arithmetic still important and relevant in the C++ world?
How i can optimize my arithmetic and/or an access to a specific index?
What about the C++ and the way in which the bits are arranged according to the standard?

... or i have taken a look at the wrong coding conventions ... ?


答:
first you'll need to ensure that writing a test and running it is easy, get the framework set up in the current projects and make that set-up procedure simple to include in future projects

this way when a programmer wants to unittest a new feature he is trying to debug he doesn't have to jump through a dozen hoops to get the tests running properly

the more akward something is to do the less likely it is you'll make a habit out of it


答:
One thing I've done that's been somewhat successful in instigating a culture change is to set up a weekly drop in, "unit test curation" seminar.  The official purpose of this is to help keep the unit test suite fast running and up-to-date, but the more important purpose, in my mind, is to give people a low pressure way to drop in, ask questions, and practice testing.  The fact that you're willing to spend an hour or whatever per week exclusively on the tests also sends the message that this is important.

I think that you get a bit of a culture change this way and you start to remove the barrier to doing it "reflexively", as you put it.  People will tend to revert to old habits at the first sign of adversity -- having a meeting like this won't fix that in one fell swoop, but I think it'll initiate a culture change and remove the barrier that results from not really knowing what you're doing.


答:
None of us actually feel bad when not writing unit tests at the same
  time as the actual code

Not sure what you mean by "at the same time", but how about writing them before the actual code ?

It's easily understandable from a psychological perspective why any human being wouldn't want to bother writing unit tests after the code. At that point the code is already working, so why on earth should we need to test it ? Some kind of laziness automatically takes place because it's tedious, seemingly useless and not writing tests doesn't appear to be dangerous. As a result, I don't know of many teams that kept on with a test-after approach over a long period of time.

In my experience, test-first (TDD style), however, is something you can quickly get addicted to because there are at least 2 immediate, tangible, endorphin-releasing benefits to it :

It helps you design your code face to face with concrete executable requirements and make the design better and better as you refactor, which is much more purposeful and gratifying than just double-checking something that already works.

The TDD cycle is punctuated with frequent "green bar" moments where you can enjoy the taste of immediate success. It constantly keeps your mind satisfied and ready to go for the next feature to implement.

So I wouldn't attempt to make your team feel bad when they didn't write the tests. Instead, I'd try to make them feel good as they do. TDD is one way to do this.


问:
Where should libraries be placed, in windows?
I have just moved from Linux to Windows, and I have to use the Zend Framework library. Where should the library be placed?

Directly on C drive

Create a lib folder like C:/lib/

Create a lib folder in my user folder

I am wondering if there is a classic folder where these kind of libraries are placed.

Update:I am asking about the location on my own standpoint. The Zend Framework library is a PHP framework.

答:
Generally speaking, your app should live in either:

1) C:\Program Files\your_app_name

2) C:\Program Files (x86)\your_app_name

For 32 bit OSs such as XP, use #1.
For 64 bit OSs use #1 if your app is 64 bit.  Use #2 if your app is 32 bit.

Also take a look at MS's Developer Guidelines


问:
GPS accuracy with software
I spoke with a guy who claimed that he's working (programming) on a GPS-system that is going to be accurate to the centimeter.

Is this even possible?

What is the limiting factor, the big distance between the satellite and the GPS, or is it the software?

Can the software be improved to make a GPS accurate to centimeters?

答:
Modern receivers use A-GPS (Assisted GPS), which calculates location based on:

US DoD's GPS

GLONASS

(soon Galileo and Compass)

WiFi hotspots

3G base stations

It's not just averaging results from various sources, but actually using all of them to create better results.

Also, if the receiver remains stationary for longer it's possible to increase accuracy a lot. This is the method used typically in surveys.

Title: GPS accuracy with software


答: No, there is no use of binary arithmetic in C++, except one "tiny" detail: the C++ standard defines the language semantics in terms of a binary abstract virtual machine that must use either 1st complement, 2nd complement or sign-magnitude integer representation.


答:
It depends on what sort of C++ code you're writing. The lower you are the more relevant it becomes. The problem with these types of questions is that everyone can only rely on their own experience and so if someone has never had to do this sort of thing they can't see why someone else might need to do it.

Here's Joel's 'Five Worlds' article


问:
Should devs, testers and business users have one unified test script?
In development, I would normally have my own test scripts that would document the data, scenarios and execution steps that I plan to test; this is my dev test plan. When the functionality has been deployed to Test, testers test it using their own test script that they wrote. In UAT, the business user then tests using their own test plan.

In retrospect, it looks like this provides a better coverage, with dev tests having a mix of black and white box testing, while testers and business users focus on black box testing. But on the other hand, this brings up distinct test cases that only are executed per stage (ie. some cases which testers thought of are only executed on Test stage) and it would like the dev missed it, which makes it a finding/bug.

Is it worth consolidating the test scripts from the start? Thus using one unified test script, or is it abit difficult to do this upfront?

答: It really depends on the project.  In some cases a unified Test, QA and UAT team that meets to discuss findings can be highly beneficial.  It saves duplication of testing effort, and ensures that all parties have a clearer understanding of the business needs via UAT scripts.  On the other hand, depending on the complexity of the project, it might make more sense to have thoroughly QA'd the inputs and outputs prior to testing business examples.  For home-grown system development, initial QA would be a must prior to user acceptance.  For out-of-the-box implementations, a unified testing team would make the most sense.</p>


问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
What would the customer say?

Here is how I imagine this playing out:

Customer: It crashes when I do x.

Programmer: Oh yeah! I remember I saw that a while back. I figured it
  wasn't a big deal yet, so I left it in
  there.

Customer: [reaches for blunt object]

Yes. Fix the bug. You'll be saving the customer from an aggravating experience, and you get to fix it before it becomes an emergency.

And if you think your fix might actually cause a crash, then you haven't really found a fix yet.


问:
Who should be the architect in an agile project?
We are developing the agile way for a few months now and I have some troubles understanding the agile manifesto as interpreted by my colleagues. The project we are developing is a framework for future projects and will be reused many times in the next years.

Code is only written to fulfill the needs of the current user story. The product owner tells us what to do, but not how to do it. What would be right, in my opinion, because he is not implicitly a programmer.
The project advanced and in my eyes it messed up a little bit.
After I recognized an assembly that was responsible for 3 concerns (IoC-Container, communication layer and project internal things), I tried to address this to my colleagues.
They answered that this would be the result of applying YAGNI, because know one told them to respect that functionalities have to be split up in different assemblies for further use.

In my opinion no one has to tell us that we should respect the Separation of Concerns principle. On the other side, they mentioned to prefer YAGNI over SoC because it is less effort to implement and therefore faster and cheaper.
We had changing requirements a lot at the beginning of the project and ended up in endless refactoring sessions, because to much has to be adapted.

Is it better to make such rather simple design decisions up front, even there is no need in the current situation, or do we have to change a lot in the later progress of the project?

答:
Is it better to make such rather simple design decisions up front, even there is no need in the current situation, or do we have to change a lot in the later progress of the project?

Both.

It would have been better if someone realized that by slapping in another responsibility that the resultant class would be bad. Agile doesn't mean no design, it just means design (well) for what you need. You'll always need a maintainable codebase if you're making a framework for future products.

That said, mistakes will be made. Requirements will change out from under you so something that used to be a good design is no longer so. Then you need to be dilligent in refactoring, or at the very least documenting that technical debt to be prioritized for later sprints.


问:
How to define implementation details?
In our project, an assembly combines logic for the IoC-Container, the project internals and the communication layer.
The current version evolved to have only internal classes in addin assemblies.

My main problem with this approach is, that the entry point is only available over the IoC-Container. It is not possible to use anything else than reflection to initialize the assembly.

Everything behind the IoC-Interface is defined as implementation detail and therefore not intended for usages outside.
It is well known that you should not test implementation detail (such as private and internal methods), because they should be tested through the public interface.
It is also well known, that your tests should not use the IoC-Container to setup the SUTs, because that would result in too much dependencies.
So we are using the InternalsVisibleTo-Attribute to make internals visible to our test assemblies and test the so called implementation details.

I recognized that one problem could be the mixup between different concerns in that assembly, changing this would make this discussion useless, because classes have to be defined public.
Ignoring my concerns with this, isn't the need to test a class enough reason to make it public, the usages of InternalsVisibleTo seems unintended, and a little bit "hacky".
The approach to test only against the publicly available IoC-Container is too costly and would result in integration style tests.

The pros of using internals are, that the usages are well known and do not have to be implemented like a public method would have to be (documentation, completeness, versioning,...).

Is there a solution, to not test against internals, but keep their advantages over public classes, or do we have to redefine what an implementation detail is.

答:
It is well known that you should not test implementation detail (such as private and internal methods), because they should be tested through the public interface. It is also well known, that your tests should not use the IoC-Container to setup the SUTs, because that would result in too much dependencies.

I understand this point of view, but I also understand that, ultimately, it's about Getting Things Done.™  When the ceremony of best practices begins to interfere with your ability to get things done, it's time to step back and re-evaluate your assumptions.

Let me state equivocally that I always unit test my private and internal methods.  Why shouldn't I?  A unit test gives me confidence that the method behaves as I expect it to.  My unit testing framework does this, not by inheriting from my class (which is why some testing frameworks require that your methods be virtual), but by creating a proxy class which reflects over my actual class to execute those methods.

So we are using the InternalsVisibleTo-Attribute to make internals visible to our test assemblies and test the so called implementation details.

That's what you should be doing.  If your best practice is telling you that you can't test your internals, then throw out the best practice.

You can, and should, still test your public methods, but keep them in a separate area so that you can identify them specifically (these tests generally map to requirements, so you can use them to prove that requirements are satisfied).

Title: How to define implementation details?


答:
You're asking fairly broad-brush stroke questions with a minimal amount of context.  That will affect the quality of answers you'll get.

If you discovered a problem that violated SoC within a few sprints after it's creation, then YAGNI doesn't quite cut it as an excuse.  That's more to effect of "deliver anything" rather than deliver a maintainable solution.

The product owner should be providing enough long-term vision so the development team as a whole can make the correct design decisions.  If the long-term vision isn't there, then a broader level conversation needs to be had so everyone knows problems like this will creep up again.  Keep in mind that you don't have to keep hammering on that issue.  Note it, make sure the consequences were understood, and get back to coding.  The next time that type of a problem creeps up, point out that this was noted a while back, deal with the schedule disruption, and get back to coding.

If the product owner isn't able to communicate that vision, then it's worthwhile to have a few key members of the team spend more time with the product owner so the team can get a better understanding of what's coming next.

Honestly, this sounds like more of a communication issue as opposed to a development methodology issue.

Title: Who should be the architect in an agile project?

Body:
We are developing the agile way for a few months now and I have some troubles understanding the agile manifesto as interpreted by my colleagues. The project we are developing is a framework for future projects and will be reused many times in the next years.

Code is only written to fulfill the needs of the current user story. The product owner tells us what to do, but not how to do it. What would be right, in my opinion, because he is not implicitly a programmer.
The project advanced and in my eyes it messed up a little bit.
After I recognized an assembly that was responsible for 3 concerns (IoC-Container, communication layer and project internal things), I tried to address this to my colleagues.
They answered that this would be the result of applying YAGNI, because know one told them to respect that functionalities have to be split up in different assemblies for further use.

In my opinion no one has to tell us that we should respect the Separation of Concerns principle. On the other side, they mentioned to prefer YAGNI over SoC because it is less effort to implement and therefore faster and cheaper.
We had changing requirements a lot at the beginning of the project and ended up in endless refactoring sessions, because to much has to be adapted.

Is it better to make such rather simple design decisions up front, even there is no need in the current situation, or do we have to change a lot in the later progress of the project?


问:
Designing a hierarchical structure with lots of reads and writes?
I am in the process of working on a video on demand system part of it involves the management of a hierarchical tree structure (think windows explorer) which allows users to upload videos, move folders around, create new folders etc. User action will be allowed depending on which permissions they have.

In addition to managing the structure (creating folders and uploading videos), subscribers will be viewing content (read access). The number of reads will be significantly more than the writes.

My question (and it is big one) is should I store the data in a database (for the writes) and also have some sort of cache which will be used for the reads? or do I use two databases? or is there a better solution?

Also I will have to resolve concurrency issues which I think optimistic locking on the database will resolve.

I have a fair bit about CQRS over the last few months but not sure if this is the way to go.

Any ideas?

答:
If it's a system with any sort of scale involved (i.e. multiple users), you are almost certainly going to need a database.  You should only need one. Databases are already designed to handle concurrency.

Caching will come into play if, and when, you become the next Netflix.  In other words, YAGNI (You ain't gonna need it, at least not yet).  Caching is intended to be bolted on to an existing system so, if your software is architected sensibly, you should be able to add it later.

Is CQRS "Command Query Responsibility Segregation?"  If you pick a sensible architecture like MVC, you should get those sort of best practices for free.