答:
Alternate idea: if your goal is to prevent bugs occurring because people forget there's three views and do something with only two of them that they really should do with all of them, then make a function that makes it impossible to forget:

```<code>setViewVisibilities(0.0f, 0.0f, 1.0f)
</code>```

Now you have something far more powerful - compile time guarantees you haven't forgotten. If you forget a parameter, the compiler will yell at you. This is far more useful than comments or unnecessary code, as it creates a strict named protocol that enforces the property you care about.

For the case where view3 doesn't need it's visibility changed, you could add some behavior where passing a special value like -1.0 or nil or something along those lines means "don't change the view visibility at all". This gets around the problem of setting visibilities unnecessarily.

Title: Is it better to call a function that doesn't have an effect at that point, IF it improves code clarity?

Body:
I have three views in my program (iOS app). Only one of them is ever active at the same time so I set the visibility off for two of them and switch visibility as the user presses buttons. The views are initialized as visible so I set the visibility off in code before the main view shows.

I can do

```<code>[view1 setAlpha:0.0f];
[view2 setAlpha:0.0f];
</code>```

for two of the views, but now the third one (the one that should be visible at the start of the app) is not addressed. I put a

```<code>[view3 setAlpha:1.0f];
</code>```

after the first two, because I think it keeps it clear that there are in fact three views, not two as one might think when seeing the code. How do other programmers do this? Is it purely preference or are there some conventions?

If the call is very heavy, it's obviously better to not call it when that isn't necessary, but I was wondering about small things like my example.

Body:
Alternate idea: if your goal is to prevent bugs occurring because people forget there's three views and do something with only two of them that they really should do with all of them, then make a function that makes it impossible to forget:

setViewVisibilities(0.0f, 0.0f, 1.0f)

Now you have something far more powerful - compile time guarantees you haven't forgotten. If you forget a parameter, the compiler will yell at you. This is far more useful than comments or unnecessary code, as it creates a strict named protocol that enforces the property you care about.

For the case where view3 doesn't need it's visibility changed, you could add some behavior where passing a special value like -1.0 or nil or something along those lines means "don't change the view visibility at all". This gets around the problem of setting visibilities unnecessarily.


问:
Is it better to call a function that doesn't have an effect at that point, IF it improves code clarity?
I have three views in my program (iOS app). Only one of them is ever active at the same time so I set the visibility off for two of them and switch visibility as the user presses buttons. The views are initialized as visible so I set the visibility off in code before the main view shows.

I can do

```<code>[view1 setAlpha:0.0f];
[view2 setAlpha:0.0f];
</code>```

for two of the views, but now the third one (the one that should be visible at the start of the app) is not addressed. I put a

```<code>[view3 setAlpha:1.0f];
</code>```

after the first two, because I think it keeps it clear that there are in fact three views, not two as one might think when seeing the code. How do other programmers do this? Is it purely preference or are there some conventions?

If the call is very heavy, it's obviously better to not call it when that isn't necessary, but I was wondering about small things like my example.

答:
You have an invariant:

Only a single view (out of 3) is ever active (and visible).

Then, I suggest that you provide a function to switch the activity and visibility of ALL views at once:

```<code>[setActiveView viewID:2]
</code>```

This function will:

check if the view is already active, avoiding unnecessary work

set the view as active, and visible

set the other 2 views as inactive and invisible

It has multiple advantages about a raw call to setVisibility:

friendly: calling it unnecessarily does not create a performance issue

defensive: its single parameter is much harder to botch, whereas for setVisibility it's harder to remember that the range of values is 0.0f - 1.0f and that only one must be set to 1.0f

resilient: the next guy cannot accidentally forget one of the views

adaptable: adding/removing a view does not require scrutinizing all the application code to find where the switches are, a single function (this one) need be updated

Ideally, to help enforce the invariant, no other function should be able to mess up with this setting...

ContentLicense: CC BY-SA 3.0

Body:
You have an invariant:

Only a single view (out of 3) is ever active (and visible).

Then, I suggest that you provide a function to switch the activity and visibility of ALL views at once:

[setActiveView viewID:2]

This function will:

check if the view is already active, avoiding unnecessary work

set the view as active, and visible

set the other 2 views as inactive and invisible

It has multiple advantages about a raw call to setVisibility:

friendly: calling it unnecessarily does not create a performance issue

defensive: its single parameter is much harder to botch, whereas for setVisibility it's harder to remember that the range of values is 0.0f - 1.0f and that only one must be set to 1.0f

resilient: the next guy cannot accidentally forget one of the views

adaptable: adding/removing a view does not require scrutinizing all the application code to find where the switches are, a single function (this one) need be updated

Ideally, to help enforce the invariant, no other function should be able to mess up with this setting...


问:
What's the best way to run a technical book club?
At work, we've been doing lunchtime book clubs for a while. So far we've done:

Clean Code

Working Effectively with Legacy Code

The Pragmatic Programmer

We read a chapter per week, and one person is assigned to present over the content and help facilitate discussion.  Of the three, we've probably had the most success with The Pragmatic Programmer. It seems like the more technically complicated the content was, the more people tended to drop out as the book went along.

I'd like to do a technically-heavy book like SICP or Java Concurrency in Practice, but I don't know of good ways to make this work with the format we're currently doing. What advice do you have?

答: When dealing with technical details I like to try them myself so that I can tackle problems and overcome them. Therefore I think that if you would like to whet the appetite of your programmers with some technical stuff you should present the cool stuff regarding this subject and point them to the book that you want them to read. This is what Microsoft doing on PDC or other conferences. They put the cool stuff and give you some resources to read more. Hope that helps.</p>

ContentLicense: CC BY-SA 2.5


问:
What is it about functional programming that makes it inherently adapted to parallel execution?
I've been reading over and over that functional languages are ideal (or at least very often useful) for parallelism.  Why is this?  What core concepts and paradigms are typically employed and which specific problems do they solve?

On an abstract level, for example, I can see how immutability might be useful in preventing race conditions or other problems stemming from resource competition, but I can't put it any more specifically than that.  Please note, however, that my question is broader in scope than just immutability -- a good answer will provide examples of several relevant concepts.

答:
Lets first look at why procedural programming is so bad at concurrent threads.

With a concurrent programming model, you are writing sequential instructions that (by default) expect to be run in isolation.  When you introduce multiple threads, you need to explicitly control access to prevent concurrent access to a shared variable when those changes may affect each other.  This is difficult programming to get right, and in testing, it is impossible to prove that it has been done safely.  At best, you can only confirm that on this test run, no observable issues occurred.

In functional programming, the problem is different.  There is no shared data. There is no concurrent access to the same variable.  Indeed, you can only set a variable once, there are no "for loops", there are just blocks of code that when executed with a given set of values will always perform the same outcome.  This makes testing both predictable and a good indicator of correctness.

The problem the developer has to solve in functional programming is how to design the solution minimising common state.  When the design problem requires high levels of concurrency and minimal shared state, functional implementations are a very effective strategy.


问:
How to have TFS automatically add certain tasks to new work items?
We use TFS at my workplace to manage our source code and track development.

Whenever we have a bug or work to do, we always have to do the following two tasks as a minimum:

Test the work, or decide whether testing is needed.

Update the release notes for the current release, or decide whether it needs a specific entry.

Other tasks are specific to the work being done, but I find myself constantly typing "Testing" and "Release notes" when adding new work items.

Is there a way to get TFS to automatically add these two tasks whenever a new bug or work item is created?  In the rare case these tasks are not required, they can simply be marked as done or removed for that work item, so I'm not concerned about the impact in making this automatic.

I have had a look around and it looks like I might be able to create a PowerShell script to add the tasks to any work items that are missing them, which may be the way to go.

答:
Important note

There is no out-of-the-box feature for this, and usually I try to steer people away from generic tasks like "Test", "Deploy" and have them think about testing all the way through the work and to have them define intermediate tests they want to execute along the way.

Generic stuff such a Release Notes and Deployment can be completely automated. Probably also using powershell ;).

So I try to have people put their focus on using their Powershell-fu on automating these generic and bad tasks.

The answer

Of course that's not the answer to your question per-se. So here is the real answer, yes, powershell is an option, you can call into the REST api or the Client Object model and use that to query wok items and to create new work items. The API broadly used and there is a lot of information out there in terms of blog posts and the like. Or you can create a small console application that also uses the same Client Object Model.

You can also use the SOAP api from the alerts to get notified when a workitem is added or changed and have your code act on that by adding the required child work items.

An alternative to the SOAP api is to use something like the TFS Aggregator, which integrates into the server itself. It uses the same TFS client object model. I'm part of the team building it and we've released for both 2013u2+ and 2015+. The TFS Aggregator allows you to write rules that use Powershell of C#-script to act on work item changes. It already has a lot of work done to it to prevent common pitfalls when working with the Client Object Model from an automation perspective.

