答:
I am a fan of using data attributes:

HTML:

```<code><div class="ajax-widget" data-endpoint="/api/some-endpoint">
    ...
</div>
</code>```

JS:

```<code>// Or whatever your initialisation logic is.
$('.ajax-widget').each(function() {

    // Grab the endpoint and use it for something.
    // e.g. AJAX call, assigning to a property for later etc.
    var endpoint = $(this).data('endpoint');
    ...
});
</code>```

The benefits to this are many.

They are easily parsed with jQuery.

It offers good separation of concerns (allowing you to keep your JS out of your views and in JS files).

You can create flexible, modular widgets/plugins using the same JavaScript that can be pointed to various endpoints without modifying JavaScript.

Avoids having to have funky environment checks in your JS - configure environment-specific URLs server-side and let the client just do its thing with whatever you give it.

You can make use of MVC helpers without littering your JavaScript (and, again, pulling it into your views).

You can easily build HTML prototypes which point to endpoints returning pre-specified results (such as static JSON files) allowing you to develop and test client-side code independently without having to change JS code in production.

Probably many more that I can't think of right now.

This is the standard convention we use and I honestly think it's spot on. The benefits I've listed above are in the context of AJAX calls but they apply for just about any scenario you can name in which you'd need to do something like this (client-side redirects, dynamic hyperlink creation and so on).

Title: URLs in javascript in the browser

Body:
I am a fan of using data attributes:

HTML:

<div class="ajax-widget" data-endpoint="/api/some-endpoint">
    ...
</div>

JS:

// Or whatever your initialisation logic is.
$('.ajax-widget').each(function() {

    // Grab the endpoint and use it for something.
    // e.g. AJAX call, assigning to a property for later etc.
    var endpoint = $(this).data('endpoint');
    ...
});

The benefits to this are many.

They are easily parsed with jQuery.

It offers good separation of concerns (allowing you to keep your JS out of your views and in JS files).

You can create flexible, modular widgets/plugins using the same JavaScript that can be pointed to various endpoints without modifying JavaScript.

Avoids having to have funky environment checks in your JS - configure environment-specific URLs server-side and let the client just do its thing with whatever you give it.

You can make use of MVC helpers without littering your JavaScript (and, again, pulling it into your views).

You can easily build HTML prototypes which point to endpoints returning pre-specified results (such as static JSON files) allowing you to develop and test client-side code independently without having to change JS code in production.

Probably many more that I can't think of right now.

This is the standard convention we use and I honestly think it's spot on. The benefits I've listed above are in the context of AJAX calls but they apply for just about any scenario you can name in which you'd need to do something like this (client-side redirects, dynamic hyperlink creation and so on).


问:
Bad Practice using Auto Generated Classes for Data Access
I've seen this before but haven't found concrete reasons.

When you add Entities to your EF model, EF auto generates classes for these entities.

In terms of DataAccess, why is it preferred to not use these Auto Generated Classes, and instead use your own Data Models for Data Access.

Ex.

```<code> EFAutoGeneratedClass = //query = BAD

 SeparateModelClass = //query = Good
</code>```

答:
My problem with auto generated code is its lack of maintainability. If there is a small change in the database then you have to refresh the entire generated code section and make sure that only the intended change have gone in. And if you are not using any code repository which does not tell you the changes in the code then it is much more difficult to find the code changes. It also means that the entire component should be tested again fully for all scenarios.

Also, I have noticed that developers working on the legacy generated code sometimes make manual changes in the generated code instead of generating the auto generated code section again. After a period of time it becomes almost impossible to replace the auto generated code.

Code First of Entity Framework seems to me a much better option. The code change is localized to a certain file so less chances of breaking any existing functionality.

So in nutshell, if you have a very disciplined team who does not touch the generated sections and also diligently covers all the test scenarios using Unit Tests...then by all means you can go for generated code approach but try to have Code First approach as much as possible.

ContentLicense: CC BY-SA 3.0


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
I always think of abstraction in programming as hiding details and providing a simplified interface.  It is the main reason programmers can break down monumental tasks into manageable pieces.  With abstraction, you can create the solution to a part of the problem, including all of the gritty details, and then provide a simple interface to use the solution.  Then you can in effect "forget" about the details.  This is important because there is no way a person can keep all of the details of a super complex system in their minds at once.  This is not to say that the details underneath the abstraction will never have to be revisited, but for the time being, only the interface must be remembered.

In programming, this simplified interface can be anything from a variable(abstracts away a group of bits and provides a simpler mathematical interface) to a function(abstracts away any amount of processing into a single line call) to a class and beyond.

In the end, programmers' main job is to usually abstract away all the computational details and provide a simple interface like a GUI that someone who doesn't know one thing about how computers work can make use of.

Some of the advantages of abstraction are:

Allows a big problem to be broken up into manageable pieces.  When adding a person's records to a database, you don't want to have to be messing with inserting and balancing index trees on the database.  This work may have been done at some point, but now has been abstracted away and you no longer have to worry about it.

Allows multiple people to work well together on a project.  I don't want to have to know all the ins-and-outs of my colleague's code.  I just want to know how to use it, what it does, and how to fit it together with my work (the interface).

Allows people who don't have the required knowledge to perform a complex task to do so.  My mom can update her facebook and people she knows all over the country can see it.  Without the abstraction of an insanely complex system to a simple web interface, there is no way she would be able to begin to do something similar (nor would I for that matter).

Abstraction can, however, have the reverse effect of making things less manageable if it is overused.  By breaking up a problem into too many small pieces, the number of interfaces you have to remember increases and it gets harder to understand what is really going on.  Like most things, a balance must be found.

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