The TFS Aggregator is a serverside pugin for TFS 2013 (update 2 and later) which now has the ability to create new work items based on rules. An example task can be found here:

https://github.com/tfsaggregator/tfsaggregator/wiki/Auto-Create-Children


问:
What's the right way to work with a graphic designer?
Recently, we worked with a graphic designer (arranged by the client) to provide the skin for a Django+Bootstrap application we had built. The designer provided a series of static images of the new layout, along with a document describing some technical attributes (font sizes, colours, a few dimensions etc).

It turned out to be incredibly time consuming to implement this. Although the whole site was basically a front page, an index page, and half a dozen detail pages, I spent at least 5 days just implementing the CSS and HTML changes. So I'll go out on a limb and call this The Wrong Way.

My basic approach was:

Compare the static image and current rendering, and notice a difference.

Guess what change would be need in the CSS/HTML

Make that change

Go to step 1.

Some of the particular issues were me not understanding that the design included a change from 8 columns to 12, some images provided in the wrong format (.png's can render differently on different browser/platform combinations), hassles trying to undo Bootstrap's styling, the usual CSS wrestling to achieve pixel perfect rendering etc. And occasionally I had to reorganise the HTML templates to get a certain behaviour.

What's the right way?

答:
As a graphic designer turned full stack web developer, for me this has so far been the easy part. I find that a lot of times there is a communication gap between a UX design team and the developers that implement the product. Sure, documents help, but the process can begin to feel a lot more natural once some face to face conversations about strategy occur. Also, I know that time is scarce for everyone, but try to get involved during the design and layout phase. This can help tremendously when communication is needed between a designer and developer. The project takes on more of a unified team effort and less of a "Well, I'm done my part, over the wall it goes" scenario.
I have found it to be very beneficial to have the design and development work happening in parallel, encourage the design team to supply you with wireframes early in the process. That way, you can do one style pass that deals solely with layout and positioning. Then, as the deaigns become more rich and complete. Take another CSS pass for appearance and other style attributes. At least this keeps you from having to focus on everything at once.</p>


答:
Pure functional code is thread-safe by default.

That, by itself, is already a huge win. In other programming languages, designing blocks of code that are completely thread-safe can be really, really challenging. But a pure functional language forces you to make everything thread-safe, except in the few places where you explicitly do something that's not thread-safe. You could say that in imperative code, being thread-safe is explicit [and hence typically rare], whereas in pure functional code, thread-unsafe is explicit [and hence typically rare].

In an imperative language, most of the problem is how to add enough locking to prevent weird data races, but not too much to kill performance or provoke random deadlocks. In a pure functional language, most of the time such considerations are moot. The problem now is "only" figuring out how to divide the work up evenly.

At one extreme, you have a tiny number of parallel tasks which don't use all available cores. At the other extreme, you have billions of tiny tasks which introduce so much overhead that everything slows to a crawl. Of course, trying to figure out "how much work" a particular function call does is often very difficult indeed.

All of these problems exist in imperative code as well; it's just that the imperative programmers are usually too busy wrestling with just trying to make the thing work at all to worry about delicate fine-tuning of task sizes.

Title: What is it about functional programming that makes it inherently adapted to parallel execution?

Body:
I've been reading over and over that functional languages are ideal (or at least very often useful) for parallelism.  Why is this?  What core concepts and paradigms are typically employed and which specific problems do they solve?

On an abstract level, for example, I can see how immutability might be useful in preventing race conditions or other problems stemming from resource competition, but I can't put it any more specifically than that.  Please note, however, that my question is broader in scope than just immutability -- a good answer will provide examples of several relevant concepts.


问:
Purpose of encrypted product ID/key in shopping carts
I'm a newbie for PHP ecommerce applications. For my academic activities, I need to complete a shopping cart system with basic shopping cart functions. I have studied several apps which are already developed. I noticed that most of them are using encrypted product ids. I mean they are not just plain numbers. As I think the purpose is to make it ambiguous for those who see it and think about some malicious activity. Not related with the security directly.

I know this is not suitable question for SO. I do not want any source code. Can anyone please answer to give me some light in this area?

Update
I might be wrong definitely. Should be a hash there. Please find this example product edit url. I really meant such a thing.

```<code>example.com/product/dc85058a-a69e-11e5-e112-44da4901619b/edit
</code>```

答:
The answer to your question, that number you are seeing is called a GUID.  Its a number format that can be generated quickly, and is mathematically just short of being guaranteed that neither yourself or anyone else will generate a new guid, with the same value.

It is quite likely that this is used as the identifier in the database record for that product.  Its less likely that this is a manufacturers product number.

My original answer is below, although no longer relates to the question that was asked.

There are places during the on-line purchase where encryption, and security are critical.  In particular the interactions between the website and the on-line payment system are critical, for ensuring that the customer pays the amount that the merchant expects, and that the merchant can rely 100% on the payment system notification that a specific order has been paid.

However, during the browsing and shopping phase, product ID's are just a way to identify the items that the customer is considering buying.  I see no value in making this part of the process more complex than it needs to be.

What you may be looking at, is the cookie data.  If the shopping basket is being stored as a cookie, by the web browser then this would explain the use of encryption. It is good practice for cookie data to be encrypted.


问:
How does Functional Programming's immutability feature work with CQS?
Given immutability (which is often encouraged and said to be one of building blocks of functional programming) and CQS (which says that commands should not return a value other than void/unit), how do these work together?

For example:

How would you perform a series of commands (eg multiple file copies, which can throw all kinds of exceptions but should not crash the program), and collect their success or failure+reason in a list of results?

I can imagine some solutions in OO like throwing events or giving access to a Report instance (either static or passing it in by reference), but what are the possibilities in functional languages which do not break CQS?

答:
Given immutability (which is often encouraged and said to be one of building blocks of functional programming) and CQS (which says that commands should not return a value other than void/unit), how do these work together?

There are no commands in functional programming. Period.

A function's result can only depend on its arguments, and it must be the same every time you call the function with the same arguments. There can be no mutation and no side-effects. Functions must be referentially transparent, which means that I can always replace the function application with its result anywhere and everywhere in the program without changing the meaning of the program. (In particular, this means that if I have a procedure that returns void (i.e. nothing), I can replace it with nothing everywhere, which obviously will change the meaning of the program, and thus such a procedure cannot exist in functional programming.)

Of course, something command-like must still be achievable, otherwise your programs would be pretty boring. As Simon Peyton-Jones ones said during an introduction to Haskell, if your program has no side-effects, it cannot print a result, it cannot ask for input, it cannot interact with the network or the file system, all it does is heat up the CPU, after which someone from the audience interjected that heating up the CPU is also a side-effect, so, technically speaking, if you want your program to have no side-effects, you cannot even run it. Clearly, that is ridiculous.

So, side-effects have to be modeled somehow.

One way to do this, is to imagine that you can somehow describe the state of the entire universe in a datastructure and then pass an instance of that datastructure describing the current state of the world into a function, and the function then returns a new instance of that datastructure describing the new state of the world. Of course, this cannot literally work, describing the state of the world requires at least as much memory as the entire world has. It's a conceptual model.

There's a slight problem: the function could pass the old state of the world on to another function, for example, now there are two functions which have the same state of the world, and both of them could return a different new state of the world. Or, a function could hold on to the old state of the world, and later return it back, effectively time-traveling into the past. Of course, this must be somehow prohibited. One solution would be linear types, which are types that ensure that its values are used only once. Clean does this, it has World types, which are a special kind of linear types for such world values.

In Haskell, all side-effects must take place in a monad. Monads are a way of augmenting computation with additional structure. You can imagine it as the monad threading the world value described above through the different functions but without ever actually directly exposing the value to the functions. (In reality, once you have monadic I/O, you don't actually need the world value any more, the monad itself provides the structure for side-effects.) Earlier attempts at modeling I/O in Haskell included I/O based on lazy streams and continuation-based I/O, which also work, but monadic I/O was found to be easiest to work with.

In all these different models, side-effects will always show up in the types of side-effecting functions. IOW, your commands are now functions which return, takes an argument, or both, a value of a side-effecting type.

A nice side-effect (hah!) of this is that different kinds of side-effects can get their own types, instead of having a catch-all "this is a side-effect" type. For example, in Haskell, there is the well-known IO type, which basically says "anything can happen". But there are also types like Reader (reads global state, an OO example would be a global singleton configuration object that is dependency-injected), Writer (writes global state, e.g. a logger, again, typically solved in OO with a global singleton logger object that gets injected), State (mutable shared state, but no other kind of side-effect), STM (Software Transactional Memory, like State but transactional for parallelism).

The "separation" portion of CQS is achieved using the type system. Commands simply have types that are incompatible with queries. I.e. a "command" which changes some global integer will have State Int somewhere in its type, a command which prints an integer will have type Int -> IO Int and so on.


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答: I try and write tests before the code.  I run my tests at least twice before a commit.  It then runs again with the Continous Integration server.</p>


问:
What is the difference between business and application logic?
Please note that I asked the same question on stackoverflow but they directed me to ask here.

While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.

Here  they say that they are the same but the answer here is totally different.

For me I understand it in the following way:

If we look up for the definition of the Logic word in Google we will get

system or set of principles underlying the arrangements of elements in
a computer or electronic device so as to perform a specified task.

So, if the logic is set of principles underlying the arrangements of elements then the business logic should be set of principles underlying the arrangements of the business rules, in other words it means the rules that should be followed to get a system reflects your business needs.

And for me the application logic is the principles that the application based on, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.

So please could anybody help me to get rid of confusion about the difference between the application and the business logic.

答:
I agree with SO's LoztInSpace that this is quite opinionated answer and that everyone can have slightly different definitions. Especially if historical influences are involved. This is how I would define the terms:

Business logic is logic, that is created with collaboration and agreement with business experts. If business expert says that "Customer cannot withdraw more money than he has in his account.", then this is a business rule. In ideal world, this logic would be in some kind of library or service, so it can be either reused across multiple applications or changed in all relevant applications at once.

Application logic is simply everything else. Example can be "clicking this button opens window to add new customer". It has nothing to do with business, but it is still logic that needs to be implemented. In ideal world, application logic will use library or service, that is implementing the business rules. Multiple application, each with different application logic, can reuse one business logic. Imagine web app, web service and mobile app all operating using one business logic, but each clearly need different application logics.

The reason why I think those two get mixed up, is that keeping them separate is extremely hard. Even if you do your most to keep them separate, use cases surface where you have to mix them up. If for example you have all your business logic in service, it keeps it separate. But having some business logic in local application that is using the service might increase responsiveness or user comfort, because the local application doesn't need to call service for every small change.

Another reason why they are mixed together is that for many non-technical people. UI is "the application", so anything reflected in the UI is important. In the ideal "business logic" case, there is no UI. There would probably be suite of automated tests to verify the logic, but nothing that can be shown to business people. So to business people, everything is same kind of "logic". IMO.

ContentLicense: CC BY-SA 4.0


答:
Na, they're just different terms for the same thing - the "middle tier" of program code that does the things you want your program to perform. Like many things in software, there are no hard-and-fast terminology for pieces of a system, as there are no single formal definitions for building systems.

So sometimes people will call it business logic, others application logic, others will call it program logic, its all much of a muchness. Don't bother trying to define this so rigidly, nearly every system varies in how its built so be glad there's only this minor level of vagueness in terminology!

Title: What is the difference between business and application logic?

Body:
Please note that I asked the same question on stackoverflow but they directed me to ask here.

While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.

Here  they say that they are the same but the answer here is totally different.

For me I understand it in the following way:

If we look up for the definition of the Logic word in Google we will get

system or set of principles underlying the arrangements of elements in
a computer or electronic device so as to perform a specified task.

So, if the logic is set of principles underlying the arrangements of elements then the business logic should be set of principles underlying the arrangements of the business rules, in other words it means the rules that should be followed to get a system reflects your business needs.

And for me the application logic is the principles that the application based on, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.

So please could anybody help me to get rid of confusion about the difference between the application and the business logic.


答:
Every system or application is going to have its own definitions of what is business logic and what is application logic. It will either be explicit or implicit.

In my experience data driven applications (e.g. DBs etc.) tend to have a more formal definition of what the business logic is.

The application logic tends to focus on getting information from point A to point B, the business logic centres around what the information is - and the language of the business logic is usually domain specific. Put another way, the application logic is focused on the question "how does it work?", the business logic on "what does it do?" - again, the distinction can be very fuzzy and is more often that not domain specific.


问:
Is there a downside to using AggressiveInlining on simple properties?
I bet I could answer that myself if I knew more about tools to analyze how C#/JIT behaves but since I don't, please bear with me asking.

I have simple code like this :

```<code>    private SqlMetaData[] meta;

    private SqlMetaData[] Meta
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            return this.meta;
        }
    }
</code>```

As you can see I put AggressiveInlining because I feel like it should be inlined.

I think. There's no guarantee the JIT would inline it otherwise. Am I wrong?

Could doing this kind of thing hurt the performance/stability/anything?

答:
Compilers do a lot of optimizations. Inlining is one of them, whether the programmer wanted or not. For example, MethodImplOptions does not have an "inline" option. Because inlining is automatically done by the compiler if needed.

Many other optimizations are especially done if enabled from the build options, or "release" mode will do this. But these optimizations are kind of "worked for you, great! Not worked, leave it" optimizations and usually give better performance.

```<code>[MethodImpl(MethodImplOptions.AggressiveInlining)]
</code>```

is just a flag for the compiler that an inlining operation is really wanted here. More info  here and here

To answer your question;

There's no guarantee the JIT would inline it otherwise. Am I wrong?

True. No guarantee; Neither C# has a "force inlining" option.

Could doing this kind of thing hurt the performance/stability/anything?

In this case no, as it is said in Writing High-Performance Managed Applications : A Primer

Property get and set methods are generally good candidates for inlining, since all they do is typically initialize private data members.

Body:
Compilers do a lot of optimizations. Inlining is one of them, whether the programmer wanted or not. For example, MethodImplOptions does not have an "inline" option. Because inlining is automatically done by the compiler if needed.

Many other optimizations are especially done if enabled from the build options, or "release" mode will do this. But these optimizations are kind of "worked for you, great! Not worked, leave it" optimizations and usually give better performance.

[MethodImpl(MethodImplOptions.AggressiveInlining)]

is just a flag for the compiler that an inlining operation is really wanted here. More info  here and here

To answer your question;

There's no guarantee the JIT would inline it otherwise. Am I wrong?

True. No guarantee; Neither C# has a "force inlining" option.

Could doing this kind of thing hurt the performance/stability/anything?

In this case no, as it is said in Writing High-Performance Managed Applications : A Primer

Property get and set methods are generally good candidates for inlining, since all they do is typically initialize private data members.


问:
Manuals - How Up To Date?
If you have a product that has been in the market for a long time, but it is still in active development daily - how often should the manuals be updated? If your users are constantly updated to the bleeding edge version due to the fact that your organization sees fit that the latest bug fixes are always in the shipped version. Meaning, you could fix a bug one day and next day it is hitting production.</p>

答: The documentation should by in sync with whatever software you are shipping to a customer. Any other mis-match is going to give you problems. And if you don't have a writer on staff, try contractors. Once you find one you like, keep him on retainer.</p>

Title: Manuals - How Up To Date?


答:
The hardest part of writing parallel code is to stop one thread from reading data that is being updated by anther thread.

A common solution to this is to use immutable objects, so that once an object is created it is never updated.      But in real life data has to be change, therefore “persistence” data is used, where every update returns a new object – this can be make efficient by careful choose of data structures.

As functional programming does not allow any side effects, “persistence objects” are normally used when doing functional programming.
So the pain a functional programmer is forced to take due to the lack of side effects, leads to a solution that works well for parallel programming.

An additional benefit being that functional language systems check that you are keeping to the rules, and have lots of tools to help you do so.


问:
Why doing everything with one software project is wrong?
I am newly employed by a company. After a couple of weeks, I have heard lots of time that there is a huge project which most of the programmers are working on it. They call it something like Managing Everything Software. Then, somehow I got the document which they define what the MES will do. The document itself was 60 pages but contains only about what it does, not how it does.

The document simply describes properties of these softwares:

Enterprise Resource Planning (ERP),

Human Resources Management System (HRMS),

Content Management System (CMS),

Learning Content Management System (LCMS),

Enterprise Social Platform,

Document and Workflow Management System,

File Management System that can search on any file type like PDF, Word, etc.(like Elastic Search)

LDAP based authentication and authorization

Not only that, all these will be wired to each other.

It may seem those are different software projects but they are not.
The project is, to make all of these with one big software:

Most of you already know the divide and conquer method to apply to software development. If it would be me, I would divide those tasks into small pieces. Then define database tables for each piece. Every piece would be responsible for their own data. No other part would have direct access to those tables which belong to other piece of program. If they need to access it, they would ask the responsible program to do it. This is pretty much an architecture of the SOA. But the way this big project is written, never mentions those pieces nor how connections between them will be. According to documentation, every part can see or change any table (if authorized).

Since people so involved in what the software will achieve, they pretty much seem in a position which they had narrowed vision. The project is reflected as silver bullet for all problems. I have to tell them we should slice the project into little ones and connect them like in SOA and this will make everything much more easier. But the problem is I don't know how to convince them that their approach is not the best way to do it. I have to provide solid evidence, sources, books, links and maybe videos to convince them that this is not gonna work.

I couldn't find any documents to support me(since my English is not so great to search this non technical stuff on internet). Can you please provide any information about why doing everything with one software project is wrong?

答:
You are a bit confused with how software documentation is developed.

What you read is the requirements document. There are entire books written at length of how to engineer and document requirements, but all you need to know is that the requirements document specifies what the software is supposed to do. It makes no mention of how, since these documents are usually shared with management, who have little understanding (usually) of how software is constructed. There is very little to no technical jargon written into this document.

How to accomplish the requirements is up to you - the developer - to figure out. Usually before code is written for a large project, a Design Document is written that explains the how to the what. This is written for the development team so the project can be built and more importantly, maintained!. Here is where you put the fancy diagrams, the languages/technologies you will use, testing methods, etc. If you work for a good company, they will usually let the developers choose which technologies and languages are the best fit for the job.

Essentially, figuring out how code is supposed to meet the requirements is software engineering!

P.S. That being said, if you find the requirements to be impossible (my professors used to call this "wings on a car"), then it is your responsibility to bring it up to your Project Manager. They will then either work with the customer to change the requirements to make it more reasonable, or make you do it anyway. Unfortunately, it usually ends up being the latter.


答:
I'm not sure what you mean by "one and only one software!" but I think you may be reading too much into this document.  Since it talks about what not how, it sounds much more like a high level requirements document for a system and not a single application.  This is actually a very important document for any large project.  I'm sure that if you were to look at the equivalent documents for SAP or Oracle or MS Windows, they would be larger and more complex, but these were successful projects, so big doesn't mean wrong.

Let's look at the problem a different way.  If all of this functionality is needed to help the company function efficiently, doesn't it make sense to have a document that lists all of these parts, so that they aren't all built separately and then don't work together?

It is up to your team to decompose the what into the how.  You are on the right path if you believe these should not all be part of a single application executable.  There is no reason to believe this can't be done based on the information we have so far.  As long as people recognize the size of the effort and the resources required, looks like you'll have work (a job) for a while.  Good Luck!

Title: Why doing everything with one software project is wrong?

Body:
I am newly employed by a company. After a couple of weeks, I have heard lots of time that there is a huge project which most of the programmers are working on it. They call it something like Managing Everything Software. Then, somehow I got the document which they define what the MES will do. The document itself was 60 pages but contains only about what it does, not how it does.

The document simply describes properties of these softwares:

Enterprise Resource Planning (ERP),

Human Resources Management System (HRMS),

Content Management System (CMS),

Learning Content Management System (LCMS),

Enterprise Social Platform,

Document and Workflow Management System,

File Management System that can search on any file type like PDF, Word, etc.(like Elastic Search)

LDAP based authentication and authorization

Not only that, all these will be wired to each other.

It may seem those are different software projects but they are not.
The project is, to make all of these with one big software:

Most of you already know the divide and conquer method to apply to software development. If it would be me, I would divide those tasks into small pieces. Then define database tables for each piece. Every piece would be responsible for their own data. No other part would have direct access to those tables which belong to other piece of program. If they need to access it, they would ask the responsible program to do it. This is pretty much an architecture of the SOA. But the way this big project is written, never mentions those pieces nor how connections between them will be. According to documentation, every part can see or change any table (if authorized).

Since people so involved in what the software will achieve, they pretty much seem in a position which they had narrowed vision. The project is reflected as silver bullet for all problems. I have to tell them we should slice the project into little ones and connect them like in SOA and this will make everything much more easier. But the problem is I don't know how to convince them that their approach is not the best way to do it. I have to provide solid evidence, sources, books, links and maybe videos to convince them that this is not gonna work.

I couldn't find any documents to support me(since my English is not so great to search this non technical stuff on internet). Can you please provide any information about why doing everything with one software project is wrong?


答:
As others have pointed out, these terms do not have one universally accepted meaning. I will describe the definitions I have encountered more often, i.e. in several projects with different companies.

The business logic defines a normalized, general-purpose model of the business domain for which an application is written, e.g.

Classes like Customer, Order, OrderLine, and associations like customer-order, and so on.

General-purpose operations such as registerCustomer, cancelOrder

Very often this class model is mapped to a database model and the mapping is implemented using ORM. The operations are normally performed each in their own transaction and provide the basic API for modifying the database, i.e. the persistent state of the application.

The application logic is a layer built on top of the business logic and serves to implement specific use cases. Application logic modules may use ad-hoc data representation, e.g. a CustomerSummary class without any association to Order if you want to list customers only. Such ad-hoc data representation must be mapped to the underlying normalized representation provided by the business model. For example, CustomerSummary can be defined as a view on top of Customer.

Note that the boundary between the two layers may not be so clearly-defined. E.g. after implementing several use cases one might notice similar data structures in the application logic and decide to unify (normalize) them and move them to the business logic.


问:
Looking to calculate break even price (minus fees) on an individual level without brute forcing
I am trying to calculate the break-even price on an individual product given a percent of the price I sold it for and the price I bought it for. For example: I buy an item for $200 and the fees on the sale of the item are 13% of the final sale price. I want the answer to be $230.

$230 (sale price) * .13 (percent fee) = $29.90 (fee in dollars) (round up to $30)

$230 (sale price) - $200 (item cost) - $30 (fee) = $0 (break even)

So if I buy an item at $200 I need to sell it at $230 just to break even.

This seems like an easy problem but I haven't been able to figure out a way that isn't brute force because the fee changes with every sold price so there doesn't seem like a way to know the fee in advance. I've been just guessing and plugging in the numbers but there has got to be another way so I can write up a simple script.

I also don't care about cents, I'm going to round everything up.

I am looking for a non-brute algorithm. The only thing I can come up with is brute forcing it and I'm sure there is a better algorithm that exists. Looking at various inputs and outputs I don't see a pattern.

答:
After you take off the 13%, you have 87% remaining.  You multiply by 0.87 to get your revenue:

```<code>$230 * 0.87 == $200.10
</code>```

From this point, it's basic algebra to show if you know the $200 you divide by 0.87 to get $230.  So, your formula is:

```<code>original price / (1 - fees)
$200 / (1 - 0.13) = $229.89
</code>```

Body:
After you take off the 13%, you have 87% remaining.  You multiply by 0.87 to get your revenue:

$230 * 0.87 == $200.10

From this point, it's basic algebra to show if you know the $200 you divide by 0.87 to get $230.  So, your formula is:

original price / (1 - fees)
$200 / (1 - 0.13) = $229.89


问:
Is there a need to keep tests for simple (self-contained) functions?
Consider this:

```<code>public function polynominal($a, $b, $c, $d)
{
    return  $a * pow($x, 3) + $b * pow($x, 2) + $c * $x + $d;
}
</code>```

Suppose you write various tests for the above function and prove to yourself and others that "it works".

Why not then remove those tests, and live happily ever after?  My points is that some functions do not need to be tested continuously after they have been proven to work.  I am looking for counter-points that state, yes these functions still need to be tested, because: ...   Or that yes, these do not need to be tested...

答:
Yes.  If we could say with 100% confidence, with certainty: this function will never be edited and will never run in a context which could cause it to fail - if we could say that, we could drop the tests and save a few milliseconds on every CI build.

But we can't.  Or, we can't with many functions.  And it's simpler to have a rule of running all the tests all the time than to put effort in determining exactly what confidence threshold we're satisfied with, and exactly how much confidence we have in the immutability and infallibility of any given function.

And processing time is cheap.  Those milliseconds saved, even multiplied many times, don't add up to nearly enough to justify taking the time with every function to ask: do we have sufficient confidence that we need never test it again?


答:
Regression testing

It's all about regression testing.

Imagine the next developer looking at your method and noticing that you are using magical numbers. He was told that magical numbers are evil, so he creates two constants, one for the number two, the other one for the number three—there is nothing wrong in doing this change; it's not like he was modifying your already correct implementation.

Being distracted, he inverts two constants.

He commits the code, and everything seems to work fine, because there are no regression testing running after each commit.

One day (could be weeks later), something breaks elsewhere. And by elsewhere, I mean in the completely opposite location of the code base, which seems to have nothing to do with polynominal function. Hours of painful debugging lead to the culprit. During this time, the application continues to fail in production, causing a lot of issues to your customers.

Keeping the original tests you wrote could prevent such pain. The distracted developer would commit the code, and nearly immediately see that he broke something; such code won't even reach the production. Unit tests will additionally be very precise about the location of the error. Solving it wouldn't be difficult.

A side effect...

Actually, most refactoring is heavily based on regression testing. Make a small change. Test. If it passes, everything is fine.

The side effect is that if you don't have tests, then practically any refactoring becomes a huge risk of breaking the code. Given that is many cases, it's already difficult to explain to the management that refactoring should be done, it would be even harder to do so after your previous refactoring attempts introduce multiple bugs.

By having a complete suite of tests, you are encouraging refactoring, and so better, cleaner code. Risk-free, it becomes very tempting to refactor more, on regular basis.

Changes in requirements

Another essential aspect is that requirements change. You may be asked to handle complex numbers, and suddenly, you need to search your version control log to find the previous tests, restore them, and start adding new tests.

Why all this hassle? Why removing tests in order to add them later? You could have kept them in the first place.

Title: Is there a need to keep tests for simple (self-contained) functions?

Body:
Consider this:

```<code>public function polynominal($a, $b, $c, $d)
{
    return  $a * pow($x, 3) + $b * pow($x, 2) + $c * $x + $d;
}
</code>```

Suppose you write various tests for the above function and prove to yourself and others that "it works".

Why not then remove those tests, and live happily ever after?  My points is that some functions do not need to be tested continuously after they have been proven to work.  I am looking for counter-points that state, yes these functions still need to be tested, because: ...   Or that yes, these do not need to be tested...


问:
Is it good practice to store software version numbers in VCS?
A product version, such as v1.0.0.100, represents not only a unique production release of software, but helps identify feature sets and hotfix stages for said product. Right now I see two ways to maintain the final package/build/binary version of a product:

Version Control. A file somewhere stores the version number. Continuous Integration (CI) build server will have a script to build the software that uses this checked-in version number to apply it to all areas of the software needed (binaries, installer packages, help pages, documentation, etc).

Environment and/or build parameters. These are maintained outside of version control (i.e. they are not tied to the snapshot/tag/branch). The build scripts distribute and use the number in the same way, however they just obtain the value differently (it is provided to the build script, instead of having the script know where to get it relative to the source tree).

The problem with the first approach is that it can complicate merges across mainline branches. If you still maintain 2 parallel releases of the same software, you will resolve conflicts when merging between the two mainlines if the version has changed on both since the last merge.

The problem with the second approach is reconciliation. When you go back to a release 1 year ago, you will rely solely on the tag information to identify its release number.

In both cases, there might be certain aspects of the version number that are not known prior to the CI build. For example, a CI build may programmatically put in a 4th component that is really the automated build number (e.g. 140th build on the branch). It might also be a revision number in VCS.

What is the best way to keep up with a software's version number? Should the "known" parts always be maintained in VCS? And if so, are the conflicts across mainline branches an issue?

Right now we maintain our version number via parameters specified and maintained in the CI build plan (Atlassian Bamboo). We have to be careful before merging to our master branch that the version numbers are properly setup in advance of the CI build kicking off. With regards to the Gitflow workflow, I feel that if the version number were tracked in source control, we could guarantee it is setup properly when we create our release branch in preparation of the release. QA would perform final integration/smoke/regression testing on this branch and upon signoff, a merge to master takes place which signals commitment to release.

答:
Personally, I choose option 3: keep versioning information in VCS metadata, specifically, tags.

Git makes it very easy to do so, because there is a command git describe, which can uniquely describe a commit based on a tag. Here's how it works:

If the current commit is tagged, output the name of the tag.

Otherwise, walk the history backwards until you find a tag and then output a description in the following format: <tag>-<number of commits since the tag>-g<abbreviated commit hash>.

If there are uncommitted changes in the workingtree, append -dirty.

So, if you are doing a release build, and have the commit tagged 1.2.3, it will output 1.2.3. If you are currently working on 1.2.4 and you made 4 commits since 1.2.3, and have uncommitted changes in the tree, it will output 1.2.3-4-gdeadbee-dirty.

This is guaranteed to be unique and monotonic, as well as human-readable, and thus can be used directly as a version string. The only thing you have to ensure is a proper naming convention for tags.


答:
I compile & test if one of the following conditions is satisfied:

Last compile was 15 minutes ago

Last compile was 25 lines ago

New function/subroutine has been implemented

Major change

New feature (or a bug disguised as a feature)

Bug fix (removed a "feature")

I'm Bored

Title: How often do you run & test your code while programming?

Body:
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?


问:
Is Python's calendar.month_name implementation of an empty string in the first index good practice or poor design?
The documentation states:

An array that represents the months of the year in the current locale.
  This follows normal convention of January being month number 1, so it
  has a length of 13 and month_name[0] is the empty string.

Is this level of skeuomorphism warranted? Or is it confusing and potentially bug prone to start an array of expected values with no value?

答:
It's better (and less confusing) to have the empty [0] placeholder at the beginning of the array so that you can just plug the month directly into the array indexer, than it is to start January at month 0 and have to perform a bit of conversion math to get the correct array index each time.

Sensible date implementations should not allow a month zero.  Note that, for historical reasons, arrays typically start at an array index of zero.


答:
Everything said in the other answers is correct, but I will add one more.

Documentation

Unit tests, if well written, can explain to a developer exactly what a function does, what its input/output expectations are, and more importantly, what behavior can be expected of it.

It can make spotting a bug easier and lower confusion.

Not everybody remembers polynomials, geometry, or even algebra :)  But a good unit test checked in to version control will remember for me.

For an example of how useful it can be as documentation, look at the Jasmine introduction: http://jasmine.github.io/edge/introduction.html  Give it a few seconds to load, then scroll to the bottom.  You'll see the entire Jasmine API documented as unit test output.

[Update based on feedback from @Warbo] Tests are guaranteed to be up-to-date as well since if they are not, they will fail, which generally will cause a build failure if CI is used.  External documentation changes independently of the code, and therefore isn't necessarily up to date.


答:
Yes. It is good practice to keep most of the version number in vcs. If we consider semantic versioning semver.org where we have major.minor.patch.build the first three must live in vcs. The last one can be a incrementing number from your build server used to backtrack the specific commit that a binary is made from.

To facilitate this in .NET we have made a small cmd line exe that is committed to git. With a pre-build event, it picks up the build number which teamcity tagged during build. This cmd line tool auto generates a class with one constant containing the build number. The rest of the version number: major.minor.patch is just a normal constant in another file. These two shared files are included in every assembly in a solution as a link(alt+shift-drag).

This approach is powerfull enough that we can have teamcity build and test our code. Push to azure and have kudu build it again but with the teamcity build number as the version of the dll's.

Title: Is it good practice to store software version numbers in VCS?

Body:
A product version, such as v1.0.0.100, represents not only a unique production release of software, but helps identify feature sets and hotfix stages for said product. Right now I see two ways to maintain the final package/build/binary version of a product:

Version Control. A file somewhere stores the version number. Continuous Integration (CI) build server will have a script to build the software that uses this checked-in version number to apply it to all areas of the software needed (binaries, installer packages, help pages, documentation, etc).

Environment and/or build parameters. These are maintained outside of version control (i.e. they are not tied to the snapshot/tag/branch). The build scripts distribute and use the number in the same way, however they just obtain the value differently (it is provided to the build script, instead of having the script know where to get it relative to the source tree).

The problem with the first approach is that it can complicate merges across mainline branches. If you still maintain 2 parallel releases of the same software, you will resolve conflicts when merging between the two mainlines if the version has changed on both since the last merge.

The problem with the second approach is reconciliation. When you go back to a release 1 year ago, you will rely solely on the tag information to identify its release number.

In both cases, there might be certain aspects of the version number that are not known prior to the CI build. For example, a CI build may programmatically put in a 4th component that is really the automated build number (e.g. 140th build on the branch). It might also be a revision number in VCS.

What is the best way to keep up with a software's version number? Should the "known" parts always be maintained in VCS? And if so, are the conflicts across mainline branches an issue?

Right now we maintain our version number via parameters specified and maintained in the CI build plan (Atlassian Bamboo). We have to be careful before merging to our master branch that the version numbers are properly setup in advance of the CI build kicking off. With regards to the Gitflow workflow, I feel that if the version number were tracked in source control, we could guarantee it is setup properly when we create our release branch in preparation of the release. QA would perform final integration/smoke/regression testing on this branch and upon signoff, a merge to master takes place which signals commitment to release.


答:
Because nothing is so simple that there can't be bugs.

Your code, while on the face of it looks to be bug free. It is in fact a simple programmatic representation of a polynomial function.

Except it has a bug...

```<code>public function polynominal($a, $b, $c, $d)
{
    return  $a * pow($x, 3) + $b * pow($x, 2) + $c * $x + $d;
}
</code>```

$x is not defined as an input to your code, and depending on the language or the runtime, or the scoping, your function may not work, may cause invalid results, or may crash a spaceship.

Addendum:

While you may consider your code bug free for now, how long that remains the case is hard to say. While it might be argued that writing a test for such a trivial piece of code isn't worth it, having already written the test the work is done and deleting it is deleting a tangible safe guard.

Of additional note is code coverage services (like coveralls.io) that give a good indication of the coverage a test suite provides. By covering every line of code you give a decent metric of the quantity (if not the quality) of testing you perform. In combination with a lot of small tests, these services at least tell you where not to look for a bug when it happens.

Ultimately, if you already have a test written, keep it. Because the space or time saving from deleting it will likely be much less than the technical debt later on if a bug does arise.

Body:
Because nothing is so simple that there can't be bugs.

Your code, while on the face of it looks to be bug free. It is in fact a simple programmatic representation of a polynomial function.

Except it has a bug...

public function polynominal($a, $b, $c, $d)
{
    return  $a * pow($x, 3) + $b * pow($x, 2) + $c * $x + $d;
}

$x is not defined as an input to your code, and depending on the language or the runtime, or the scoping, your function may not work, may cause invalid results, or may crash a spaceship.

Addendum:

While you may consider your code bug free for now, how long that remains the case is hard to say. While it might be argued that writing a test for such a trivial piece of code isn't worth it, having already written the test the work is done and deleting it is deleting a tangible safe guard.

Of additional note is code coverage services (like coveralls.io) that give a good indication of the coverage a test suite provides. By covering every line of code you give a decent metric of the quantity (if not the quality) of testing you perform. In combination with a lot of small tests, these services at least tell you where not to look for a bug when it happens.

Ultimately, if you already have a test written, keep it. Because the space or time saving from deleting it will likely be much less than the technical debt later on if a bug does arise.


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答:
Not all but probably most. Maybe javascript can become fast enough to replace HashCalc but theres no web alternative to VLC (browsers wont support all those codecs). I doubt webbrowsers will let me access any file i want or store a recent file list (without a 'is this ok to access' everytime i click on the recent file) and i dont like the idea of distributing apps that are 99% web browsers (several mb) with my 100kb of code when it comes to cases where code breaks bc browsers are not backward compatible with the html or i need a variant/slight modification of webkit.

-edit- also i like static languages rather then dynamic but i am assuming i can use a good language with LLVM which should be supported by the browser.

OwnerDisplayName: Shnitzel

LastEditorDisplayName: Shnitzel


问:
Any Deterministic Compression Algorithms out There?
The title says it all, basically.

Are there any deterministic compression algorithms - that is, an algorithm which, given identical input, will always produce identical output?

As far as I know, all widely-used compression algoritms are "adaptive" and will vary their output based on whatever heuristic they happen to be using at the moment.

答:
Most compression algorithms are deterministic. Being "adaptive" in no way contradicts being "deterministic": it only means varying behavior based on input, so if the input is the same, so will be the output.

You can easily verify this by compressing the same file several times using an algorithm of your choice (zip, gzip, bzip2, 7z, etc.) and comparing the outputs. For example on linux, you can run this command several times to compress the file /etc/fstab and compare if its checksum is the same each time: gzip < /etc/fstab | md5sum -.


问:
Is it better to call a function that doesn't have an effect at that point, IF it improves code clarity?
I have three views in my program (iOS app). Only one of them is ever active at the same time so I set the visibility off for two of them and switch visibility as the user presses buttons. The views are initialized as visible so I set the visibility off in code before the main view shows.

I can do

```<code>[view1 setAlpha:0.0f];
[view2 setAlpha:0.0f];
</code>```

for two of the views, but now the third one (the one that should be visible at the start of the app) is not addressed. I put a

```<code>[view3 setAlpha:1.0f];
</code>```

after the first two, because I think it keeps it clear that there are in fact three views, not two as one might think when seeing the code. How do other programmers do this? Is it purely preference or are there some conventions?

If the call is very heavy, it's obviously better to not call it when that isn't necessary, but I was wondering about small things like my example.

答:
In this particular case, @Mattieu M. has the right solution.

In the more general case, where there is no similar transform, you have to ask yourself:  Is there any chance a future programmer might mess this up?

The answer is usually yes.  Which means, yes, you should add the call.  Maybe some future version of the framework starts with all views OFF instead of ON.


问:
Pre-calculate values or not on Raspberry Pi
Say that you want to rotate something 360 steps 100 times. You now have a choise to pre-calculate 360 sin and cos values once and then use the stored values 100 times, or you can calculate sin and cos every time.

As far as I understand on modern CPUs you're better off just calculating sin and cos each time because the CPU is many times faster than memory access anyway. However, on a slower CPU like the one used on a RPi (not version 2) would this still hold? or is it slow enough that pre-calculating values is better? A Raspberry Pi has a 700 MHz single core processor.

答:
I ran some tests on my RPi and came to these conclusions:

Looping 100 times over a float LUT with size 360 (ie 100 full rotations with 1 deg resolution or 360*100 sin lookups and 360*100 cos lookups) the LUT is approx. 10-20 times faster than calculating sinf and cosf directly in the loop.

Using a double LUT with same size makes the LUT approx. 40 times faster than calculating sin and cos directly in the loop.

Some things to note:

The LUT is small enough to fit in the 16k L1 cache of the RPi, if one
were to use larger LUTs they might not end up in the L1 cache and the
result might be radically different.

I only used a small placeholder calculation in the loop to prevent the compiler from optimise it away. With a more complicated inner loop the L1 cache might be used up.

Given that this is sin and cos it's actually enough to create for example a sin LUT and use it for the cos values as well (with a 90 deg offset), saving some memory.


答:
Yes, keep the tests, keep them running and keep them passing.

Unit tests are there to protect you (and others) from yourself (and themselves).

Why is keeping the tests a good idea;

Validate the previous requirements' functionality in the face of new requirements and additional functionality

Verify that refactoring exercises are correct

Internal documentation - this is how the code is expected to be used

Regression testing, things change

Do the changes break the old code?

Do the changes require further change requests or updates to current functions or code?

Given that the tests are already written, keep them; it is time and money already spent that will reduce maintenance costs further down the line


问:
Eclipse unit test - one project per file/class?
My new company has never had unit testing, but have finally been persuaded to introduce it.

They have chosen Google test and, for some reason, want to run the unit tests from within Eclipse (where I, personally, would run it from the command line, preferably as some sort of CI and/or check-in process).

With hundreds, possibly thousands, of individual source files, each dealing with one class or a group of related functions, we need to have one test script per source file, but do we really need one Eclipse project, or can we just have as single, humungous project which runs each of the test scripts?

Management insist that the unit tests be runnable from within Eclipse.

答:
Usally Unit-Tests are included in the Project, typically under a different source-folder e.g.

src ==> for your Code
test ==> for your Unit-Tests.

If you use Maven, you will get a structure similar to that.

Those tests can be run per Command line and from Eclipse ot-of-the-box, if the Tests are JUnit-Tests. Eclipse has a nice GUI for that, afaik its included in every Eclipse: Eclise & Junit

Sometimes, people put their Tests in a seperate Project, so for each Eclipse-Project you have you create a _test-Project for the Unit-Tests. This might be an advantage, when you run the Tests seperate from you build, e.g. every 3 hours or so.

It is very uncommon to make one Project for each Class - you'll end easily up with thousands of Test-Projects.

For how to use Google-Test with Eclipse this might help: https://stackoverflow.com/questions/3951808/using-googletest-in-eclipse-how


问:
How do you sync changes to the data in your database?
I am new to a team developing a very large web application. Prior to my start, the team had 0 automation in place and just did everything by hand. This was possible because they were only a team of 2. I am now gradually changing this but obviously I can't just make everyone start from scratch and "do it right".

A problem I'm struggling with are changes to data (not schema) in the database. There are quite a few things that are configured in the database, such as translations, navigations, roles/permissions and mail templates. Luckily these are usually just defined by the team and pushed to staging/production, not both ways.

Our setup is every dev has their own dev environment and their own database. Then there is a staging and production environment. The idea is that a dev can create his new navigation entries, permissions and translations on his dev box then somehow apply these changes to a) the other dev's boxes and b) staging and production.

The obvious way to monitor these changes is to store them as code or SQL files, however this gets quite tricky considering a mail template stores it's data in 3-4 tables and has foreign keys. Another way would be to create export/import functionality, but that would be quite time consuming.

I know this topic has been discussed before but usually the discussion ends with "track your changes in sequential sql or code files". I'm hoping to hear what other teams might be doing and maybe there's even a really great tool for handling this somewhat generically?

答:
SQL scripts are the right way to go:

The information was originally created via a sql statements, most reliable repeat-ability would come from the same script

Import/export can also get tricky if two devs are modifying the same table.

It's hard to code review an export file.

It's hard to debug an export file

We have 5 database environments in our world: dev, staging, alpha, beta, production.  Developers only run their own scripts against dev.  They are responsible for checking these scripts into source control, just like the rest of our source.  We have an automated deployment system which retrieves those scripts from source control and runs them against each successive environment.


问:
Relational Model to NoSQL model
I'm trying to switch my brain in to a NoSQL mode (document oriented database). I created a JSON datastructure that looks a little bit like this

```<code>{
  "listInstances" : [
    {
      "listClassId" : 1,
      "listInstanceName" : "Test",
      "instanceFields" : {
        "header" : [
        ],
        "rows" : [
        ]
    }
  ]
  "listClasses" : {
    "1" : {
      "listClassName" : "Class A",
      "fields" : {
        "header" : [
        ],
        "rows" : [
        ]
    }
  }
}
</code>```