问:
Sharing development test cases (unit and development integration) with the QA (test) team?
The testing team (the so-called QA team in some organizations) insists that the development team should share their (the development team's) test cases with them. Their arguments are that the development test cases are the starting point for the QA testing.

As a development team member, I don’t understand the request. Per me, the tester should test the solution based on the requirements. I don’t know if the test team should be shared with the detailed design (low-level design) document. However, we are sharing them the detailed design.

I have read some posts here that say the QA team should share their test cases with the development team for a better solution and for better throughput. But, nothing sort of the development team sharing their test cases with the QA test team.

It looks like my QA team is very happy if I share my development unit and integration test cases and the test results.

答:
My first reaction of this question is “it depends”.

It depends on what you mean by “development team test cases”.

If you have only unit tests (white-box test); QA Team (integration and system test) could not leverage your test-cases. Unit test are only there to verify your unit, which solely don’t satisfy a requirement (mostly). White-box testing shouldn’t be the way for integration or system tests.

If you have behavioral tests; QA Team can use them to derive some integration scenarios.

If you are using TDD; as per definition, tests are executable documents of the requirements, architecture and design of the application. QA team would definitely need these test cases.

Some test design methods like gray-box testing requires detailed design information to be able to isolate or to mock test subjects like component or subsystem (integration test). Therefore sharing the detailed design with QA team is also necessary.

System Test guys never bother with detailed design. They focus on user scenarios. Therefore development tests (white-box) won’t be any use for them.

My humble recommendation for your case is an evaluation of agile approaches like having tester(s) (QA) within the dev-team and design tests (feature, integration, system) together upfront.


问:
Why are self-hosting compilers considered a rite of passage for new languages?
I've heard in a number of places now that people expect languages to use, or at least have, a self-hosting compiler in order to deserve respect.

I'm curious as to why this is. A compiler seems like a very significant piece of software to write, and I imagine not all languages are well-suited to creating them. Wouldn't it make more sense to spend the effort working in something that will give better results?

答:
If you want to have a compiler for language X be self-hosting, your first have to implement it in some other language, say Y, such that it takes input for language X and spits out assembly code, or some intermediate code, or even object code for the machine the compiler is running on.  You want to choose language Y to be as similar to language X as possible, since at some point you will translating code written in Y to X.

But you don't want to write any more of the compiler in language Y than necessary, so to start with, you implement only a subset of the language -- eliminating redundant constructs.  In the case of a 'C' type language, while but no for or do while.  if but no case or tertiary op.  No structures or unions or enumerations.  Etc.  What you have left is just enough of the language to write a parser and a rudimentary code generator for language X.  Then check the output.  Again.

Once you have this working, you can rewrite the compiler source that was written in language Y into language X, and compile the language X source using the compiler written in language Y.  The output will be a new compiler written in the new language X that compiles language X, i.e. it is now self-hosting.  However it is not complete since you only implemented a subset of the language in language Y.

So now you add in the missing features, testing each one (or group of features) that they generate correct code.  i.e. once the feature is implemented in the compiler, you can write test programs using the new feature(s), compile and test them, but you shouldn't use them in the compiler source yet.  Once the new feature(s) are verified, you can then use these new features in the compiler source itself -- perhaps replacing some of the original code written in the language subset -- recompile the compiler source using the version with the new features.

You now have a mechanism for adding new features to the language -- and, once the code generation for the features has been verified correct, they can be used in the next generation of the compiler itself.

Back 60 years or so ago when computers first arrived on the scene (and later again when microprocessors first arrived), there were no other languages Y suitable for implementing the initial compiler.  So the first compilers had to be written in assembly code, and then when enough of the compiler was running, the assembly code would be replaced by the version written in new language.  No assembler either?  The the whole processor dropped down another level, with the assembler initially being written in machine code.


问:
Objects in smalltalk and c++
I have a question based on SmallTalk and C++. In one of the programming languages books, there is a question like:

"Does an object in Smalltalk require its own private stack? What about in C++?"

Could you please explain those questions above if you know the answers?

Thanks.

答:
In no language does each object require its own stack. Not in Smalltalk. Not in C++. Not in any other language in common use.

The only notable exception to this would be thread objects, or objects that otherwise embody concurrency context. Each thread of execution requires its own call stack. That is true independent of the language used--Smalltalk, C++, Python, or whathaveyou.

NB Some languages or environments attempt to achieve concurrency (the effect of "multi-threading") without per-thread stacks in order to reduce overhead. Such green threads or "greenlets" are quite useful and increasingly common. Concurrency in go, for example, is centered around this idea. But even if green threads are called "threads," they behave closer to coroutines than true threads. Those that are "stackless" are simulating multi-threaded concurrency, not implementing it fully.

Title: Objects in smalltalk and c++


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
You're dealing with multiple teams and multiple projects. Likely decades of work went into the codebase.

The short answer is that your teams and projects have varying needs and varying dependencies.

The monolithic repository approach reduces commits to "Everything is stable in this configuration!!!" (i.e. unrealistic, huge commits sourced from many teams). That, or many intermediate points of incompatibilities for many projects. Either way, there's a lot of wasted energy invested in supporting configurations which were simply never meant to be.

Your repositories should be structured independently instead, and should have multiple repositories which represent their dependencies. The dependencies should be configured, updated, and tested by the project maintainers at appropriate points in development.

ProjectA saw its last major release 3 years ago. It is in maintenance mode and has "older" system requirements. It should refer to an appropriate set of dependencies. It has 20 dependencies.

ProjectB was just released. It has more modern System Requirements, and was developed and tested by another team. It has 15 dependent libraries (=repos), 10 of which are shared with ProjectA. These projects generally refer to different commits of their dependent libraries. Dependencies are updated at appropriate points in development.

ProjectC is yet to be released. It's very similar to ProjectB, but includes significant changes and improvements to its dependencies. Developers of ProjectB are only interested in taking the stable releases of the dependencies they share with ProjectC. ProjectB's team makes some commits to the shared dependencies, although they are mostly bugfixes and optimizations at this time. A monolithic repository would either hold development of ProjectC back in order to maintain support for ProjectA, or ProjectC's changes would break A and B, or developers would just end up not sharing/reusing code.

With multiple (distributed) repositories, each team can work independently and minimize impacting the other projects while reusing and constantly improving the codebases. This also keeps teams from shifting focus/speed when changes come in from other teams. The centralized monolithic repository makes each team dependent on every team's move, and that would have to be synchronized.


问:
Does a create() method exist as part of a pattern?
Is there something special(i.e. a design pattern being related) to a method named create()?

Background

The case is, I often make some instances of objects (of the same class/prototype). These objects do not always already objects reflect a state in which they are complete yet. Potentially some initialization needs yet to be done to make them more completly initialized (which cannot be done in the constructor function/method) since for some reasons the information to do so might existing already. An alternative making of the objects once this information is available is made difficult since the objects already made are made available via references to other objects (even though some functionality is not yet possible because of the some missing initalization).

In order to have a way to complete the initialization of the object I would like to call a method .create([...]) on the objects which should be a way for a second step completion of some of the objects initialization.

My interest is if related to this background is if this is a legitimate/reasonable course of action (i.e. to have some objects that may have different states of readyness; which are made into a "complete" state via a method - I thought to name that .create([...]))?

Specifically I would of course like to know if there are for instance already patterns with standard method names for the described task (two-step initialization of objects) and also if the method name .create[...] chosen in worst case conflicts with some existing pattern and would confuse readers of my code.

答:
From what I have both read and experienced, it is not a good practice to have more than one single step in initialization of an object. This is not good because

You need to babysit all such objects, so that the required initialization steps are completed before the objects are used

You would have to expect anyone using your code to also properly babysit their objects.

You can easily see that step 1 is quite error-prone, as one might forget some of the steps, or have a hard time to track whether a certain step completed. And, of course, you should not allow the users of your code to break it easily, meaning you should spare them step 2.

However, there are known exceptions to the above preachings which have made it to the development world and became widespread and proven practices. The most important thing is to not allow programmatically for your objects to be used before being properly initialized. This would imply that you have certain encapsulation mechanisms over the initialization lifecycle. Here are possible approaches I can think of, and the respective use cases in real life:

Factory classes

A factory class, (or simply a factory), is a separate class that exposes a single method (create if you wish), that is used to instantiate your working object. It must return a fully initialized and ready-to-use instance of your class, therefore all the initialization steps happen inside of that method. For instance this code (used C# as language):

```<code>public class FooFactory
{
    public Foo Create()
    {
        Foo foo = new Foo();
        foo.configure(...);
        foo.init(...);
        foo.complete(...);
        return foo;
    }
}
</code>```

This is considered a design pattern, see wikipedia article. In most cases the creation method is called Create or CreateFoo but you can choose whatever suits you.

Dependency Injection (DI for short)

This requires you to get familiar with a dependency injection framework and employ it in your project. The DI framework will take care for passing completely initialized instances of your objects and some implementations support post-constructor initialization steps that are execute before the object is ready for use. This acts in a similar way to the above factory pattern, but the advantages of dependency injection. An example is the popular Spring framework (primarily addressing Java development, has also a .NET port), which allows you to specify both init and destroy methods on your class. The init method can be any method of the class you select, so you can easily fit your intention with the create method to work with that.

```<code><beans ...>
  <bean class="com.mycompany.Foo" init-method="create">
    ...
  </bean>
</beans>
</code>```

See this short article for some reference.

An alternative to the above approach is to rather specify a static class and method that would initialize your Foo class. For the below example, the createFoo is a static method of the FooFactory class and returns an instance of Foo.

```<code><beans ...>
  <bean class="com.mycompany.FooFactory"
        factory-method="com.mycompany.FooFactory.createFoo" />
</beans>
</code>```

The above list is not exhausting, there are other solutions that might seem appropriate in certain scenarios.

Body:
From what I have both read and experienced, it is not a good practice to have more than one single step in initialization of an object. This is not good because

You need to babysit all such objects, so that the required initialization steps are completed before the objects are used

You would have to expect anyone using your code to also properly babysit their objects.

You can easily see that step 1 is quite error-prone, as one might forget some of the steps, or have a hard time to track whether a certain step completed. And, of course, you should not allow the users of your code to break it easily, meaning you should spare them step 2.

However, there are known exceptions to the above preachings which have made it to the development world and became widespread and proven practices. The most important thing is to not allow programmatically for your objects to be used before being properly initialized. This would imply that you have certain encapsulation mechanisms over the initialization lifecycle. Here are possible approaches I can think of, and the respective use cases in real life:

Factory classes

A factory class, (or simply a factory), is a separate class that exposes a single method (create if you wish), that is used to instantiate your working object. It must return a fully initialized and ready-to-use instance of your class, therefore all the initialization steps happen inside of that method. For instance this code (used C# as language):

public class FooFactory
{
    public Foo Create()
    {
        Foo foo = new Foo();
        foo.configure(...);
        foo.init(...);
        foo.complete(...);
        return foo;
    }
}

This is considered a design pattern, see wikipedia article. In most cases the creation method is called Create or CreateFoo but you can choose whatever suits you.

Dependency Injection (DI for short)

This requires you to get familiar with a dependency injection framework and employ it in your project. The DI framework will take care for passing completely initialized instances of your objects and some implementations support post-constructor initialization steps that are execute before the object is ready for use. This acts in a similar way to the above factory pattern, but the advantages of dependency injection. An example is the popular Spring framework (primarily addressing Java development, has also a .NET port), which allows you to specify both init and destroy methods on your class. The init method can be any method of the class you select, so you can easily fit your intention with the create method to work with that.

<beans ...>
  <bean class="com.mycompany.Foo" init-method="create">
    ...
  </bean>
</beans>

See this short article for some reference.

An alternative to the above approach is to rather specify a static class and method that would initialize your Foo class. For the below example, the createFoo is a static method of the FooFactory class and returns an instance of Foo.

<beans ...>
  <bean class="com.mycompany.FooFactory"
        factory-method="com.mycompany.FooFactory.createFoo" />
</beans>

The above list is not exhausting, there are other solutions that might seem appropriate in certain scenarios.


问:
Organise C++ classes around SQL database
My question is about how best to organize C++ classes around a database
model, and I understand this may appear very elementary.

The software I propose to create will do the following. It is intended for
small FMCG manufacturers and will use Qt.

The software will record non-conformance's, product complaints,
corrective actions and serve as an electronic record keeping

There will be quite a bit of 'business logic', as the standout
feature is intended to be comprehensive reporting, searching and
analysis, as well as a flexible approach to entering data to smooth
workflows (ie, a break away from the "one screen per process stage"
paradigm)

The persistent store is an SQL database, with a table(s) for each
type of record (some records will be broken into separate tables for
investigations/solutions. This means that most work will be done on a
single row).

Each customer who uses this software will require amendments,
additional columns/fields or changes in column names and maybe
business logic. Each customer may require updates which change the
database structure. The idea is that anything that can be customized, any
client specific requirements will live within these classes.

There will be reporting, mainly involving pulling records matching
particular categories, word searches, etc.

I have the database schema done and laid out, and the logic of how tables
relate is clear.  I have used this very schema in another framework, but a web based app doesn't seem to offer the level of power to the user with regards to the GUI, which is essential to differentiate this product from the others.

My question is how to design classes around the database. It is important to
get this right, so that the architecture of the software doesn't have to be
redesigned later on. The classes will not be responsible for the persistent
store, only for acting as an intermediary between the layer responsible for
the persistent store and the controllers/views.

The most logical approach appears to be to have a class for non-conformances/complaints etc, which solely store the instance (ie, one object per non-conformance record), validate data and class specific business logic (ie, computations).  One class per table seems logical in this case.  What I'm struggling with, is whether it is standard practice to simply have data members for each column, define getters and setters, or whether I should create a class which isn't hard-coded to map to a table, but which populates a map based on the database schema or external file which defines the database and column properties. The former means that the coding for the class needs to be changed when columns are modified, the latter potentially not.  Keep in mind, for the majority of the time, each user will be working with one record at at time.

In short, I can see example of how to do SQL queries, but I've struggled to
find anything which shows me what the class should look like (or if this entire approach is wrong) and I'd like to compare what I'm doing, with what the industry would define as good practice (I'm not a programmer by trade).

Thank you,

答:
The common mistake many people make with database mapping is that they focus on the schema and develop a tightly-coupled representation of the tables in business logic classes. This is not the best way at all - obviously it makes the business logic layer so tightly coupled to the DB that they quickly realise its a mistake and end up adding another layer to try to decouple business logic from DB, calling it a DAO or ORM or similar.

What you should do is look at your DB as a layer in itself, one that provides an API where data requests are made. I find its easiest to conceptualise this by writing all your SQL as stored procedures and restricting all access to the underlying tables. (this approach also has the benefit of increasing security)

Once you do this, you start to look at the data as a resource to be consumed, the business logic will have classes written that map to the stored procedures and they work together - logic in the business logic classes with data that is operated on sourced from your "data API". It also means you can change the schema without any change to the business logic layer at all (though, obviously if you change the stored proc API that is used, you'll have to change the callers, but you can add new sprocs where needed without any impact on existing code).

Another benefit is that your DB and your business logic are then independent and can be worked on separately. using your DB API would be not much different than using a 3rd party API provided via a web service or other data source.


问:
Advanced subversion techniques, what am I missing?
I started using SVN about 9 months ago and it's been a game changer to say the least.  Although, I feel I'm still a bit lost.  I feel like there is a lot more I need to take advantage of to really step up my application development.

For example

I would like to be able to quarantine any volatile/major changes into some kind of 'sub-repository' or something.  I'm finding that major changes are impeding minor bug fixes that are quite urgent.  How can I push one simple update without pushing incomplete or broken code?

答:
To address your example, you have three possibilities to do that:

You can commit single files. If you use an IDE for accessing the Repository, it has most likely a view, to select or unselect single files before committing. On the command-line you type svn commit file1 path1/file2 path2 to commit file1, path1/file2 and every change under path2.

You can make different working copies. You work on your large feature in your standard working copy and get the information about the urgent bug. You can checkout your repository to a different directory and fix the bug in this second working copy. You may even check out only a subdirectory with the component where the bug occurs. After bugfix you can commit in your second working copy without committing your work on the big feature. EDIT: That way is also described in the answer of Anna Lear.

You create a branch for the work on your feature. For that you use the copy command. If you use the standard-layout for your repository (directories with the projectname and subdirectories with the names trunk, tags and branches, trunk containing the project) you can use the svn-copy-command like follows to create the branch: svn copy svn://hostname/projectname/trunk svn://hostname/branches/branch-for-feature-X. Now you can switch your working copy to the new location: svn switch svn switch svn://hostname/projectname/branches/branch-for-feature-X. If you switch in bugfixing mode you commit your actual changes, switch your working copy back to trunk, fix the bug and commit, and switch the working copy back to your feature-branch. If you are ready with developing the feature you can merge it back to the trunk.

For the simple case described you will usually use #1 (I use most often), sometimes #2. Working with branches (case #3) is more complicated (read more), but allows for more tricks. But branches matching your description of a subrepository.

Besides from your example I cannot say much. There are many things about Subversion, but I don't know what you already use and what you need for your project. For learning more about SVN the SVN-Book is a great resource: http://svnbook.red-bean.com/


问:
How to deal with product owner who refuses to follow UI design rules
We develop Android application. We base on old version of similar application developed in our company. This old application was designed by some noobs which didn't follow UI Android design rules.

Now our product owner says: do stuff the same way as old application.

(Small example: user can add items to a list; in Android you have + button on Action Bar for that; but we have "Add item" as last item on list.)

My eyes hurts when I look on that design and furthermore implementing it needs quite a lot of effort to bow good tools to generate bad design.

答:
Users do not like change. Even when the change is objectively superior from an UX perspective, the human resistance to change habits will result in them finding it subjectively worse.

So when you already have a userbase you are developing the new application for, it is not a bad idea at all to follow the UI conventions they are used to instead of following UI convention which are more common in general but less common to your target audience.


问:
Proper MVC design and helper classes
I've been reading into Model-View-Controller and was wondering where something like a XyzClient class would fit into this design. Splitting up MVC is easy when all you have are some views to display, some code to handle user interactions and some (maybe persistence driven) database entities.

But where does something like a PaypalClient or a DateFormatter class fit into? When talking of model I think of some database entity like Student or Course but not of some helper like PaypalClient. Is this a model or a controller? And where does something like DateFormatter (a helper for formatting dates) fit? Or should I prevent such classes when designing MVC (without them I would get massive controller code)?

答:
In larger applications, you will benefit from further modularisation beyond MVC. The model can be broken down into:

Domain objects - like Student or Course that you mention

Data access objects (DAO) - code to load/save domain objects

Service layer - business logic that operates on domain objects

People often forget about the DAO layer because if you're using an ORM, it does all that internally. However, your PaypalClient is an example of an explicit DAO. If you want to do a nice job, make sure you separate the Paypal domain objects from the data access objects.

DateFormatter should be part of the view. Are you using templates for the view? Most template systems let you define custom filters, which convert an object to a string. There is also the MVVM pattern, but that's more important when you're doing complex processing for the view; for simple date formatting that is overkill.

Title: Proper MVC design and helper classes


问:
Java Web Application in Cluster with Shared Database. How to Negotiate an Instance to do Updates? How to Notify Instances of Updates?
I have a Java web application, running in a cluster of Tomcat application servers and a shared SQL/JDBC database. Data from the database is cached in memory in each instance of the web app.

My web application needs to update the database periodically with weather report data from a source outside of my web application (i.e. a background thread periodically collects and writes a whole bunch of data rows into a table in the database using SQL). Only one instance of my web application in the cluster should do this and then make the other instances aware that the data in the database has changed so that they can flush their caches and start using the updated data from the database. The propagation of the update to the database doesn't need to be real time.

What is the best practice to achieve this? How do I negotiate, which node will be the one to perform the updates? Which JEE technologies could I use? I want to avoid simply polling for changes in the database.

答:
Using a messaging broker seems like the best tool to inform other applications that they should update rather than polling (which is fine really too).

http://www.rabbitmq.com/

Locking the database table for writing is what you want to prevent race conditions.


问:
How do you go about training a replacement?
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?

答:
Depending on the complexity of what you are doing training someone after you give notice can be a lost cause, and even without complexity there are an increasing number of places that just walk you out as soon as you give notice (make sure you have what is yours before giving notice), so it is often better to train your replacement(s) before you give notice.  A made-up upcoming vacation or surgery is a good excuse if you need it, but assuming you are working in a team you should be able to work that sort of stuff in a bit as you go and pass it off as keeping them in the loop.

If you have already pulled the trigger and have a final date then making them aware of where to look for various things is probably the #1 thing that will help them get working.  When you are showing them the projects and what does what you need to make certain they have some idea of the workflow through the systems and where in the larger projects the important bits are.  You wont have time to give them much detail, but you can probably get them to a point that they know what code to pull up when they need to start sorting through a problem.


问:
How to communicate software design efficiently between developers?
Recently I've come to understand that a serious problem at my workplace is the lack of communication between developers. It's odd, because we're a totally open sort of organization. Everyone can go to everyone and ask whatever they need and communication is hardly regulated at all. And yet it doesn't happen by itself...

The kind of lack that I feel most keenly myself is between me (the architect of the system, more or less) and the rest of the developers (which usually work on a piece of required functionality, not the framework). Whenever I create some component or a naming convention or whatever... there's no way I can make it known to all the people who might need to know this. At most I tell it in person to the fellow who asked me for it, but that's about it.

As a result, wheels get reinvented, there are hardly any conventions in the code (mostly evolved from copy-pasting), occasional cargo-cult coding, etc. I try to clean it up whenever I get the opportunity, but with workload being as large as it is, there are rarely such chances. :(

I'm not really sure how to solve this. I could try and document all the stuff that has been created (probably would take at least a week - difficult to budget that much time) in our internal wiki, but who ever reads such places regularly for news? And how would you find if something that you need has already been implemented somewhere?

What do other people do to avoid this pitfall? What methods have shown themselves as efficient?

答:
This is where DevOps comes into play. It actually tears down silos between Developers and IT Infrastructure people. So, every one knows what's happening in a project. No one is left behind. </p>

<p>For you solution, try to implement DevOps culture in your organization. </p>

Body:
This is where DevOps comes into play. It actually tears down silos between Developers and IT Infrastructure people. So, every one knows what's happening in a project. No one is left behind.

For you solution, try to implement DevOps culture in your organization.


答:
There is no simple answer.

Big pictures put on walls can help. something like the 4C diagrams  (Context, Container, Component, Class) http://static.codingthearchitecture.com/c4.pdf (though class is probably too much detail)

These can help orientate people in the code, and understand what exists.

Code reviews can help spread good practices, but doing them well is an art. The reviewee should not feel put upon, and there should (mostly) not be a single gatekeeper to the repository (because of the hit-by-a-bus problem if no other)

Other than that, standups and card boards are methods for knowledge share within the team, and a good engaged team that wants to better itself is pretty key to the whole endeavour!

Title: How to communicate software design efficiently between developers?

Body:
Recently I've come to understand that a serious problem at my workplace is the lack of communication between developers. It's odd, because we're a totally open sort of organization. Everyone can go to everyone and ask whatever they need and communication is hardly regulated at all. And yet it doesn't happen by itself...

The kind of lack that I feel most keenly myself is between me (the architect of the system, more or less) and the rest of the developers (which usually work on a piece of required functionality, not the framework). Whenever I create some component or a naming convention or whatever... there's no way I can make it known to all the people who might need to know this. At most I tell it in person to the fellow who asked me for it, but that's about it.

As a result, wheels get reinvented, there are hardly any conventions in the code (mostly evolved from copy-pasting), occasional cargo-cult coding, etc. I try to clean it up whenever I get the opportunity, but with workload being as large as it is, there are rarely such chances. :(

I'm not really sure how to solve this. I could try and document all the stuff that has been created (probably would take at least a week - difficult to budget that much time) in our internal wiki, but who ever reads such places regularly for news? And how would you find if something that you need has already been implemented somewhere?

What do other people do to avoid this pitfall? What methods have shown themselves as efficient?


答:
The simplest answer is code reviews (and by code reviews, I really mean "everything related to code changes including the code itself). Obviously this means you'll have to have documentation.

I know places where people are hacking away all over the place, last place my mate worked at every time he came to fix a bug he'd grab the latest code and .. it'd have changed. One team would put changes in this direction, and another team would put changes in a different direction. Sometimes the teams changed direction all by themselves and you ended up with pure chaos where nothing got done to the product, but there was constant and intense code changes.

This is where you need some form of non-developer type change control. If you implement a system where changes are made in a controlled way, and by that I mean anyone can change something, its just that they need some reason to do it and some form of authorisation that its a good thing to progress.

So you can mandate that no change gets applied unless its in response to a change ticket. (anyone can create a ticket describing a problem that needs changing, of course) but these tickets then get assigned to a person or team by someone in charge of product direction - a business analyst or technical design authority or even a team get-together. What's important is that the change gets done in a non-individual way.

Once that is taken care of, someone will go and make changes and then you get them reviewed. This means someone else sees the code but also the ticket changes and documentation. So if you want to change your DB access system, fine... but you need to describe what it is, why it was changed, and how it works now. Without such documentation the change fails its review. Afterwards you can implement internal 'training' such as brown bags or code dojos to ensure the rest of the team gets informed.

Some people will resist this, but they tend to be the ones who churn code constantly, "cutting code" rather than "working on the product". This is an important distinction to make, as developers we can all get caught up in the concept that the code is what's important - its not. The product you're building is what's important and that is much more than just code.

The documentation doesn't have to be extensive, just enough to tell someone else what you've done or how it works. It can be a wiki or even just notes on the tickets - as tickets get old, they'll fade from view and the documentation with them, but this is ok as it means only relevant, current docs gets kept. Alternatively you can have a wiki of components, architecture and usage and that gets kept up to date as part of each code change. Or (my preference) is to store all your technical documentation alongside the code as text documents in a markup format that is built into html by the build server and presented on a web server - so anyone can see the current documentation which is easily updated when code is updated.

A last resort is to get an architecture team who has the responsibility to document the system, but they will also have the power to prevent any changes being made unless the documentation is updated first - many looser teams may not like this more restrictive approach, but  if they cannot make it work using my suggestions then this is the system that would then have to be implemented.


问:
Should simple tasks be divided into separate functions?
If I have to write a simple program (25-35 lines), should I divide it even further, in functions which have a few lines and get executed max. 2 times, or to put it all im one?

e.g. if I need to add and substract 2 angles, should I do everything in one function or write one which converts everything back (and forth) and one which does the actual adding/substracting, leaving main with only I/O (extra: should an angle be defined as a structure or to stick to ints, assuming it isn't used anywhere else)?

My reasoning is that the code is clearer and that I find it easier to write as well, but apparently some people find it unnecessarily long and too complicated. I'm looking for "the right way", preferably examples or experiences from job interviews. Obviously large real-world applications need to be modular, but what about script-like or programs that focus solely on one algorithm?

答:
There is not a "right way", you have to choose when "promote" a fragment of code in a method.

Usually it make sense create a new method:

when your main method is too long, bloated or complex (code readability/maintainability)

when that fragment is used two times or more (no code duplication)

when that frament could be used from two methods or more (code reusability)

when you need to use local variables (that are nearly useless in the main method)


问:
How do big companies maintain their products' source code without it falling into wrong hands?
I am developing a web application by using ASP.NET. I would like to hire some developers to speed up my process but I am afraid what If my members take my code and go away? I am just wondering how big companies maintain their product code without falling into wrong hands. For eg: As I said you earlier I am hiring some staff to my speed up my process but you know every man is not same. Some people may work hardly and some may get the whole code and leave.

So my question is how big companies like Microsoft, Facebook, Yahoo keep their code protected?

Facebook currently have nearly 8,348 members (September 2014). If I say each and every person have the full Facebook code am I right or wrong?

So what are the best practices should I follow if I hire staff members to speed up the process?

答:
You're overestimating the importance of source code, and underestimating the importance of everything else in the value chain of selling software.

Sure, a contractor might steal your source code. But what then? Will they be able to create a release, maintain the code further, contact your customers and sell them a knock-off for a lower price? Almost certainly not. Particularly for extremely large companies like Microsoft, making money from software involves a hell of a lot more then compiling the classes and shipping them to people for money. Nobody could possibly steal the Windows source code and proceed to put Microsoft out of business; the legal, practical and logistical hurdles are just way too high to pull that off.

That leaves the fear that by reading the source, competitors will learn the clever tricks you used and gain an advantage. This, too, is almost always grossly overrated; if your ideas are any good, you will have to ram them down people's throats! Software succeeds big not because it uses clever tricks, but because it fulfills a need accurately. Successful software shops do good market research, gather good requirements, have a solid production and testing process in place and generally do things in the most predictable, easy-to-plan way.

To be sure, sometimes there is a market advantage to be gained from having more brilliant engineers than the competition. Read Paul Graham's description of Viaweb one day - the competition didn't even know they were using Common Lisp! But are you really a Paul Graham? Probably not.

(And Microsoft does in fact make windows source code available to many partner universities - under non-disclosure agreements, to be sure, but still, exactly to the people that might use the ideas gleaned from it to compete with Microsoft! But this never happens, because possessing someone's source code doesn't magically equate to usurping their market position.)


问:
Something like "tracking" for local branches in git?
I often have a workflow where I develop some feature in a Git branch, switch to another feature-branch, etc. During development, the original develop branch and the feature branches diverge.

Now when switching branches I am all of the sudden developing on an older version of my project (which is to be expected, of course).

I do wonder however whether something like a "tracking" behaviour can be configured with Git, which would mean that specially-marked feature branches would be automatically rebased on another branch (like develop or master). This would simplify a lot, especially rebuilds.

答:
You can do

```<code>git checkout your_branch
git fetch  # get the latest
git rebase master
</code>```

Rebase will replay your changes on top of the latest master.
You will need to resolve any conflicts.  Conflicts occur when the same line(s) in the same file are edited by both the latest master and the feature branch.

Body:
You can do

git checkout your_branch
git fetch  # get the latest
git rebase master

Rebase will replay your changes on top of the latest master.
You will need to resolve any conflicts.  Conflicts occur when the same line(s) in the same file are edited by both the latest master and the feature branch.


答:
There are (at least) two issues hidden in this common problem. The first is having a process that ensures that the appropriate communications are taking place, and the second is ensuring that developers actually follow the process - who are often under stress to deliver, and excited about writing code, driven by ego (often in a good way) etc.

The latter, I think, is often easier to achieve in practice that the former: separate the development of deployment (final integration) tests from the people responsible for coding, and do not accept any code into master branch until it passes all tests. Then, regardless of how much or little developers listen to, or follow, the communication process, any changes they make will have no impact on deployed code if it breaks the existing tests. If the tests are a true expression of all requirements (functional and non-functional) - including testing that new functionality isn't added without test confirmation - then this process enforces communication because otherwise a developer's code never goes anywhere! Your minimum job is then to communicate any new requirements to the test writers and ensure that they are implemented first.

The former - i.e. the actual communication  process can then develop over time. Initially the use of the quality gate of full integration testing talked about above before commits to master are allowed will force people to come to you to ask about functionality and requirements etc. or nobody's code will ever get deployed and devs are motivated by deployment. You could then start to work with appropriate mechanisms for communication e.g. scrum meetings, or collaboration tools like Trello, or email lists, or code reviews, or daily requirement user story discussion meetings or whatever works for your structure of teams.

Put the independent deployment quality gate in place first and the rest will, eventually, follow.


答:
We have a cluster-environment too. We use Hazelcast for such jobs. With Hazelcast you could embed the codeblock for updating within a "Hazelcast-Lock-Section". It is not my favourite solution, but this is how it is done in our application (and maybe suits hazelcast your needs).

I opt for a smaller and easier solution:
I would write a small (buzzword-alarm: micro-) service using Spring Boot.

Its only job is to update the data. It does not interfere with your application. And when it has finished its job, it could notify the application (if necessary). And the best part: you need no negotiation between instances.

The advantages of a small service are:

separation of concerns. A separate service which does only one thing (and does that well).

runs independent of other parts of the application.

errors are obviously limited to this service

easy to (un-)deploy

Advantages of Spring Boot:

Monitoring

Monitoring2

Did I mention Monitoring?

Easy to set up

Integrates nicely with all the other Spring Goodness

Other frameworks, which might be interesting for such a task are Dropwizard or Vert.x. I tried neither, but maybe you take a look.

P.S.:

Data from the database is cached in memory in each instance of the web app

Don't do that. There are nicer solutions like memcached or redis

Title: Java Web Application in Cluster with Shared Database. How to Negotiate an Instance to do Updates? How to Notify Instances of Updates?

Body:
I have a Java web application, running in a cluster of Tomcat application servers and a shared SQL/JDBC database. Data from the database is cached in memory in each instance of the web app.

My web application needs to update the database periodically with weather report data from a source outside of my web application (i.e. a background thread periodically collects and writes a whole bunch of data rows into a table in the database using SQL). Only one instance of my web application in the cluster should do this and then make the other instances aware that the data in the database has changed so that they can flush their caches and start using the updated data from the database. The propagation of the update to the database doesn't need to be real time.

What is the best practice to achieve this? How do I negotiate, which node will be the one to perform the updates? Which JEE technologies could I use? I want to avoid simply polling for changes in the database.


问:
Should I accept empty collections in my methods that iterate over them?
I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

```<code>public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
    foreach(var node in nodes)
    {
        // yadda yadda yadda
        yield return transformedNode;
    }
}
</code>```

In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.

My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.

Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?

答:
Utility methods should not throw on empty collections. Your API clients would hate you for it.

A collection can be empty; a "collection-that-must-not-be-empty" is conceptually a much more difficult thing to work with.

Transforming an empty collection has an obvious outcome: the empty collection. (You may even save some garbage by returning the parameter itself.)

There are many circumstances in which a module maintains lists of stuff that may or may not be already filled with something. Having to check for emptiness before each and every call to transform is annoying and has the potential to turn a simple, elegant algorithm into an ugly mess.

Utility methods should always strive to be liberal in their inputs and conservative in their outputs.

For all these reasons, for God's sake, handle the empty collection correctly. Nothing is more exasperating than a helper module that thinks it knows what you want better than you do.


答:
As ever, it depends.

Does it matter that the collection is empty?

Most collection-handling code would probably say "no"; a collection can have any number of items in it, including zero.

Now, if you have some sort of collection where it is "invalid" to have no items in it, then that's a new requirement and you have to decide what to do about it.

Borrow some testing logic from the Database world: test for zero items, one item and two items.  That caters for the most important cases (flushing out any badly-formed inner or cartesian join conditions).

Title: Should I accept empty collections in my methods that iterate over them?

Body:
I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

```<code>public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
    foreach(var node in nodes)
    {
        // yadda yadda yadda
        yield return transformedNode;
    }
}
</code>```

In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.

My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.

Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?


答:
I use two things - my voice and a whiteboard.

I mean, as much as developers hate meetings, you do need to work as a team. Standups are a great time to talk about new stuff you're doing in code (and to ask if something already exists). For big things, the sprint planning meeting is a good time for the entire team to provide input to the design, so everyone knows what is going on. And the sprint demo meeting is a good time to go into short detail about how the design has changed since the beginning of the sprint. In my experience, a whiteboard is the best tool for communicating that design amongst developers. Too few are proficient enough at reading code, and nobody reads (quickly obsolete) documentation.

And for particularly big/complex/subtle things, you'll likely need to have a dedicated meeting to disseminate that info.

Code reviews can help be a last line of defense against duplicated effort or misuse/mis-modification of code. But they catch things after all of the work is done. By having good teamwork, you prevent the wasted work from being done altogether.

Don't use agile/scrum? First, my condolences. Second, the premise still holds. You need to talk as a team - daily for little things. And you need to coordinate the bigger things periodically so that you work as a team.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
Yes, I do it all the time.

If you don't call any libraries, code generated from C requires no OS support. It also gives you fine control over the generated machine language. So it's great for writing drivers or other code that lives in kernel spaces, and other constrained situations like many kinds of embedded systems work. It's also the primary language for open-source projects I work with like X Windows, GTK+, and Clutter.

While you can do everything in C you can in C++, often C++'s mechanisms make it quicker and easier to write code. I love OOP and the way C++ classes encapsulate functionality, and I love RAII. Careful use of automatic destructor invocation when an object goes out of scope eliminates most of the memory and resource leaks that are the bane of C programming. The STL is basically a giant library of highly optimized algorithms and data structures; if you wanted to use them from C, you'd have to write them yourself or buy them someplace.

Unfortunately, for reasons I don't understand, the runtime system on Linux requires a special shared object library (equivalent to DLL on Windows, dylib on Mac) to run any C++, and it's not found when you run a C program. So I can't do one of my favorite Mac and Windows tricks, which is to write a C++-based shared object with a C-based API, and call it from a C program.

So here's my decision-making process:

Am I working in a constrained situation like a device driver? Use C.

Am I writing a Linux library anybody else will have to use? Use C.

Am I working inside code that's already written in C? Use C.

Am I writing a Mac or Windows library, or a Linux library only I will use? Write the internals in C++, but only expose a C interface to avoid the fragile binary interface problem.

Use C++.

One nice thing is that because C++ can compile C, if you really need fine-grained control over the code generated for a particular situation, you can just write C for that, and C++ for the rest, and compile it all with the C++ compiler.


问:
Coupling in OOP Contracts: Many simple values of few complex objects as arguments?
When designing an OOP-based application, should one prefer to transfer information between objects through complex objects that do a lot of handling work, or should I retrieve the data from the holding object first, and hand over many arguments in the call?

Take, for example, an application that does timeseries econometrics and needs to transfer a list of dates as available in the data set.
Using the first approach, I'd hand over a handle to the entire dataset-object, which in turn contains a calendar-object, which contains date-objects. All these objects handle different parts of the date-functionality, holiday checks, etc.
Within the receiving object, the call would somewhat look like this:

```<code>xlDate = MyDataset.MyCalendar.MyDate.convertToXlsFormat()
</code>```

While, obviously, that would happen before in the other case, and xlDate would simply be an argument.

Now I see that in general, tight coupling is bad, and this seems a little tight. I do, however, write scientific software, thus my users are always programmers who usually extend the program. For them, having all the handles available means less change, and less to worry about.

Think about a situation where you'd need yesterdays stockprices instead of todays. In the first situation, a programmer could very easily adapt the original function and replace it (since you can store functions in variables in Matlab, that can be done from a config file), while in the second, he'd need to add a control flow to the calling function, and thus increase the 'scope of responsibility', if you want to call it that, so the programmer needs a larger mental model of his specific function.

I thought of a wrapper as well, but I think that is just the worst of both: huge object handed to the wrapper, and your original function extends to the wrapper as well. I dont see benefits here.

So: How big is too big, and how deep nesting is too deep?

答:
Some would say that even calling the method of another object is too deep.  In your case, you shouldn't need to venture farther than MyDataset for all that you need in that method.  The fact that you do need to move farther is an indication that your method is stretching beyond the reach of what it should be allowed to do and minimize coupling.

If you are using MyDataset only to get MyCalendar, the fix should be fairly obvious:  remove unnecessary dependence to MyDataset and simply pass MyCalendar instance instead.

However, your class may even need an instance of MyDataset and MyCalendar.  That doesn't mean that you should be calling MyDataset.MyCalendar.  To fix this, you could do one of several things:

Move required functionality of MyCalendar into MyDataset (not recommended if it doesn't make sense, and in this case it most certainly does not)

Create a function in MyDataset that calls performs that functionality for you (facade pattern) (not recommended either for the same reasons as above).

Make MyCalendar instance be passed into the method (recommended, only if you need MyCalendar for that particular function).

Make MyCalendar instance be passed into constructor, in other words a class field (recommended, only if MyCalendar is used throughout your class).  To ease this with your code, you could provide an alternative constructor without MyCalendar instance passed, which assigns your field value of MyCalendar from the instance of MyDataset passed.

If you require a date be in a certain format, I encourage you to resist the urge to format it within your function.  This is for two important reasons:

Your function should not be doing anything other than what it is expected to do.  If it needs a date in a certain format, it should already be an argument in the proper format passed to your function.  It moves work outside of your function and simplifies it.

In this way you are modularizing your code as well as simplifying it.  The converter can be in its own class.  The end effect is the opposite of coupling.  You are removing code, however trivial, that doesn't pertain to what that class is supposed to do and thereby eliminating duplicated code and keeping it easy to maintain.

It seems clear to me that you know that coupling is wrong, but I just wanted to point out some ways I try to approach the problem and hopefully I gave you a couple of ways to reduce and even eliminate coupling in your code.


问:
Build a map with city blocks and road
Is there a design pattern or well known algorithm to build a simple map with roads and city blocks?

To have an idea of what's my target i describe some of the constraints and the context:

a matrix which represents a (rectangular) map

few possible city blocks represented as rectangles (eg, 4x3, 5x2, 1x6)

few possible road sizes (eg, 1, 2)

block are never connected, meaning that there is always a road between them

the result would be an array like this:

```<code>111101111100110
111101111100110
111100000000110
000001110000110
000001110000000
...
</code>```

where as for example, "1" are the blocks and "0" are the roads.

What I intend to do is to place a block where it is possible, then circumscribe with roads, and go on. This would be ok, but could lead to some place where blocks don't fit.

I would like to know if there is something in the state of the art of such algorithms.

答:
Most algorithms will come up with a randomly generated map purely based on a seed. It would never evaluate the map, and therefore not guarantee a nice user experience.

Since you have mentioned that you would like to build a "state of the art" map generator, the first thing that comes to my mind is genetic algorithms. Such an algorithm would create many different maps, based on an underlying gene combination. With each iteration, every map would be evaluated and improved. (the gene pool can be the exact same representation as your matrix above - what's even nice about this is that you will not have such a block city effect - unless that's what you want, then you can code it that way too).

In order to implement this, all you would need is an evaluation algorithm (for any given map). If you can come up with such an evaluation algorithm and you let this map-generation process run through a couple of iterations/evolutions (e.g. 100), you would end up with some really cool maps.

An evaluation algorithm (fitness) would consist of something like:

```<code>penalty = how many roads are too close to one another +
how many cities are too close to one another
</code>```

I have simplified the formula above, it should be a bit more like:  the sum of how close each city is to each other city + the sum of how close ... etc

then  fitness = 1/penalty

I did a quick search on: "genetic algorithm & map generator" and came up with some results that claim:

"In this paper we introduce a procedural map generator for a real-time strategy (RTS) game. The main component of this generator is a genetic algorithm devoted to create and evolve balanced maps, i.e. maps where no player has any map related advantage with respect to other players."

http://www.lcc.uma.es/~raul/pubs/procedural_map_generation_for_a_rts_game.pdf

Title: Build a map with city blocks and road

Body:
Most algorithms will come up with a randomly generated map purely based on a seed. It would never evaluate the map, and therefore not guarantee a nice user experience.

Since you have mentioned that you would like to build a "state of the art" map generator, the first thing that comes to my mind is genetic algorithms. Such an algorithm would create many different maps, based on an underlying gene combination. With each iteration, every map would be evaluated and improved. (the gene pool can be the exact same representation as your matrix above - what's even nice about this is that you will not have such a block city effect - unless that's what you want, then you can code it that way too).

In order to implement this, all you would need is an evaluation algorithm (for any given map). If you can come up with such an evaluation algorithm and you let this map-generation process run through a couple of iterations/evolutions (e.g. 100), you would end up with some really cool maps.

An evaluation algorithm (fitness) would consist of something like:

penalty = how many roads are too close to one another +
how many cities are too close to one another

I have simplified the formula above, it should be a bit more like:  the sum of how close each city is to each other city + the sum of how close ... etc

then  fitness = 1/penalty

I did a quick search on: "genetic algorithm & map generator" and came up with some results that claim:

"In this paper we introduce a procedural map generator for a real-time strategy (RTS) game. The main component of this generator is a genetic algorithm devoted to create and evolve balanced maps, i.e. maps where no player has any map related advantage with respect to other players."

http://www.lcc.uma.es/~raul/pubs/procedural_map_generation_for_a_rts_game.pdf


答:
Why focus on how big companies handle it when small companies also have the same issues? I'm the sole backend developer for a small company and have access to all of my company's Git repositories, both at work and at home. In theory I could take all this work and run off with it at any moment. There are many reasons why I don't including, but not limited to:

Theft is illegal

Losing my job means losing my paycheque, which is probably going to be worth more in the long run than any single project I could steal unless it was really, really good

Stealing the code is not stealing the infrastructure. I have neither the capacity nor knowledge required to run and maintain Facebook on my own even if I had full access to the source code

Stealing the code is not stealing the audience. There are already plenty of Facebook clones, people aren't going to flock to a literal clone just because it exists

Stealing the code would prevent or severely hinder me from getting another job in the field due to nobody else wanting to hire a source code thief

In short, there's very little incentive to actually steal code. I think the bigger issue is giving programmers the inspiration to develop your idea on their own in their own way, but at some point you have to be willing to trust your project to other people if you want them to be able to work on it. It's a gamble but unless you're going to do all the development work yourself, it's a gamble you'll have to take.

Title: How do big companies maintain their products' source code without it falling into wrong hands?

Body:
I am developing a web application by using ASP.NET. I would like to hire some developers to speed up my process but I am afraid what If my members take my code and go away? I am just wondering how big companies maintain their product code without falling into wrong hands. For eg: As I said you earlier I am hiring some staff to my speed up my process but you know every man is not same. Some people may work hardly and some may get the whole code and leave.

So my question is how big companies like Microsoft, Facebook, Yahoo keep their code protected?

Facebook currently have nearly 8,348 members (September 2014). If I say each and every person have the full Facebook code am I right or wrong?

So what are the best practices should I follow if I hire staff members to speed up the process?


问:
Alternative locking strategies
I'm having a problem with the design of my application, that neither optimistic nor pessimistic locking tends to solve. Here is a simplified/altered version of the problem that describes the situation.

Premise of the problem:

A document-processing application

A database where documents are stored

Multiple clients simultaneously access the database

What I try to achieve:

Say there are 10 unprocessed documents in the database. The first client requests the number of unprocessed documents. The response is 10. He requests 6 of them and starts processing. Before he finishes the second client requests the number of unprocessed documents. There is no point for him to process the same documents as the first client, so I want the program to answer "There are 4 unprocessed documents".

The problem if I optimistically lock those 6 documents:

In the particular case of this application transaction will take a long time and there is a big chance that other client still thinks that there are 10 unprocessed documents, not 4.

The problem if I pessimistically lock those 6 documents:

Again, the transaction takes a long time to complete and the other client will get stuck waiting for an answer about the number of documents.

The problem if I shorten the transaction and commit a status change before processing:

There is a chance that a power outage occurs, as a result 6 documents have a status "exported for processing", but in reality they aren't.

What alternative/custom locking strategy should be selected for this kind of scenario with concurrent access and long transactions?

答:
I would try to solve this with (at least) four document states

unprocessed

export started (but not under processing)

under processing (means: after export finished)

processed

Moreover, it will be probably a good idea to add a timestamp field to remember when the last state was changed, and as @Bart pointed out, an additional field which user caused the state change.

The state changes itself should be done for each document individual, in a single, short, atomic transaction. For example, before the export starts, set the state acccordingly. After the export was successfully finished, you set the state accordingly, too. When the document was processed, again. This gives you fine-grained control over the transactions and will allow individual failure-recovery.

For example, assumed there is a power outage, or a network outage in the middle of an export of 100 documents, this will leave you with about 50 docs in state "export started" and 50 docs "under processing". Using the timestamp field, you can now easily detect when there are documents for which the state is still "export started" for more than, lets say, 15 minutes, and reset those docs back to "unprocessed" after this time out. You can also reset docs from "under processing" back to unprocessed when the processing takes more than, lets say, 5 days. The check for these pending state may be done in a separate background program, running, for example, every minute, or every five minutes, whatever suits your process best.

Actually, "locking of those documents" should mean: all docs with the state different from "unprocessed" are locked for export & processing from others - but not by using a long lasting "database lock mechanism". The database should always stay responsive and tell you how many documents of which state are stored. To my understanding, this is still called a "pessimistic lock" strategy (since the same document is not to be processed by two different users at the same time), but with a failover strategy.

Title: Alternative locking strategies


答:
This is heavily dependent on your situation at hand. You don't give much surrounding context. Who are you writing this for? Is it a throwaway script to fulfil a specific need right now or do you intend for it to be used and maintained further on down the line?

If you're writing it for yourself then you can do whatever you want, it's only you that will be using it. Likewise if it's a throwaway script it doesn't really matter either since you're not going to be using it in the future.

If you're asking for 'best practice' or you're writing this with the intention that you will maintain it/other people will use it, then it's generally preferable to split code up into the smallest possible reusable chunks. This way it's very simple to modify, add or remove steps to your code that you may end up needing in the future but currently can see no use for.

It's a huge pain to have to rip up half of your code because you made certain assumptions a few months ago that no longer hold true. I, like many others I'm sure, learnt this lesson the hard way. It's generally better to write code with as few assumptions as possible and craft generic methods which can be swapped out at any time while having to alter as little existing code as possible.

Title: Should simple tasks be divided into separate functions?

Body:
If I have to write a simple program (25-35 lines), should I divide it even further, in functions which have a few lines and get executed max. 2 times, or to put it all im one?

e.g. if I need to add and substract 2 angles, should I do everything in one function or write one which converts everything back (and forth) and one which does the actual adding/substracting, leaving main with only I/O (extra: should an angle be defined as a structure or to stick to ints, assuming it isn't used anywhere else)?

My reasoning is that the code is clearer and that I find it easier to write as well, but apparently some people find it unnecessarily long and too complicated. I'm looking for "the right way", preferably examples or experiences from job interviews. Obviously large real-world applications need to be modular, but what about script-like or programs that focus solely on one algorithm?


答:
I see two important questions which determine the answer to this:

Can your function return anything meaningful and logical when passed an empty collection (including null)?

What is the general programming style in this applicaton/library/team?  (Specifically, how FP are you?)

1. Meaningful return

Essentially, if you can return something meaningful, then do not throw an exception.  Let the caller deal with the result.  So if your function...

Counts the number of elements in the collection, return 0.  That was easy.

Searches for elements which match particular criteria, return an empty collection.  Please do not throw anything.  The caller may have a huge collection of collections, some of which are empty, some not.  The caller wants any matching elements in any collection.  Exceptions only make the caller´s life harder.

Is looking for the largest/smallest/best-fit-to-the-criteria in the list.  Oops.  Depending on the style question, you might throw an exception here or you could return null.  I hate null (very much an FP person) but it is arguably more meaningful here and it lets you reserve exceptions for unexpected errors within your own code.  If the caller doesn´t check for null, a fairly clear exception will result anyway.  But you leave that to them.

Asks for the nth item in the collection or the first/last n items.  This is the best case for an exception yet and the one that is least likely to cause confusion and difficulty for the caller.  A case can still be made for null if you and your team are used to checking for that, for all the reasons given in the previous point, but this is the most valid case yet for throwing a DudeYouKnowYouShouldCheckTheSizeFirst exception.  If your style is more functional, then either null or read on to my Style answer.

In general, my FP bias tells me ¨return something meaningful¨ and null can have valid meaning in this case.

2.  Style

Does your general code (or the project´s code or the team´s code) favour a functional style?  If no, exceptions will be expected and dealt with.  If yes, then consider returning an Option Type.  With an option type, you either return a meaningful answer or None/Nothing.  In my third example from above, Nothing would be a good answer in FP style.  The fact that the function returns an Option type signals clearly to the caller than a meaningful answer may not be possible and that the caller should be prepared to deal with that.  I feel it gives the caller more options (if you will forgive the pun).

F# is where all the cool .Net kids do this kind of thing but C# does support this style.

tl;dr

Keep exceptions for unexpected errors in your own code path,  not entirely foreseeable (and legal) input from somebody else´s.


答:
There are more gradations in "locking" than just pure pessimistic ("don't allow any other accesses of this document while it's being looked at!") and pure optimistic ("assume that no accesses of or updates to this document will ever conflict with one another!").

There's more granular, still-pessimistic locking. E.g., allow clients to only take out one document at a time. This is akin to "row level locking" rather than "table locking" in DBMS design.

Multi-version concurrency control is what most modern database managers use instead of truly pessimistic locking assumptions. It can provide the same ACID properties as traditional pessimistic locking.

Concurrent real-time editors like Google Docs and EtherPad allow multiple concurrent updates from multiple clients to a consistent document model. Both the upside and the downside is that there is no "checkout" feature, and logical/semantic coordination is the responsibility f the clients.

Distributed revision control systems like Git and Mercurial take a very optimistic, permissive view: Everyone gets copies of all the document they want, and can make whatever changes they want. When they later want to commit those changes back, the assumption is that all changes can be successfully merged/re-integrated into the master (and if that can't be done with complete automation, that any hard conflicts can be automatically identified and presented to a human for sorting out).

But rather than a locking strategy, it sounds like you might need a distributed job scheduler. Every HPC environment from time immemorial to today has some form of job scheduling, including error handling for when jobs die or go AWOL. So in addition to alternate strategies for managing document locks yourself, consider whether this functionality could be more easily outsourced to a job manager.

Title: Alternative locking strategies

Body:
I'm having a problem with the design of my application, that neither optimistic nor pessimistic locking tends to solve. Here is a simplified/altered version of the problem that describes the situation.

Premise of the problem:

A document-processing application

A database where documents are stored

Multiple clients simultaneously access the database

What I try to achieve:

Say there are 10 unprocessed documents in the database. The first client requests the number of unprocessed documents. The response is 10. He requests 6 of them and starts processing. Before he finishes the second client requests the number of unprocessed documents. There is no point for him to process the same documents as the first client, so I want the program to answer "There are 4 unprocessed documents".

The problem if I optimistically lock those 6 documents:

In the particular case of this application transaction will take a long time and there is a big chance that other client still thinks that there are 10 unprocessed documents, not 4.

The problem if I pessimistically lock those 6 documents:

Again, the transaction takes a long time to complete and the other client will get stuck waiting for an answer about the number of documents.

The problem if I shorten the transaction and commit a status change before processing:

There is a chance that a power outage occurs, as a result 6 documents have a status "exported for processing", but in reality they aren't.

What alternative/custom locking strategy should be selected for this kind of scenario with concurrent access and long transactions?


问:
Separate servers vs local machine for builds, issue tracking etc on solo project
For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.

Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware.

答:
That depends, I would say.

Pro local machine:

Works without net.

Easier to maintain.

Pro separate server:

Some tools (continuous integration) may cause load that is annoying on your local machine.

You can access your tools from different machines.

You have a copy of your data on a different machine.


答:
As a matter of good design, accept as much variation in your inputs as practical or possible. Exceptions should only be thrown when (unacceptable input is presented OR unexpected errors happen while processing) AND the program cannot continue in a predictable way as a result.

In this case, it should be expected that an empty collection will be presented, and your code needs to handle it (which it already does). It would be a violation of all that is good if your code threw an exception here.  This would be akin to multiplying 0 by 0 in mathematics. It is redundant, but absolutely necessary for it to work the way it does.

Now, on to the null collection argument. In this case, a null collection is a programming mistake: the programmer forgot to assign a variable. This is a case where an exception could be thrown, because you cannot meaningfully process that into an output, and attempting to do so would introduce unexpected behavior.  This would be akin to dividing by zero in mathematics - it is completely meaningless.


问:
Nearest color algorithm using Hex Triplet
Wikipedia has a list of colors that I am using for a basis of color names.  I want to find the nearest named color given an arbitrary RGB value.

For example #5D8AA8 hex triplet is "Air Force Blue". This information will be stored in a database table (tbl_Color (HexTriplet,ColorName)) in my system

Suppose I created a color with #5D8AA7. I need to get the nearest color available in the tbl_Color table. The expected answer is "#5D8AA8  - Air Force Blue". This is because #5D8AA8 is the nearest color for #5D8AA7.

Do we have any algorithm for finding the nearest color?

References

Algorithm for parsing hex into color family

Algorithm for finding the color between two others - in the colorspace of painted colors

答:
You can treat RGB colours as a 3-dimensional vector.

The distance between any two points (colors) is given by the following formula:

Your color is given as: #5D8AA8

This is made up of three hexadecimal values: [5D][8A][A8]

Follow these steps:

Strip the # off the string

Break the remainder into 2x2x2 pieces and

Use a Hex2Dec converter to convert your color into a 3D decimal values representation

Use the formula provided above to calculate the change in color.


答:
Large companies do restrict which of their employees has access to their source code.  And having access to source for one product does not mean you have access to source for all products.

But I think this has less to do with preventing the kind of theft you're talking about, and more to do with avoiding accidental changes to the wrong code.

One of the large companies you named definitely had an incident where an employee or intern posted some source code online.  They weren't happy about it, but in the end the damage was mainly reputational (i.e. they allowed it to happen).

I'm with Kilian.  The source code just isn't as important as you think it is.  I create source code and would love to believe the fruit of my work is the most valuable thing my client possesses, but it simply is not.


答:
Do you use the exact same code that is more than one or two lines in other parts?  split

Will you do it in the future? split


答:
Let's step back and use a different example which computes the arithmetic mean of an array of values.

If the input array is empty (or null), can you reasonably fulfill the caller's request? No. What are your options? Well, you could:

present/return/throw an error. using your codebase's convention for that class of error.

document that a value such as zero will be returned

document that a designated invalid value will be returned (e.g. NaN)

document that a magic value will be returned (e.g. a min or max for the type or some hopefully-indicative value)

declare the result is unspecified

declare the action is undefined

etc.

I say give them the error if they have given you invalid input and the request cannot be completed. I mean a hard error from day one so they understand your program's requirements. After all, your function is not in a position to respond. If the operation could fail (e.g. copy a file), then your API should give them an error they can deal with.

So that can define how your library handles malformed requests and requests which may fail.

It's very important for your code to be consistent in how it handles these classes of errors.

The next category is to decide how your library handles nonsense requests. Getting back to an example similar to yours -- let's use a function which determines whether a file exists at a path: bool FileExistsAtPath(String). If the client passes an empty string, how do you handle this scenario? How about an empty or null array passed to void SaveDocuments(Array<Document>)? Decide for your library/codebase, and be consistent. I happen to consider these cases errors, and forbid clients from making nonsense requests by flagging them as errors (via an assertion). Some people will strongly resist that idea/action. I find this error detection very helpful. It is very good for locating issues in programs -- with good locality to the offending program. Programs are much clearer and correct (consider evolution of your codebase), and don't burn cycles within functions which do nothing. Code's smaller/cleaner this way, and the checks are generally pushed out to the locations where the issue may be introduced.


问:
How to track temporal changes in a database?
Imagine a software for theater owners. You can accept reservations for the different cinema halls. Each hall has a different number of seats.

Say the owner wants to know how many people visited the cinema on each day in the past years. Easy, just query the Reservations table and group by date.

What if we want to know the utilized capacity - how much % of seats are sold? Easy, just join the reservations with the Cinema_Halls table, and divide the number of reservations by the number of available seats.

However, on August 1st, the owner decides to add more seats to one of the cinema halls, and updates the database accordingly. But now, all the utilization percentages before August 1st are invalid, as we do not have access to the historical number of seats.

There are three solutions that come to my mind:

Add a new table, which tracks number of seats over time. Tuple: (HallID, numberOfSeats, validFrom, validUntil)

Don't modify the cinema_hall record, but add a new one with a different number of seats, and mark the old one as invalid.

Use special temporal database features of your DBMS

(1) seems to be cumbersome. If you really want the capability to get all historical data, you would need a separate table for every single value that could change.

(2) is not how the user would want to work, and could introduce side effects.

(3) might not be supported by your database system.

What would be a good solution to solve this?

答:
It seems you raised the question with the answer already:

From my point of view, the solution I would have tried is:

"... Add a new table, which tracks number of seats over time. Tuple: (HallID, numberOfSeats, validFrom, validUntil) ..."

This way, you are also able to track when the number of seats was changed. Also in the code you are able to know the exact % of seats sold by each date. You will not depend on a specific Database feature (DB is a detail to the SW generally speaking).

I am not sure how marking the first entry as invalid would have helped, because if you do not track the dates you will not be able to know the capacity of a Hall at a given time. So this would void number 2.


问:
Watching file changes/additions/removal, but with an eye on partial transfer
I would like to monitor the filesystem in python, so that my application gets warned of the new file addition, file removal, or file change. Once the file is detected, the application starts extracting the contained data through various plugins. The problem is that I am dealing with big files, and when the user starts copying a file from outside into the watched directory, it will be detected, but it will appear as corrupted. Checking for file size between invocations is potentially a good strategy, but it ignores the fact that other generators of the file (such as wget) might have long pauses when the file is not changing in size, and yet is not completed. I don't have control of the file format I am downloading either, so I can't check for an end-of-file mark, because it could not be there.

Is there a cross platform way (or different, platform specific ways for linux and windows) to solve this problem? Can I check if a file is currently open
somehow? How is this problem solved in other software?

答:
Since you know which file is changed but not by which process this is hard but solvable. You can use psutil to handle this.

With psutil you can iterate over all running processes and ask them for their open files. Written as pseudo code:

```<code>for process in psutil open processes:
    for file in process all open files:
        check if this your file:
            yes => remember pid
pid is set:
    yes => wait for the process to finish
do your work with the file
</code>```

This is an easy but not very performing way to handle your problem.

Body:
Since you know which file is changed but not by which process this is hard but solvable. You can use psutil to handle this.

With psutil you can iterate over all running processes and ask them for their open files. Written as pseudo code:

for process in psutil open processes:
    for file in process all open files:
        check if this your file:
            yes => remember pid
pid is set:
    yes => wait for the process to finish
do your work with the file

This is an easy but not very performing way to handle your problem.