Essentially listClasses are the templates for a listInstance when a list instance is created it is assigned a template and it will take it's own copy of the fields (instanceFields).

Am I going about this the right way, this feels like a relational model (listClassId)?

Edit: As for the operations imagine an app that shows the listInstances in a table of some sort, this table can be added to (this is the point where the list class type is selected) and have instances removed, list entries can be modified to add or delete rows into their fields. The table entries can also be filtered on instance key/values (for example I'm not showing it here but imagine another key "instanceCategory").

答:
The database model is not only defined by the data (your JSON documents for e.g. mongodb, your tables for an SQL database) but also by the operations on the data: the queries, or the updates.

Without knowing what are your operations on your data, we cannot help you. If all your operations are finding some "object" by one particular "key", it would look as a relational database.

Read also NoSQL & documented-oriented database wikipages.

Title: Relational Model to NoSQL model


答:
As you figured out by yourself, SQL is the way to go, but if you put the SQL commands into scripts or embed them in code does actually not make a big difference. What matters is that you make the upgrade process robust. Therefore, I would recommend to consider the following improvement over

track your changes in sequential sql or code files

Instead, track your changes (in sql and/or code files) which work even when they are not executed in the original sequence, or when they are executed twice. Make them idempotent. In one of our systems, we use a flag table for this purpose, where each change to the data of the database is marked by a flag. The pseudocode for upgrading the database then looks like this

```<code> ' part added by developer A during development of feature "Foo"
 IF NOT CheckFlagTableIfUpgradeFooAlreadyApplied() THEN
     IF ApplyUpgradeFoo() = SUCCESS THEN
        MarkUpgradeFooInFlagTable()
        COMMIT
     ELSE
        ROLLBACK
        WriteToLog("UpgradeFooFailed")
     END IF
 END IF

 ' part added by developer B during development of feature "Bar"
 IF NOT CheckFlagTableIfUpgradeBarAlreadyApplied() THEN
     IF ApplyUpgradeBar() = SUCCESS THEN
         MarkUpgradeBarInFlagTable()
         COMMIT
     ELSE
        ROLLBACK
        WriteToLog("UpgradeBarFailed")
     END IF
 END IF
</code>```

That way, you can always take an old database with some changes applied, and others not, and upgrade it to the newest state. For example, the above script will work when the changes "Foo" and "Bar" are missing, when only the change "Foo" was applied, only the change "Bar", or both. It also very easy to add postconditions that way, to deal with cases of interdependent updates. Schema changes can be handled similar, but you often do not even need a flag table for this: just implement a test method like DoesColumnXYZExist() for verifying if a specific column was already added to the schema.

This makes it much easier and more reliable when people work in parallel to integrate they database changes at different times to all their different development databases, and to staging, testing or production databases as well.

See also this former question on Programmers, where a tool named Liquibase was mentioned for implementing this process.

Title: How do you sync changes to the data in your database?

Body:
I am new to a team developing a very large web application. Prior to my start, the team had 0 automation in place and just did everything by hand. This was possible because they were only a team of 2. I am now gradually changing this but obviously I can't just make everyone start from scratch and "do it right".

A problem I'm struggling with are changes to data (not schema) in the database. There are quite a few things that are configured in the database, such as translations, navigations, roles/permissions and mail templates. Luckily these are usually just defined by the team and pushed to staging/production, not both ways.

Our setup is every dev has their own dev environment and their own database. Then there is a staging and production environment. The idea is that a dev can create his new navigation entries, permissions and translations on his dev box then somehow apply these changes to a) the other dev's boxes and b) staging and production.

The obvious way to monitor these changes is to store them as code or SQL files, however this gets quite tricky considering a mail template stores it's data in 3-4 tables and has foreign keys. Another way would be to create export/import functionality, but that would be quite time consuming.

I know this topic has been discussed before but usually the discussion ends with "track your changes in sequential sql or code files". I'm hoping to hear what other teams might be doing and maybe there's even a really great tool for handling this somewhat generically?

Body:
As you figured out by yourself, SQL is the way to go, but if you put the SQL commands into scripts or embed them in code does actually not make a big difference. What matters is that you make the upgrade process robust. Therefore, I would recommend to consider the following improvement over

track your changes in sequential sql or code files

Instead, track your changes (in sql and/or code files) which work even when they are not executed in the original sequence, or when they are executed twice. Make them idempotent. In one of our systems, we use a flag table for this purpose, where each change to the data of the database is marked by a flag. The pseudocode for upgrading the database then looks like this

 ' part added by developer A during development of feature "Foo"
 IF NOT CheckFlagTableIfUpgradeFooAlreadyApplied() THEN
     IF ApplyUpgradeFoo() = SUCCESS THEN
        MarkUpgradeFooInFlagTable()
        COMMIT
     ELSE
        ROLLBACK
        WriteToLog("UpgradeFooFailed")
     END IF
 END IF

 ' part added by developer B during development of feature "Bar"
 IF NOT CheckFlagTableIfUpgradeBarAlreadyApplied() THEN
     IF ApplyUpgradeBar() = SUCCESS THEN
         MarkUpgradeBarInFlagTable()
         COMMIT
     ELSE
        ROLLBACK
        WriteToLog("UpgradeBarFailed")
     END IF
 END IF

That way, you can always take an old database with some changes applied, and others not, and upgrade it to the newest state. For example, the above script will work when the changes "Foo" and "Bar" are missing, when only the change "Foo" was applied, only the change "Bar", or both. It also very easy to add postconditions that way, to deal with cases of interdependent updates. Schema changes can be handled similar, but you often do not even need a flag table for this: just implement a test method like DoesColumnXYZExist() for verifying if a specific column was already added to the schema.

This makes it much easier and more reliable when people work in parallel to integrate they database changes at different times to all their different development databases, and to staging, testing or production databases as well.

See also this former question on Programmers, where a tool named Liquibase was mentioned for implementing this process.


问:
Design patterns for navigation between pages on mobile platforms
I'd like to ask you about the best way of handling navigation between pages/activities on mobile platforms. To be more specific - about handling state in more complex apps, about handling 'Back' actions, etc...

At the beginning it's worth to mention that I'm looking for a solution which will fit to MVVM approach (Windows Phone).

Of course first page of Google gives me some answers but in 99% of examples we have simple cases like (C# mixed with pseudocode):

```<code>public class ExampleViewModel : INavigationViewModel
{
     public void Activate()
     {
           //load somehow saved state if it exists

           if(savedState != null) { //assign previously saved state to current VM }
     }

     public void Deactivate()
     {
           //save view model state and it will be ok
     }
}
</code>```

So it looks pretty clear, right? Interface INavigationViewModel has defined two basic methods which simulate moving forward and back. During changing pages that methods are executed so we may think that everything will work ok.

Now let's take a look at more realistic situation:

```<code>public class ExampleViewModel : INavigationViewModel
{
     public void Activate(Dictionary<key,value> someParams)
     {
           //Activation, but from which case?
           // 1. From previous page? Ok, we have someParams != null.
           // 2. From 'back' button? Not good, someParams == null.
           // 3. From hidden state? Not good...

           // I think you get the point, right?
     }

     public void Deactivate()
     {
           //Deactivation types might be like:
           // 1. Going to another page
           // 2. Quick move forward and backward (yes, different than 1.)
           // 3. Closing app from this moment (what about filled data?)
           // 4. Full page activities (for eg. full screen datepicker)
           // Maybe some other deactivation cases?
     }
}
</code>```

Some devs (like me now) are using static classes - 'DataContainers' to handle page state. Ok that's good, but we have situations when under the same key there are unwanted or different values.

That's not all - with many 'activation cases' we need to write many conditional statements. In more complex apps it's nearly impossible to handle all variations of launching ViewModel.

In programming world we have many design patterns. I can't believe that's so few ideas (or maybe my research was not good enough) for this problem - navigation in mobile apps without writing methods with hundreds of cases.

It would be great to see something like Strategy Pattern with encapsulated cases, based on interfaces with really clean activation methods, etc... is this possible?

答:
Include crucially required state information as url parameters/cookie-as-last-resort (assuming you probably loose the querystring portion of a request in some cases).
Much like you may have a controller/action url portion to your MVC/VM setup, you can include id
 i.e. http://wherever/area/process/stage/essential_param1/2/3

This way you still can continue from where you need to relatively easily, and request any remaining parameters from the user or database.


问:
Is it okay to return the "wrong" HTTP status code in order to show a more user-friendly error page?
Located here, RFC 7231 is all about the HTTP protocol (status codes)

I'm developing an in-house web application for my university's department and I'm at a (probably unimportant) impasse.

I'm reducing users' access to resources based on role (student, faculty, staff) and have it working just fine. However, when a user attempts to access a resource and is denied access, the HTTP specification says that I should use a 403: Forbidden, marking that the user does not have access to the resource, or "hide" the resource by returning a 404: Not Found.

I could do that, but I want to make the site a bit more user-friendly and instead redirect them to their previous page with a flash (NOTE that I did not say 'Adobe Flash'; see comments) message instead of having a 403/4 page with links back to different parts of the site. I think it's a pretty UX-friendly feature.

However, that would involve redirecting via a 303: See Other, which more or less violates the standard.

Obviously it really doesn't matter as this is an in-house project for a lab at my university and nobody here is going to be complaining, but imagine this site were under the Google umbrella.

So, is it bad practice to deviate from the [HTTP] standard like this?

Edit: There seems to be a lot of confusion, so let me give an example:

User with id = 1 attempts to access mydomain.com/projects/2 through their profile (by clicking a link). User 1 is the owner of project 2, so the server accepts the requests and renders the page with the project.

User 1 then types mydomain.com/projects/3 into the URL. User 1 is not the owner of project 3. Therefore, when the request gets to the server, the server denies it.

Now, there are two options:

1.) The server redirects the user to /projects/2 (their previously visited page, which would of course always be a valid one) with a helpful notification at the top such as "Sorry, but you do not have permission to access XXXX" or

2.) The server renders a 403: Forbidden page, or a 404: Not Found page, which would probably have that same text (if it was a 403), and maybe even a JavaScript-enabled "back" link

Personally, the redirect seems way more user friendly to me, and eliminates seeing an unfriendly page like 403: Forbidden and having to click a "back" button. However, doing the redirect goes against the HTTP protocol standard.

答:
You might generate the error page (for 403: Forbidden HTTP error code). That error page might contain links to appropriate (context dependent) pages.

I'm doing a similar thing on http://gcc-melt.org/ using my lev404cgi CGI program (free software GPL3+ licensed). Try opening http://gcc-melt.org/docu or http://gcc-melt.org/foobar; these are 404: Not found error pages, but the user is given a few links to possible replacements or suggestions.

Of course, I suggest to use standard compliant HTML5 content (in particular for a University web page, since at least the CS department would have a lot of Linux systems) and avoid Adobe Flash content (it is a proprietary format; on my Linux systems, I often have to start a non Firefox browser for them -which I rarely do-, so I won't start it for some "error-reporting" content).


答:
Reality Check

I have been in challenging environments where testing is "a waste of time" during budgeting and schedule, and then "a fundamental part of quality assurance" once the customer is dealing with bugs, so my opinion is more fluid than others might be.

You have a budget.  Your job is to get the best product you can on that budget, for whatever definition of "best" you can scrape together (it's not an easy word to define).  End of story.

Testing is a tool in your inventory.  You should use it, because it's a good tool, with a long history of saving millions, or perhaps even billions of dollars.  If given a chance, you should add tests to these simple functions.  It may save your skin some day.

But in the real world, with budget and schedule constraints, it may not happen.  Don't make yourself a slave to procedure.  Test functions are nice, but at some point, your man-hours may be better spent writing developer documentation in words, rather than code, so the next developer doesn't need tests as much.  Or it might be better spent refactoring the code base so you don't have to maintain as difficult of a beast.  Or perhaps that time is better spent talking to your boss about the budget and schedule so that he or she better understands what they're bidding for when the next round of financing comes down the pipe.

Software development is a balance.  Always count the opportunity cost of anything you are doing to ensure there wasn't a better way to spend your time.


问:
Polymorphic template container: shared_ptr vs reference_wrapper
Assuming we have two classes:

```<code>class A
{
    ...
}
class B : public A
{
    ...
}
</code>```

Would it be better to write

```<code>std::deque<shared_ptr<A> > container;
</code>```

or

```<code>std::deque<reference_wrapper<A> > container;
</code>```

to create a container which is able to contain references to both of these classes and why?

In my case, the class containing the container wouldn't care, if a reference somehow became invalid.

However are there any caveats to take into account, when choosing one approach over the other?

答:
Here's my opinion on the matter:

consider whether both variants can actually be used in your case.  reference_wrapper is, by design, not default-constructible. That means you will not be able, for example, to call container.resize() when using the reference wrapper.  A shared_ptr, on the other hand, is default-constructed to an invalid/NULL state.  So, for some use cases, you can't use a reference_wrapper.  To give some examples:

```<code>int i = 42;
std::reference_wrapper<int> iref(i);             // OK
std::reference_wrapper<int> uninitialized_iref;  // Not OK, but OK with shared_ptr

iref = 23;                     // Not OK, but OK on a "normal" reference
int& iref2 = iref; iref2 = 32; // OK
static_cast<int&>(iref) = 23;  // OK
iref.get() = 23;               // OK

std::vector<std::reference_wrapper<int> > irefs; // OK
irefs.resize(10);    // Not OK!
irefs.resize(10, i); // OK
</code>```

The above examples already hint at something else: Usability and readability. Depending on your use case, you have to decide whether you prefer pointer-style notation (shared_ptr) or more-or-less-reference-style notation (reference_wrapper) and whether that makes the code more maintainable.  Personally I value this aspect quite highly.

As pointed out in a comment to your question, the object lifetime also plays a role.  When the container's lifetime is intended to exceed the lifetime of any of the referenced objects, you have to use shared_ptr (or maybe find a different system design).  With references you need to be certain about the respective scopes.  I also suspect that in your specific case, you should actually care about references becoming invalid -- if that can happen, you'd be in trouble, and it would usually be difficult to debug.

Storing shared_ptr elements of course implies that the values you want to refer to are already stored in shared pointers.  You can not create a shared pointer referencing an element created by some other means.  So, if you need to refer to existing, non-shared elements, you can not use shared_ptr and would have to go with reference_wrapper or plain old pointers.

As far as performance goes, I would not expect much of a difference. reference_wrapper usually uses a pointer internally, and the overhead for a shared_ptr is usually negligible.

All in all, I would base my decision around (a) my concrete use case, and (b) usability/maintainability/readability of the code using the container.

Body:
Here's my opinion on the matter:

consider whether both variants can actually be used in your case.  reference_wrapper is, by design, not default-constructible. That means you will not be able, for example, to call container.resize() when using the reference wrapper.  A shared_ptr, on the other hand, is default-constructed to an invalid/NULL state.  So, for some use cases, you can't use a reference_wrapper.  To give some examples:

int i = 42;
std::reference_wrapper<int> iref(i);             // OK
std::reference_wrapper<int> uninitialized_iref;  // Not OK, but OK with shared_ptr

iref = 23;                     // Not OK, but OK on a "normal" reference
int& iref2 = iref; iref2 = 32; // OK
static_cast<int&>(iref) = 23;  // OK
iref.get() = 23;               // OK

std::vector<std::reference_wrapper<int> > irefs; // OK
irefs.resize(10);    // Not OK!
irefs.resize(10, i); // OK

The above examples already hint at something else: Usability and readability. Depending on your use case, you have to decide whether you prefer pointer-style notation (shared_ptr) or more-or-less-reference-style notation (reference_wrapper) and whether that makes the code more maintainable.  Personally I value this aspect quite highly.

As pointed out in a comment to your question, the object lifetime also plays a role.  When the container's lifetime is intended to exceed the lifetime of any of the referenced objects, you have to use shared_ptr (or maybe find a different system design).  With references you need to be certain about the respective scopes.  I also suspect that in your specific case, you should actually care about references becoming invalid -- if that can happen, you'd be in trouble, and it would usually be difficult to debug.

Storing shared_ptr elements of course implies that the values you want to refer to are already stored in shared pointers.  You can not create a shared pointer referencing an element created by some other means.  So, if you need to refer to existing, non-shared elements, you can not use shared_ptr and would have to go with reference_wrapper or plain old pointers.

As far as performance goes, I would not expect much of a difference. reference_wrapper usually uses a pointer internally, and the overhead for a shared_ptr is usually negligible.

All in all, I would base my decision around (a) my concrete use case, and (b) usability/maintainability/readability of the code using the container.