问:
Find likely candidates for visited locations along GPS track
I'm creating a visualization tool for workout data, specializing on bicycle rides. I'm looking for ways to generate more value from the data that was recorded. Since there usually is a GPS track available I was wondering if and how I could extract possible visited towns or special locations during the trip. I'm especially interested in the possible intended destination of a trip.

Now this is really easy if you have a track that goes from location A to B but my tracks are usually round courses where the start and end location are the same.

Some special cases exist where the destination should be relatively easy to determine. Those are:

There is a location where the recording was paused, thus causing a gap in the recorded data

Recording isn't paused but the location stays the same for a considerable time. The likely candidate for the intended destination would be the longest of such periods.

Assuming we don't encounter one of the above circumstances I'd like to create a list of cities / special locations visited or rode by.

I can imagine narrowing down the search by dividing the track into thirds and only analyze the middle segment, which most likely contains the intended destination.

Now there are APIs available that could give me nearby locations to any given GPS point but asking for the information for every point would cause thousands of requests, since there usually is one GPS point available every second.

Now my question is:

Is there any known algorithm or technique that would decrease the number of requests I would have to send to a location API? If not, what would be a good way to find possible intended locations along a GPS track if the track contains no pauses or hot spots where the location is approximately the same for a extended period. I realize this is the same question as asking for any special location along a segment of a GPS track, which I have no good idea for either.

An example of the desired result would look like this:

A GPS track is uploaded

The algorithm/program returns a list of
locations with name and address, like:

City A, address

City B, address

Restaurant A, address

Also all ideas including how I could structure and group the location data to help with the analysis are appreciated.

答:
So I think it is going to depend on the nature of your data quite a bit. Whatever you choose to do, understanding how your data looks, feels, and scales is going to be important.

Frankly, assuming bike rides are often short, I suspect that calculating one or more bounding boxes for the bike ride, fetching all points of interest within the box, and then doing all further processing locally is going to be your best option. Again, try to get a feel for the scales involved, but that's my hunch. One or a few heavy requests vs. thousands of pinpricks is likely going to be way faster.

So once you have the list of locations, you can do local distance calculations without too much pain. Note that depending on scale you may need to employ a spatial structure like an R-tree etc. locally; another potential tool would be to reduce the curve to a much smaller series of line segments and then consider point-line segment distances.

After that, it's going to get subjective with regards to finding the final destination/waypoints. Here are some thoughts:

In addition to pauses and stops, I think your hypothesis of the middle third is good. You may be able to extend this to a general weighting scheme, or generalize to more of a "k-means" sort of an approach.

Do you have information regarding the general type of point of interest? Some points of interest inherently require stopping to feast (cycling past a restaurant is just not as satisfying) and some may be primarily a feast for the eyes (parks etc.). So that can be used to filter too: going near a restaurant without a stop is an unlikely destination, going near a park likely does not require stopping. Note that a simple heuristic by name may go a decent ways here for type of stop.

Similarly, distance by type of point of interest may be valuable. Restaurants would require an exact hit, parks would require a close hit, and scenic views may be much more distant.

It would be interesting to look at the role of inflection points in the curve vs. points of interest - I don't know if there is a positive correlation but there could be.

Good luck! Let us know how it turns out.


答:
Get all possible destinations within bounding box of your GPS trace.

Find the ones that are closest to the actual route.

Rank them by:

time spent in their vicinity

time spent before and after them (ie, weighting for "middle of the trip")

other factors like interestingness of destination (based on whatever you know about your user(s))

Pick the best.

ContentLicense: CC BY-SA 3.0

Title: Find likely candidates for visited locations along GPS track

Body:
I'm creating a visualization tool for workout data, specializing on bicycle rides. I'm looking for ways to generate more value from the data that was recorded. Since there usually is a GPS track available I was wondering if and how I could extract possible visited towns or special locations during the trip. I'm especially interested in the possible intended destination of a trip.

Now this is really easy if you have a track that goes from location A to B but my tracks are usually round courses where the start and end location are the same.

Some special cases exist where the destination should be relatively easy to determine. Those are:

There is a location where the recording was paused, thus causing a gap in the recorded data

Recording isn't paused but the location stays the same for a considerable time. The likely candidate for the intended destination would be the longest of such periods.

Assuming we don't encounter one of the above circumstances I'd like to create a list of cities / special locations visited or rode by.

I can imagine narrowing down the search by dividing the track into thirds and only analyze the middle segment, which most likely contains the intended destination.

Now there are APIs available that could give me nearby locations to any given GPS point but asking for the information for every point would cause thousands of requests, since there usually is one GPS point available every second.

Now my question is:

Is there any known algorithm or technique that would decrease the number of requests I would have to send to a location API? If not, what would be a good way to find possible intended locations along a GPS track if the track contains no pauses or hot spots where the location is approximately the same for a extended period. I realize this is the same question as asking for any special location along a segment of a GPS track, which I have no good idea for either.

An example of the desired result would look like this:

A GPS track is uploaded

The algorithm/program returns a list of
locations with name and address, like:

City A, address

City B, address

Restaurant A, address

Also all ideas including how I could structure and group the location data to help with the analysis are appreciated.


问:
Name of this pattern to wrap functionality
I have a system that allows certain functionality to be implemented different ways, but requires that the functionality of each implementing class be wrapped in another layer. For example, each implementor has a doFoo method that interacts with an API. The implementor classes can be loaded at runtime (they are, essentially, plugins for hooking into different APIs), and thus the set of possible implementors is not fixed and cannot simply be handled by a switch or an enum-like structure.

But each time one of the implementor classes executes its doFoo method, I also need to ensure that additional, method-specific code occurs before and after (think system-wide logging, error-handling, and input and output sanity-checking that are the same for all implementors).

I have the following basic setup:

an interface, FooInterface

an abstract class FooAbstract that implements FooInterface and sets up some default actions.

a concrete class Foo that extends FooAbstract. Foo serves as a kind of factory/bridge class that instantiates an implementor and adds its own code when calling any of the implementor's methods

concrete classes FooImplementorABC, FooImplementorXYZ, etc., each of which extends FooAbstract.

That way, when a user wants to use the ABC implementation of FooInterface, the user calls new Foo('ABC'). The Foo constructor instantiates the right implementor and the implementor's code as necessary.

Example code (sample code only; the real classes are more complex and are all broken into files and autoloaded appropriately):

```<code><?php
interface FooInterface
{
    public function doFoo();
    public function doBar();
    public function doGenericThing();
}

abstract class FooAbstract implements FooInterface
{
    abstract public function doFoo();
    abstract public function doBar();

    public function doGenericThing()
    {
        echo "Doing something generic\n";
    }
}

class Foo extends FooAbstract
{
    /** @var FooAbstract */
    private $implementor;

    /**
     * The constructor for this class accepts an implementation name.
     * It then attempts to instantiate the appropriate implementor
     * class.
     *
     * @param $implementationName String
     */
    public function __construct($implementationName)
    {
        $implementorClassName = 'FooImplementor' . $implementationName;
        try {
            if (class_exists($implementorClassName)) {
                $this->implementor = new $implementorClassName(); // Yes, this works in PHP! One of its best or worst features, depending on your perspective.
            } else {
                throw new Exception("ERROR: No implementation for $implementationName found!");
            }
        } catch (Exception $e) {
            echo "\n\n{$e->getMessage()}\n\n";
        }
    }

    public function doFoo()
    {
        echo "Doing Foo\n";
        // Do some stuff
        $this->implementor->doFoo();
        // Do some stuff
        echo "Done with Foo\n\n";
    }

    public function doBar()
    {
        echo "Doing Bar\n";
        // Do some stuff
        $this->implementor->doBar();
        // Do some stuff
        echo "Done with Bar\n\n";
    }
}

class FooImplementorABC extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor ABC just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor ABC just did Bar!\n";
    }
}

class FooImplementorXYZ extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor XYZ just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor XYZ just did Bar!\n";
    }
}

$myFooABC = new Foo('ABC');
$myFooXYZ = new Foo('XYZ');

$myFooABC->doFoo();
$myFooXYZ->doFoo();
$myFooABC->doBar();
$myFooXYZ->doBar();

$myFooQRS = new Foo('QRS'); // displays an error message
</code>```

All of this works just fine; the methods all get wrapped correctly, the implementation details are unimportant to the consumer, etc.

My questions are:

Is this a pattern or an anti-pattern?

If it's a pattern, is there a name for it? I can't figure out what it would be. It seems to me like a hybrid of the factory, bridge, and decorator patterns.

If it's an anti-pattern, why? How is this going to bite me down the road?

答:
an anti-pattern

N/A

because you rely on a string to instanciate $implementor. Imagine you refactor the class' names from FooImplementorABC and FooImplementorXYZ to MyClass and BarWXY. Your "factory" (Foo) won't be able to instanciate any implementor and you have no way to figure it out except by diving into the code. Plus the class Foo has 2 responsibilities (which violates the SRP): finding the correct implementation of FooAbstract and echoing some things.

My suggestion: delegate the responsibility for the FooImplementor creation outside of the class.

```<code>class LoggingFoo extends FooAbstract
{
    private $origin;

    public function __construct($origin)
    {
        $this->origin = $origin;
    }

    public function doFoo()
    {
        echo "Doing Foo\n";
        $this->origin->doFoo();
        echo "Done with Foo\n\n";
    }

    public function doBar()
    {
        echo "Doing Bar\n";
        $this->origin->doBar();
        echo "Done with Bar\n\n";
    }
}
</code>```

Usage change to:

```<code>$myFooABC = new LoggingFoo(new FooImplementorABC());
$myFooXYZ = new LoggingFoo(new FooImplementorXYZ());
$myFooABC->doFoo();
$myFooXYZ->doFoo();
$myFooABC->doBar();
$myFooXYZ->doBar();
</code>```

If you don't want your "client code" to be responsible for the FooImplementor creation, delegate it to a factory (does the concept of enum event exists in PHP ?):

```<code>public class FooFactory
{
    public static FooAbstract create(FooType $type)
    {
        switch($type)
        {
            case FooType.ABC:
                return new FooImplementorABC();
            case FooType.XYZ:
                return new FooImplementorXYZ();
            default:
                throw new Exception('Unsupported type ' + $type);
        }
    }
    public static FooAbstract createWithLogging(FooType $type)
    {
        return new LoggingFoo(create($type));
    }
}
</code>```

Usage becomes:

```<code>$myFooABC = FooFactory.createWithLogging(FooType.ABC);
$myFooXYZ = FooFactory.createWithLogging(FooType.XYZ);
</code>```

Body:
an anti-pattern

N/A

because you rely on a string to instanciate $implementor. Imagine you refactor the class' names from FooImplementorABC and FooImplementorXYZ to MyClass and BarWXY. Your "factory" (Foo) won't be able to instanciate any implementor and you have no way to figure it out except by diving into the code. Plus the class Foo has 2 responsibilities (which violates the SRP): finding the correct implementation of FooAbstract and echoing some things.

My suggestion: delegate the responsibility for the FooImplementor creation outside of the class.

class LoggingFoo extends FooAbstract
{
    private $origin;

    public function __construct($origin)
    {
        $this->origin = $origin;
    }

    public function doFoo()
    {
        echo "Doing Foo\n";
        $this->origin->doFoo();
        echo "Done with Foo\n\n";
    }

    public function doBar()
    {
        echo "Doing Bar\n";
        $this->origin->doBar();
        echo "Done with Bar\n\n";
    }
}

Usage change to:

$myFooABC = new LoggingFoo(new FooImplementorABC());
$myFooXYZ = new LoggingFoo(new FooImplementorXYZ());
$myFooABC->doFoo();
$myFooXYZ->doFoo();
$myFooABC->doBar();
$myFooXYZ->doBar();

If you don't want your "client code" to be responsible for the FooImplementor creation, delegate it to a factory (does the concept of enum event exists in PHP ?):

public class FooFactory
{
    public static FooAbstract create(FooType $type)
    {
        switch($type)
        {
            case FooType.ABC:
                return new FooImplementorABC();
            case FooType.XYZ:
                return new FooImplementorXYZ();
            default:
                throw new Exception('Unsupported type ' + $type);
        }
    }
    public static FooAbstract createWithLogging(FooType $type)
    {
        return new LoggingFoo(create($type));
    }
}

Usage becomes:

$myFooABC = FooFactory.createWithLogging(FooType.ABC);
$myFooXYZ = FooFactory.createWithLogging(FooType.XYZ);


问:
What are the advantages of linear probing over separate chaining or vice-versa when implementing hash tables?
I've been brushing up on algorithms and reviewed these two methods of implementing hash tables.  It seems like they largely have similar performance characteristics and memory requirements.

I can think of some disadvantages to linear probing -- namely, that widening the array could be expensive (but this is done, what, 2 log N times at most?  Probably not a big deal) and that managing deletions is a bit more difficult.  But I'm assuming there are advantages, too, or it wouldn't be presented in textbooks as a viable method of implementation next to the more obvious implementation.

Why would you choose one over the other?

答:
Check out this great answer:

https://stackoverflow.com/questions/23821764/why-do-we-use-linear-probing-in-hash-tables-when-there-is-separate-chaining-link

Quoting here:

I'm surprised that you saw chained hashing to be faster than linear probing - in practice, linear probing is typically significantly faster than chaining. In fact, that's the main reason it's used.

Although chained hashing is great in theory and linear probing has some known theoretical weaknesses (such as the need for five-way independence in the hash function to guarantee O(1) expected lookups), in practice linear probing is typically significantly faster due to locality of reference. Specifically, it's faster to access a series of elements in an array than it is to follow pointers in a linked list, so linear probing tends to outperform chained hashing even if it has to investigate more elements.

There are other wins in chained hashing. For example, insertions into a linear probing hash table don't require any new allocations (unless you're rehashing the table), so in applications like network routers where memory is scarce, it's nice to know that once the table is set up, the elements can be placed into it with no risk of a malloc fail.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I would like to see an else clause for while, for, and foreach. E.g.:

```<code>while (/*condition*/) {
   /* display each result */
}
else {
   /* condition was never true; display "no results found" message */
}
</code>```

The else block is only executed if the condition for the while was never true.

This would make it so you wouldn't need to keep track of Boolean flags, and perhaps it could help you think about boundary cases and possible error conditions.

ContentLicense: CC BY-SA 2.5

Body:
I would like to see an else clause for while, for, and foreach. E.g.:

while (/*condition*/) {
   /* display each result */
}
else {
   /* condition was never true; display "no results found" message */
}

The else block is only executed if the condition for the while was never true.

This would make it so you wouldn't need to keep track of Boolean flags, and perhaps it could help you think about boundary cases and possible error conditions.


问:
Design of an online book reader
I want to design an online book reader system as a programming exercise. I wrote down the following requirements:

Searching a book by title.

Bookmarking a book.

Mark a book as favorite.

Give rating.

Manage users.

The constraints are that only one user can read a particular book at a time.

I follow Clean architecture. Which advocates that:

Defer implementation details like DB and delivery mechanisms.

Start with the use case first which guides Interactors / Service Objects.

In designing use cases you will come across different Entities.

Don't pass objects between boundaries.

I know that question seems too broad hence but I wanted to proper context first, I will proceed from first step. I would like to know to pick up which use case first? Second, should I formulate all Service Objects and then move on to Entities?

答:
Yes start from finding use case then you should find all entities with their relationship and then start building application.

Restriction can be applied by single column value 1or zero, opened or closed respectively in databases table of books against each book

Title: Design of an online book reader


问:
How does google calculate travel distance/time
I've been working for quite a while now on a service that generates optimal routes for a given set of addresses and vehicles (Vehicle routing problem / traveling salesman problem).

Now it's all working fine, but the bottleneck is getting the distance/time between two addresses used for calculation. Currently we use webservices like google/mapquest to request the distance and store the result for caching. So we only request the distances once.

At the moment we have about 100milion records in cache and it made me wonder: How does google do this for every address in the world? We are talking about hundreds of billions of combination.

Even just storing every corner in a street map and then calcalate each straight road with a haversine formule and adding the results would result in massive amounts of data.

Now I understand google can handle massive amounts of data, but there are also a lot of small companies providing distance/street information. Do they all store all this data on their own or is there some magical method of calculation i'm missing?

答:
Simple.  Google uses divide and conquer techniques.  If you take long road trips, you almost certainly use the interstate.  Due to their common use in performing calculations, a lot of such calculations are simply lookups.  What is the distance between say Tennessee and Florida?  Calculate the interstate route and lookup the respective distance between these two points on the interstate.

Anything else is simply a matter of calculating shortest distance from the starting point to the interstate and later from the interstate to the final destination, which reduces a potentially thousand mile journey calculation into two 10 mile journeys and a table lookup.


答:
TL;DR: Yes, there is something you are missing.

Google appears to calculate a true minimum-time route based on their estimate of travel times over every road segment in the area. The time to calculate a perfectly optimal route between two points in a network is linear in the number of edges in the network, so even through a dense street network it is possible to calculate an optimal route fairly quickly. In my experience, Google does this very well -- they seem to really consider all the possible routes, and sometimes calculate routes over surface streets that few people would have considered.

Title: How does google calculate travel distance/time

Body:
I've been working for quite a while now on a service that generates optimal routes for a given set of addresses and vehicles (Vehicle routing problem / traveling salesman problem).

Now it's all working fine, but the bottleneck is getting the distance/time between two addresses used for calculation. Currently we use webservices like google/mapquest to request the distance and store the result for caching. So we only request the distances once.

At the moment we have about 100milion records in cache and it made me wonder: How does google do this for every address in the world? We are talking about hundreds of billions of combination.

Even just storing every corner in a street map and then calcalate each straight road with a haversine formule and adding the results would result in massive amounts of data.

Now I understand google can handle massive amounts of data, but there are also a lot of small companies providing distance/street information. Do they all store all this data on their own or is there some magical method of calculation i'm missing?


问:
Licensing, how to?
I'm currently developing an application that has quite a few dependencies.

Now I want to release the code as open-source under the WTFPL (Do What the Fuck You Want to Public License).

Of course this only applies to my code, not that of any dependency. How would I go about this?

I pull in my dependencies via an automatic build tool (sbt in that case).

More concretely:

Assume I'm pulling in lwjgl (http://www.lwjgl.org/) and another third-party-library that consists only of one file and has the copyright at the top of it.

Now how would I do this legally correctly? Just add the license to the code as it's "obvious" what's my code and what's not? Or...

I'm not sure if there is a license file in the (automatically pulled down) dependencies. Actually I just had a look into my .ivy2 folder and I can't find a license for e.g. lwjgl

Any ideas? I'm sorry, if (and it probably has) this has been covered before, but I want to make sure I'm doing this right and I couldn't find my specific question(s) [yes, I search before I post ;)]

答:
Firstly, make sure all the licenses of your dependencies allow you to share their libraries to your customers. You might need to credit the authors anywhere, it's all written down in the licenses. </p>

<p>If you have the permission, you also need to provide the licenses of the libraries in your product. If you don't have the permission, you should contact the authors of the libraries and try to buy it, so you can use it in your product. I bet this is not required, as your software is not for commecial use. </p>

Title: Licensing, how to?

Body:
Firstly, make sure all the licenses of your dependencies allow you to share their libraries to your customers. You might need to credit the authors anywhere, it's all written down in the licenses.

If you have the permission, you also need to provide the licenses of the libraries in your product. If you don't have the permission, you should contact the authors of the libraries and try to buy it, so you can use it in your product. I bet this is not required, as your software is not for commecial use.


问:
Should I declare variables at the top of the function for reasons other than the scope rules?
In JavaScript, one should declare all variables at the beginning of the function to mitigate the risk of mistakes related to the fact that the scope of variables is a function. The following code illustrates this non-intuitive scope by actually printing "Hello, World" to the console:

var demo = function () {
    if (false) {
        var hello = "Hello, World";
    }

    console.log(hello);
};
```

Similarly, in VB6 (but not in VB.NET), the variables have a scope of a function/sub, which also means that they would better be declared at the top of the function/sub block.

C, C++, Java, C#, Python or PHP don't have any reason to move the declaration of variables to the top of the method/function: instead, variables are preferably declared close to the location where they are used.

Are there languages where it is better to declare the variables at the top of the function-type block (instead of declaring them as close as possible to the location where they are used) for a reason other than function-level scoping?

In other words, is the non-intuitive scoping similar to the one used by VB6 and JavaScript the only reason to move the declaration of variables at the top of a function?

答:
The phrasing "Are there languages where it is better to..." suggests your question may not have a definite (non-subjective) answer. Better in what regard?

In some languages, you might get a benefit by ordering your variable declarations in such a way as to optimise memory usage, but with modern compilers this should be taken care of for you.

So it seems to me that it's a matter of style and personal preference.

My personal preference, having teethed on Macintosh Pascal, has been to declare variables at the very start regardless of where they'll be used (in any case, methods should be short, so that shouldn't be "too far away"). To me, this provides a good overview of "what pieces are in play", so to speak.

However, now that I work in Java, I strive to put my variables in the smallest reasonable scope (possibly just outside of the loop they'll be used in). As you explain, this approach doesn't work for JavaScript, so there's a trade-off between "human overview" and "language efficiency".


问:
Do any languages have syntax for promises?
I'm really glad that EcmaScript 6 has promises built into the language, but the syntax will still be quite wordy:

```<code>new Promise(f).then(r => {
...
}).then(r2 =>
...
}).catch(...
</code>```

I'm just wondering if there are any languages that have syntactic sugar for promises, so the result looks more like conventional imperative programming. Maybe hypothetically something like:

```<code>fetch f {
get r
  ...
get r2
  ...
catch
  ...
}
</code>```

答:
Yes, there are several such languages:

C# has async methods and the await keyword. Technically speaking, any object which implements a certain syntactic pattern can be awaited, but the intention is for this syntax to be used for, well, asynchronous programming, and the only objects in the framework which implement the syntactic pattern are Task<T> objects, which are futures/promises (depending on your exact definition of "future" and "promise", they may be futures, promises, both, or neither).

Visual Basic.NET has the same syntax with the same semantics

F# has asynchronous workflows, which were the inspiration for async/await

In languages with macros, libraries can implement their own syntax (within limits), and so there are promise libraries in Scala, Scheme, Common Lisp, Clojure, and other Lisps, which have what looks like builtin syntax.

Python 3.5+ has async / await

The next version of ECMAScript will very likely have async/await

The next version of C++ may or may not have resumable/await

And last but very important: Oz does not have special syntax for promises, because in Oz every variable is a dataflow-variable, and every value is a promise!


答:
Each computer language has its strengths and pitfalls. Each has its own coding standards/practices often accepted, built and dictated by the community around it. Because programming is a precise art I would say, unless there is a good reason to do something, you shouldn't.

Now there are very good reasons to declare variables close to where they are used:

Makes it easy to determine the type, when reading code.

Makes it easy to delete code including the declaration all together.

But as you suggest, for some languages there are better reasons to not do that, for sake of clarity or scope. Another reason could be to reserve memory or registers early on, again it depends on the language you are using. A new language may come along with non-C like semantics and may require a different approach to where variables get declared.

I would also always recommend following the coding standards established by the community for your language of choice.

Title: Should I declare variables at the top of the function for reasons other than the scope rules?

Body:
In JavaScript, one should declare all variables at the beginning of the function to mitigate the risk of mistakes related to the fact that the scope of variables is a function. The following code illustrates this non-intuitive scope by actually printing "Hello, World" to the console:

var demo = function () {
    if (false) {
        var hello = "Hello, World";
    }

    console.log(hello);
};
```

Similarly, in VB6 (but not in VB.NET), the variables have a scope of a function/sub, which also means that they would better be declared at the top of the function/sub block.

C, C++, Java, C#, Python or PHP don't have any reason to move the declaration of variables to the top of the method/function: instead, variables are preferably declared close to the location where they are used.

Are there languages where it is better to declare the variables at the top of the function-type block (instead of declaring them as close as possible to the location where they are used) for a reason other than function-level scoping?

In other words, is the non-intuitive scoping similar to the one used by VB6 and JavaScript the only reason to move the declaration of variables at the top of a function?


问:
What is an "ontology" in the context of the Semantic Web?
Okay, I have been learning SPARQL to query dbpedia and I can't seem to find clear and practical tutorials related to SPARQL and the Semantic Web. If I say that an ontology is analogous to an SQL table definition or maybe a specification of an object's members should I be slapped?</p>

答:
A semantic web ontology is defined in OWL (Web Ontology Language). It has limited support for developer tooling and is primarily an input to an inference engine. Such an engine works deductively to conclude new facts for inclusion in the store (or, conversely, to expand the results of queries).

For example if:

```<code>ex:object1 ex:hasAncestor ex:object2 .
ex:object2 ex:hasAncestor ex:object3
</code>```

then in OWL you can declare that that ex:hasAncestor is transitive and the inference engine will add a new fact to your store:

```<code>ex:object1 ex:hasAncestor ex:object3 .
</code>```

This is just one example of a new category of facts that can be inferred using OWL reasoning. OWL is often used to build mappings between similar vocabularies, or to declare that two partial records of an object should be merged (even/especially if they have different identities). You you might declare that email address fields are unique identifiers and the store will merge records for you according to the email address.

OWL has no unique business value compared to other technology, as the same logic can be always re-implemented in queries fairly trivially, but offers an interesting implementation strategy suitable for a range of use cases.

Body:
A semantic web ontology is defined in OWL (Web Ontology Language). It has limited support for developer tooling and is primarily an input to an inference engine. Such an engine works deductively to conclude new facts for inclusion in the store (or, conversely, to expand the results of queries).

For example if:

ex:object1 ex:hasAncestor ex:object2 .
ex:object2 ex:hasAncestor ex:object3

then in OWL you can declare that that ex:hasAncestor is transitive and the inference engine will add a new fact to your store:

ex:object1 ex:hasAncestor ex:object3 .

This is just one example of a new category of facts that can be inferred using OWL reasoning. OWL is often used to build mappings between similar vocabularies, or to declare that two partial records of an object should be merged (even/especially if they have different identities). You you might declare that email address fields are unique identifiers and the store will merge records for you according to the email address.

OWL has no unique business value compared to other technology, as the same logic can be always re-implemented in queries fairly trivially, but offers an interesting implementation strategy suitable for a range of use cases.


问:
Illusory code duplication
The usual instinct is to remove any code duplication that you see in the code. However, I found myself in a situation where the duplication is illusory.

To describe the situation in more details: I am developing a web application, and most views are basically the same - they display a list of items which the user can scroll and choose from, a second list that contains selected items, and a "Save" button to save the new list.

It seemed to me that the problem is easy. However, each and every view has its own quirks - sometimes you need to recalculate something, sometimes you must store some additional data etc. These, I solved by inserting callback hooks in the main logic code.

There are so many minute differences between the views that it is becoming less and less maintainable, because I need to provide callbacks for basically all functionality, and the main logic starts to look like a huge sequence of callback invocations. In the end I am not saving any time or code, because every view has its own code that is executed - all in callbacks.

The problems are:

the differences are so minute that the code looks almost exactly alike in all views,

there are so many differences that when you look at the details, to code is not a bit alike

How should I handle this situation?

Is having core logic composed entirely of callback calls a good solution?

Or should I rather duplicate the code and drop the complexity of callback-based code?

答: Have you considered using a Strategy pattern? You would have one View class that contains the common code & routines called by several views. Children of the View class would contain the code specific to those instances. They would all use the common interface you created for the View, and thus the differences would be encapsulated & coherent.</p>

Title: Illusory code duplication


答:
Ultimately you have to make a judgment call about whether to combine similar code to eliminate duplication.

There seems to be an unfortunate tendency to take principles like "Don't repeat yourself" as rules that must be followed by rote at all times.  In fact, these are not universal rules but guidelines that should help you think about and develop good design.

As everything in life, you must consider the benefits versus the costs.  How much duplicated code will be removed?  How many times is the code repeated?  How much effort will it be to write a more generic design?  How much are you likely to develop the code in the future?  And so on.

Without knowing your specific code, this is unclear.  Perhaps there is a more elegant way to remove duplication (such as that suggested by LindaJeanne).  Or, perhaps there simply isn't enough true repetition to warrant abstraction.

Insufficient attention to design is a pitfall, but also beware over-design.

Title: Illusory code duplication

Body:
The usual instinct is to remove any code duplication that you see in the code. However, I found myself in a situation where the duplication is illusory.

To describe the situation in more details: I am developing a web application, and most views are basically the same - they display a list of items which the user can scroll and choose from, a second list that contains selected items, and a "Save" button to save the new list.

It seemed to me that the problem is easy. However, each and every view has its own quirks - sometimes you need to recalculate something, sometimes you must store some additional data etc. These, I solved by inserting callback hooks in the main logic code.

There are so many minute differences between the views that it is becoming less and less maintainable, because I need to provide callbacks for basically all functionality, and the main logic starts to look like a huge sequence of callback invocations. In the end I am not saving any time or code, because every view has its own code that is executed - all in callbacks.

The problems are:

the differences are so minute that the code looks almost exactly alike in all views,

there are so many differences that when you look at the details, to code is not a bit alike

How should I handle this situation?

Is having core logic composed entirely of callback calls a good solution?

Or should I rather duplicate the code and drop the complexity of callback-based code?


问:
Tournament bracket method to put distance between teammates
I am using a proper binary tree to simulate a tournament bracket. It's preferred any competitors in the bracket that are teammates don't meet each other until the later rounds.  What is an efficient method in which I can ensure that teammates in the bracket have as much distance as possible from each other?  Are there any other data structures besides a tree that would be better for this purpose?

EDIT: There can be more than 2 teams represented in a bracket and there is no requirement to have an equal number of people from each team in a bracket.  I intend to use this for individual sports where a person still has an affiliation with a team and we want to delay teammates facing each other until as late as possible.

答:
Start at the root node (the final match) and the entire list of players.

Partition the list into equal sized two lists so that people from the same team end up in different lists. You can do this by looping through the teams and put half of the players from that team into each of the two partitions.

Recurse down the left subtree with the first list and the right subtree with the second list and do the same thing again in each subtree.

This will ensure that players from the same team are evenly distributed. If there are only two players from one team you are even guaranteed that they cannot meet each other until the final because they were immediately split into different subtrees.

You can make the partition function used in step 2 generic. Send it in as a function pointer and you can easily extend it to take into account things such as rank.


问:
good books to get deep into PHP
I am a PHP developer with ~3 years experience.  I want to get deeper into PHP and really understand more low level constructs/functionality.  I have mainly done frontend web dev and a little php cron jobs.  I want to learn more about stream contexts, closures, process forking, etc.

The book I've found that seems closest to this is  Expert PHP and MySQL (Wrox).  I also found Pro PHP.  I know there has to be more out there but I can't seem to find anything.

Suggestions?

答:
I kind of agree that learning php is usually not learned by books. But, there are many people who learn better by reading a book for some reasons (me included). I believe that the market is not mature enough. I would suggest something like this:

Head first labs, php book (I have not read it but everything from the head first series is great)

and honestly difficult on thinking something else...

Title: good books to get deep into PHP


答:
Remember that DRY is about knowledge. It doesn't matter whether two pieces of code look similar, identical, or totally different, what matters is if the same piece of knowledge about your system can be found in both of them.

A piece of knowledge might be a fact ("the maximum allowed deviation from the intended value is 0.1%") or it might be some aspect of your process ("this queue never contains more than three items"). It's essentially any single piece of information encoded in your source code.

So when you're deciding whether something is duplication that should be removed, ask whether it's duplication of knowledge. If not, it's probably incidental duplication, and extracting it to some common place will cause problems when you later want to create a similar component where that apparently duplicated part is different.

Title: Illusory code duplication


问:
What is the best way to horizontally scale .Net back-end applications?
Given a workload with many long running CPU/IO intensive operations (e.g. producing multi-GB text files from database reads and business rules), what is the best way to balance .net application load across a group of Windows Server 2012 R2 VMs?

Ideally, the approach would allow for adding/removing/patching nodes as needed. It's pretty much a 24/7 operation with little opportunity for maintenance windows.

Background

We are in the process of migrated millions of lines of COBOL code from a IBM mainframe to C#. The current workload is batch centered and there are lots of jobs that fire up at a scheduled time to perform units of work of various sizes.

Wherever possible, we'll look to make the converted processes more real-time, event-driven, etc... However, because of dependence on existing inputs/ouputs to/from many upstream and downstream partners and a desire to get from one platform to the other in the shortest time possible with minimal disruption, we're going to have constraints that prevent us going with a completely greenfield approach.

Due to the large volumes of constantly changing data involved and the interconnectedness of that data with other legacy systems, moving to a cloud-based infrastructure is probably not feasible.

Approaches we're considering

JMS queues - We have an enterprise class JMS compliant ESB and we could queue the work, having consumers on each VM that could pull work based on resource availability.

Task coordinator - We've considered creating a custom workload manager that would monitor servers and decide where to send work. Something along these lines.

答:
Here is an excerpt from a related question, specifically about scaling.

Scaling across machines can be done in various ways. Likely what you will want is partitioning. The easiest way is by hashing on some request value to decide which server to send to. For instance, if your customer ID is an integer (or can be consistently reduced to one... e.g. with GetHashCode) and you have 3 machines processing tasks, you can use a simple modulus to decide which customer should go to which machine. machineNumber = customerId % 3. CustomerId 1,4,7, etc will always go to machine 1. However, if Machine 1 goes down, 1/3 of the customer requests will not get processed until it comes back up. Since these are long running imports anyway, that's likely not a big deal. The load will also not be distributed evenly, since there are usually some customers who are heavier users. Again, probably not a huge deal. Measure to make sure.

Another way that is resilient to failure is to use a distributed directory. It keeps track of which node currently owns which customer. Project Orleans uses a mechanism like this. It allows for nodes to fail and customers to be transitioned to another node. Before allocating a new customer on a node, you can also query the node to see which is the least loaded. However, I'm not aware of a pre-built component for this purpose, and building it yourself is perilous to your time.

Since you mentioned queues, you might look at a feature called Competing Consumers which is available in various queue systems. In that case, you setup multiple machines or VMs (nodes) to service the queue. Whenever a new message comes through, the first node to answer gets the message and is expected to process it.

The Issues and Considerations section of the competing consumers link has some excellent points regarding such a queue/workload system.


答:
You start out using A* with intersections as nodes.  GPS units in the 90s had enough memory and processing power to do that.  You don't have to store the distance from every intersection to every other intersection.  Just to the next intersection over.

A* uses heuristics to avoid searching possibilities that are unlikely to be on the shortest path.  If you're driving from New York to LA, it's not going to search paths that go through Florida.  You'd be surprised how efficiently it works on real-world data, even just using crow-flies distance as the heuristic.

Google has made many proprietary tweaks to improve its heuristics to favor interstates and major thoroughfares, take traffic into account, not take weird detours through side streets, etc.  They probably also do a hierarchical search for really long trips, using different heuristics for local and interstate travel, basically using one search to get onto the interstate, another to get to your destination city using a database with only major intersections, and then a local search to get to your hotel, the same way a human would plan a trip.

For individual addresses, you interpolate.  200 E. Main is at the intersection of 2nd and Main.  300 E. Main is at the intersection of 3rd and Main.  So you know 250 E. Main is halfway between.  You don't have to store every individual household.


问:
Arguments againts checking-in binary files into SCMs
I work for a company that primarily builds Java applications and I'm trying to convince everybody to stop checking-in binary files (dependencies and final products) to SCM.

They know it is a bad practice but they think that "it works" and it is not really a problem even when many people know about Maven and other tools for building besides Ant. Both PMs and programmers (around 50 people) are ready to listen to any argument against and even acknowledge that it is a waste of backup space but I want to be really convincing because the habit change would involve a lot of effort. What arguments do you use to support a change?

Edit: Okay, it makes sense to make a distinction between files that almost do not change, like dependencies, and generated files. Even so, I'm interested in reasons against the latter.

答: Seems redundant to include both source and object files (source files are obviously required). In addition to just being unnecessary, the object files can take-up a lot of space. If your firm is using a distributed SCM (Git, Hg, Bzr) then those binary files must be copied and stored among all the developers. </p>


问:
What is the difference between "kk" and "HH"+1 in ISO-8601?
In the ISO-8601 there are multiple hour formats, one of them is "kk" for hours 1-24.

What is the purpose of this? Are there countries that offset their time? Is it for military usages?

The wikipedia article didn't clarify the exact nature between HH and kk. The main source of my concern is the behaviour of the formats in SimpleDataFormatter.

Edit:
The direct part from the SimpleDateFormat that I'm referring to is this:

H   Hour in day (0-23)  Number  0

k   Hour in day (1-24)  Number  24

In usage...

```<code>HH:mm:ss  // 00:00:00
kk:mm:ss  // 01:00:00
</code>```

答:
Direct answer to your question, there is no difference. The point is you do not need to do the +1 computation by using kk. My source can be found at: http://www-01.ibm.com/support/knowledgecenter/SSKM8N_8.0.0/com.ibm.etools.mft.doc/ak05616_.htm?lang=pt

Here you find this description:

HH  hour of day in 24 hour form (00-23)
kk  hour of day in 24 hour form (01-24)

Now, regarding HH+1 = kk. Example: HH: 00 in kk is 01. You can do this for each of the values.

As for the usage, it is for i18n purposes or different usages as you already mentioned. In different parts of world, different notations are used. But normally, you would only use kk in situations in which you have business hours which goes beyond or after 24 hours. For example, TV stations.


问:
Understanding binary numbers in terms of real world objects
When I represent a number in the decimal system, I have an intuitive knowledge of what it amounts to. For example take the number '10': I understand that it means 10 apples or 10 people... i.e I can count in the real world.

But as soon as the number is converted to any other system, this understanding no longer applies. For example 10 when converted to binary will be 1010...now what does this represent? Is there a way to understand this number 1010 in terms of counting objects in the real world?

答: Basically, the decimal system is based on the powers of 10 (10⁰, 10¹, 10²...), whilst the binary number system is based off of the powers of two (Place values count up by two, 2⁰, 2¹, 2²...). So here's 101 converted from binary to decimal. [(1x2³)+(0x2²)+(1x2¹)]÷2 which equals to 5. Do you notice the pattern (No, not illuminati). The exponents count down from how many numbers the binary term is, while 0 represents.. well.. a zero in the binary term, when a 1 represents a 1. 1x2 is a one in the term, and 0x2 is a zero.</p>


问:
What is the difference between a function and a lambda?
I'm a little bit confused about 'function' and 'lambda'.  I've seen some examples showing that the scheme keyword lambda works very similarly to the JavaScript keyword function, but I really don't know how they are related.

I'm told that 'function' and 'method' can be used interchangeably when speaking about objects in .net.  I'm wondering if 'lambda' and 'function' similarly mean the same thing.  I wonder if 'lambda' has some esoteric meaning, seeing that the Greek letter lambda (λ) appears in so many avatars on this site.  To make things even more confusing, in .net, the functional parts of C# refer to function expressions passed to another function as 'lambda expressions', so the word really seems to be all over the place.

I'm also vaguely familiar with the term 'lambda calculus'.

What is the difference between a function and a lambda?

答:
TL;DR As others pointed out: the lambda notation is just a way to define functions without being forced to give them a name.

Long version

I would like to elaborate a bit on this topic because I find it very interesting. Disclaimer: I have taken my course on lambda calculus a long time ago. If someone with better knowledge finds any inaccuracies in my answer, feel free to help me improve it.

Let's start with expressions, e.g. 1 + 2 and x + 2. Literals such as 1 and 2 are called constants because they are bound to specific fixed values.

An identifier such as x is called variable and in order to evaluate it you need to bind it to some value first. So, basically you cannot evaluate x + 1 as long as you do not know what x is.

The lambda notation provides a schema for binding specific input values to variables. A lambda expression can be formed by adding λx . in front of an existing expression, e.g. λx . x + 1. Variable x is said to be free in x + 1 and bound in λx . x + 1

How does this help in evaluating expressions? If you feed a value to the lambda expression, like so

```<code>(λx . x + 1) 2
</code>```

then you can evaluate the whole expression by replacing (binding) all occurrences of the variable x with the value 2:

```<code>(λx . x + 1) 2
      2 + 1
      3
</code>```

So, the lambda notation provides a general mechanism for binding things to variables that appear in an expression / program block. Depending on the context, this creates sightly different concepts in programming languages:

In a purely functional language like Haskell, lambda expressions represent functions in the mathematical sense: an input value is injected into the body of the lambda and an output value is produced.

In many languages (e.g. JavaScript, Python, Scheme) evaluating the body of a lambda expression can have side-effects. In this case one can use the term procedure to mark the difference wrt pure functions.

Apart from the differences, the lambda notation is about defining formal parameters and binding them to actual parameters.

The next step, is to give a function / procedure a name.
In several languages, functions are values like any other, so you can give a function a name as follows:

```<code>(define f (lambda (x) (+ x 1)))      ;; Scheme

f = \x -> x + 1                      -- Haskell

val f: (Int => Int) = x => x + 1     // Scala

var f = function(x) { return x + 1 } // JavaScript

f = lambda x: x + 1                  # Python
</code>```

As Eli Barzilay pointed out, these definition just bind the name f to a value, which happens to be a function. So in this respect, functions, numbers, strings, characters are all values that can be bound to names in the same way:

```<code>(define n 42)   ;; Scheme

n = 42          -- Haskell

val n: Int = 42 // Scala

var n = 42      // JavaScript

n = 42          # Python
</code>```

In these languages you can also bind a function to a name using the more familiar (but equivalent) notation:

```<code>(define (f x) (+ x 1))         ;; Scheme

f x = x + 1                    -- Haskell

def f(x: Int): Int = x + 1     // Scala

function f(x) { return x + 1 } // JavaScript

def f(x): return x + 1         # Python
</code>```

Some languages, e.g. C, only support the latter notation for defining (named) functions.

Closures

Some final observations regarding closures. Consider the expression x + y. This contains two free variables. If you bind x using the lambda notation you get:

```<code>\x -> x + y
</code>```

This is not (yet) a function because it still contains a free variable y. You could make a function out of it by binding y as well:

```<code>\x -> \y -> x + y
</code>```

or

```<code>\x y -> x + y
</code>```

which is just the same as the + function.

But you can bind, say, y in another way (*):

```<code>incrementBy y = \x -> x + y
</code>```

The result of applying function incrementBy to a number is a closure, i.e. a function / procedure whose body contains a free variable (e.g. y) that has been bound to a value from the environment in which the closure was defined.

So incrementBy 5 is the function (closure) that increments numbers by 5.

NOTE (*)

I am cheating a bit here:

```<code>incrementBy y = \x -> x + y
</code>```

is equivalent to

```<code>incrementBy = \y -> \x -> x + y
</code>```

so the binding mechanism is the same. Intuitively, I think of a closure as representing a chunk of a more complex lambda expression. When this representation is created, some of the bindings of the mother expression have already been set and the closure uses them later when it gets evaluated / invoked.

Body:
TL;DR As others pointed out: the lambda notation is just a way to define functions without being forced to give them a name.

Long version

I would like to elaborate a bit on this topic because I find it very interesting. Disclaimer: I have taken my course on lambda calculus a long time ago. If someone with better knowledge finds any inaccuracies in my answer, feel free to help me improve it.

Let's start with expressions, e.g. 1 + 2 and x + 2. Literals such as 1 and 2 are called constants because they are bound to specific fixed values.

An identifier such as x is called variable and in order to evaluate it you need to bind it to some value first. So, basically you cannot evaluate x + 1 as long as you do not know what x is.

The lambda notation provides a schema for binding specific input values to variables. A lambda expression can be formed by adding λx . in front of an existing expression, e.g. λx . x + 1. Variable x is said to be free in x + 1 and bound in λx . x + 1

How does this help in evaluating expressions? If you feed a value to the lambda expression, like so

(λx . x + 1) 2

then you can evaluate the whole expression by replacing (binding) all occurrences of the variable x with the value 2:

(λx . x + 1) 2
      2 + 1
      3

So, the lambda notation provides a general mechanism for binding things to variables that appear in an expression / program block. Depending on the context, this creates sightly different concepts in programming languages:

In a purely functional language like Haskell, lambda expressions represent functions in the mathematical sense: an input value is injected into the body of the lambda and an output value is produced.

In many languages (e.g. JavaScript, Python, Scheme) evaluating the body of a lambda expression can have side-effects. In this case one can use the term procedure to mark the difference wrt pure functions.

Apart from the differences, the lambda notation is about defining formal parameters and binding them to actual parameters.

The next step, is to give a function / procedure a name.
In several languages, functions are values like any other, so you can give a function a name as follows:

(define f (lambda (x) (+ x 1)))      ;; Scheme

f = \x -> x + 1                      -- Haskell

val f: (Int => Int) = x => x + 1     // Scala

var f = function(x) { return x + 1 } // JavaScript

f = lambda x: x + 1                  # Python

As Eli Barzilay pointed out, these definition just bind the name f to a value, which happens to be a function. So in this respect, functions, numbers, strings, characters are all values that can be bound to names in the same way:

(define n 42)   ;; Scheme

n = 42          -- Haskell

val n: Int = 42 // Scala

var n = 42      // JavaScript

n = 42          # Python

In these languages you can also bind a function to a name using the more familiar (but equivalent) notation:

(define (f x) (+ x 1))         ;; Scheme

f x = x + 1                    -- Haskell

def f(x: Int): Int = x + 1     // Scala

function f(x) { return x + 1 } // JavaScript

def f(x): return x + 1         # Python

Some languages, e.g. C, only support the latter notation for defining (named) functions.

Closures

Some final observations regarding closures. Consider the expression x + y. This contains two free variables. If you bind x using the lambda notation you get:

\x -> x + y

This is not (yet) a function because it still contains a free variable y. You could make a function out of it by binding y as well:

\x -> \y -> x + y

or

\x y -> x + y

which is just the same as the + function.

But you can bind, say, y in another way (*):

incrementBy y = \x -> x + y

The result of applying function incrementBy to a number is a closure, i.e. a function / procedure whose body contains a free variable (e.g. y) that has been bound to a value from the environment in which the closure was defined.

So incrementBy 5 is the function (closure) that increments numbers by 5.

NOTE (*)

I am cheating a bit here:

incrementBy y = \x -> x + y

is equivalent to

incrementBy = \y -> \x -> x + y

so the binding mechanism is the same. Intuitively, I think of a closure as representing a chunk of a more complex lambda expression. When this representation is created, some of the bindings of the mother expression have already been set and the closure uses them later when it gets evaluated / invoked.


问:
Does Git subtree count as distribution for copyleft licenses?
If I include, say, a GPLv3 repository in in my repository using git subtree, would that count as distribution? Am I now required to license my repository as GPLv3 as well?

I don't intend to modify or interact with the GPL code, but I would like to have it in my repository for convenience and as a reference.

答:
No, it does not. Distribution is when you provide the code to someone else. Simply moving code around within your own computer does not constitute distribution.

When you downloaded this code (or cloned the public git repo), you are not the one distributing; whoever put that code up where you can download it is the distributor. As long as you stick to personal use, you are not distributing it and none of the GPL restrictions apply.


答:
If that repository is public, yes, you obviously published it.

Otherwise obviously not.

And if you publish something, you better have the right to do so.

While you can have gpl and non-gpl code side-by-side in the same public repository, if one is the derived work of the other, remember that you must have the license to publish a derived work.

Title: Does Git subtree count as distribution for copyleft licenses?

Body:
If I include, say, a GPLv3 repository in in my repository using git subtree, would that count as distribution? Am I now required to license my repository as GPLv3 as well?

I don't intend to modify or interact with the GPL code, but I would like to have it in my repository for convenience and as a reference.


问:
Should Someone without Programming Knowledge Phone Screen?
I've been given most of the hiring responsibilities and will be conducting the in-person interviews. I'm also going through the resumes for worthy candidates. The plan is to have the HR department do the phone screening though. They'll ask the normal HR questions and then any questions I give them and then report back the answers.

The idea is to not have me (or my project manager) waste valuable time making tens of calls. What this would mean, though, is that HR would be asking the questions. They don't know anything about programming, and really nothing about what we do from a technical aspect.

When researching phone screen questions, most assume the screener is technical, such as Steve Yegge's phone screen questions. I'm just wondering if anyone has any experience with this and has any advantages/disadvantages to this.

答:
No, I don't think this is a particularly good idea.

The HR interviewer can't ask follow up questions to see if "near miss" answers are good or not.

The HR interviewer can't answer the candidate's technical questions (remember, interviews go both ways).

It presents the company in a poor light, not valuing candidates' time.

That process is more likely to let through shoddy candidates, and the wasted time interviewing them in person will kill any gains you might have had by having cheaper HR people do it.


答:
What's the potential for change? For example, our application has 8 different business areas with a potential of 4 or more user types for each area.  Views are customized based on the user type and the area.

Initially, this was done using the same view with a few checks here and there to determine if different things should show.  Over time, some of the business areas have decided to do drastically different things.  In the end, we basically migrated to one view (partial views, in the case of ASP.NET MVC) per piece of functionality per business area.  Not all business areas have the same functionality, but if one wants functionality that another has, that area gets its own view.  It's a lot less cumbersome for comprehension of the code, as well as for testability.  E.g., making a change for one area won't cause an unwanted change for another area.

As @dan1111 mentioned, it can come down to a judgment call.  In time, you may find whether it works or not.

Title: Illusory code duplication


问:
When are enums NOT a code smell?
Dilemma

I've been reading a lot of best practice books about object oriented practices, and almost every book I've read had a part where they say that enums are a code smell. I think they've missed the part where they explain when enums are valid.

As such, I am looking for guidelines and/or use-cases where enums are NOT a code smell and in fact a valid construct.

Sources:

"WARNING As a rule of thumb, enums are code smells and should be refactored
to polymorphic classes. [8]"
Seemann, Mark, Dependency Injection in .Net, 2011, p. 342

[8] Martin Fowler et al., Refactoring: Improving the Design of Existing Code (New York: Addison-Wesley, 1999), 82.

Context

The cause of my dilemma is a trading API. They give me a stream of Tick data by sending thru this method:

```<code>void TickPrice(TickType tickType, double value)
</code>```

where enum TickType { BuyPrice, BuyQuantity, LastPrice, LastQuantity, ... }

I've tried making a wrapper around this API because breaking changes is the way of life for this API. I wanted to keep track of the value of each last received tick type on my wrapper and I've done that by using a Dictionary of ticktypes:

```<code>Dictionary<TickType,double> LastValues
</code>```

To me, this seemed like a proper use of an enum if they are used as keys. But I am having second thoughts because I do have a place where I make a decision based on this collection and I can't think of a way how I could eliminate the switch statement, I could use a factory but that factory will still have a switch statement somewhere. It seemed to me that I'm just moving things around but it still smells.

It's easy to find the DON'Ts of enums, but the DOs, not that easy, and I'd appreciate it if people can share their expertise, the pros and cons.

Second thoughts

Some decisions and actions are based on these TickType and I can't seem to think of a way to eliminate enum/switch statements. The cleanest solution I can think of is using a factory and return an implementation based on TickType. Even then I will still have a switch statement that returns an implementation of an interface.

Listed below is one of the sample classes where I'm having doubts that I might be using an enum wrong:

```<code>public class ExecutionSimulator
{
  Dictionary<TickType, double> LastReceived;
  void ProcessTick(TickType tickType, double value)
  {
    //Store Last Received TickType value
    LastReceived[tickType] = value;

    //Perform Order matching only on specific TickTypes
    switch(tickType)
    {
      case BidPrice:
      case BidSize:
        MatchSellOrders();
        break;
      case AskPrice:
      case AskSize:
        MatchBuyOrders();
        break;
    }
  }
}
</code>```

答:
Firstly, a code-smell doesn't mean that something is wrong. It means that something might be wrong. enum smells because its frequently abused, but that doesn't mean that you have to avoid them. Just you find yourself typing enum, stop and check for better solutions.

The particular case that happens most often is when the different enum's correspond to different types with different behaviors but the same interface. For example, talking to different backends, rendering different pages, etc. These are much more naturally implemented using polymorphic classes.

In your case, the TickType doesn't correspond to different behaviors. They are different types of events or different properties of the current state. So I think this is ideal place for an enum.

Title: When are enums NOT a code smell?


答:
what if you went with a more complex type:

```<code>    abstract class TickType
    {
      public abstract string Name {get;}
      public abstract double TickValue {get;}
    }

    class BuyPrice : TickType
    {
      public override string Name { get { return "Buy Price"; } }
      public override double TickValue { get { return 2.35d; } }
    }

    class BuyQuantity : TickType
    {
      public override string Name { get { return "Buy Quantity"; } }
      public override double TickValue { get { return 4.55d; } }
    }
//etcetera
</code>```

then you could load your types from reflection or build it yourself but the primary thing going here is that you are holding to Open Close Principle of SOLID

Title: When are enums NOT a code smell?

Body:
Dilemma

I've been reading a lot of best practice books about object oriented practices, and almost every book I've read had a part where they say that enums are a code smell. I think they've missed the part where they explain when enums are valid.

As such, I am looking for guidelines and/or use-cases where enums are NOT a code smell and in fact a valid construct.

Sources:

"WARNING As a rule of thumb, enums are code smells and should be refactored
to polymorphic classes. [8]"
Seemann, Mark, Dependency Injection in .Net, 2011, p. 342

[8] Martin Fowler et al., Refactoring: Improving the Design of Existing Code (New York: Addison-Wesley, 1999), 82.

Context

The cause of my dilemma is a trading API. They give me a stream of Tick data by sending thru this method:

```<code>void TickPrice(TickType tickType, double value)
</code>```

where enum TickType { BuyPrice, BuyQuantity, LastPrice, LastQuantity, ... }

I've tried making a wrapper around this API because breaking changes is the way of life for this API. I wanted to keep track of the value of each last received tick type on my wrapper and I've done that by using a Dictionary of ticktypes:

```<code>Dictionary<TickType,double> LastValues
</code>```

To me, this seemed like a proper use of an enum if they are used as keys. But I am having second thoughts because I do have a place where I make a decision based on this collection and I can't think of a way how I could eliminate the switch statement, I could use a factory but that factory will still have a switch statement somewhere. It seemed to me that I'm just moving things around but it still smells.

It's easy to find the DON'Ts of enums, but the DOs, not that easy, and I'd appreciate it if people can share their expertise, the pros and cons.

Second thoughts

Some decisions and actions are based on these TickType and I can't seem to think of a way to eliminate enum/switch statements. The cleanest solution I can think of is using a factory and return an implementation based on TickType. Even then I will still have a switch statement that returns an implementation of an interface.

Listed below is one of the sample classes where I'm having doubts that I might be using an enum wrong:

```<code>public class ExecutionSimulator
{
  Dictionary<TickType, double> LastReceived;
  void ProcessTick(TickType tickType, double value)
  {
    //Store Last Received TickType value
    LastReceived[tickType] = value;

    //Perform Order matching only on specific TickTypes
    switch(tickType)
    {
      case BidPrice:
      case BidSize:
        MatchSellOrders();
        break;
      case AskPrice:
      case AskSize:
        MatchBuyOrders();
        break;
    }
  }
}
</code>```

Body:
what if you went with a more complex type:

    abstract class TickType
    {
      public abstract string Name {get;}
      public abstract double TickValue {get;}
    }

    class BuyPrice : TickType
    {
      public override string Name { get { return "Buy Price"; } }
      public override double TickValue { get { return 2.35d; } }
    }

    class BuyQuantity : TickType
    {
      public override string Name { get { return "Buy Quantity"; } }
      public override double TickValue { get { return 4.55d; } }
    }
//etcetera

then you could load your types from reflection or build it yourself but the primary thing going here is that you are holding to Open Close Principle of SOLID


问:
Databaseless ASP.NET MVC 5 on top of an external REST API
Where you would envision an out-of the-box ASP.NET MVC 5 web application on top of an MSSQL database, I have now been placed in a situation where I'm supposed to use custom external token endpoints and use bearer tokens to make authenticated API calls.

I'm, de facto, attempting to create a(n as) databaseless (as possible) ASP.NET MVC 5 web application.

These phases are, perhaps not by the book, but successful:

custom OWIN middleware that uses these token and auth endpoints

an in-memory identity that is constructed, based on what I get back from the user endpoint and that contains, among other things, the bearer token and roles as external claims, all of which are brought to the front as true Identity Claims.

The ability to make authenticated API calls to this external RESTful API and GET/POST data using said bearer token (using RestSharp).

Now I find myself at something of a crossroads:

I'll need to figure out how to implement Identity Roles and make it work for me to allow / shield some content and functionality based on the roles I get from the endpoint response. These are pretty much hierarchical (admin, keyuser, user).

How will I need to proceed as I have no O/RM layer? I would imagine I would simply continue to create my own domain models and viewmodels as needed?

I'm trying to figure out how to do all of this as "dbless" as possible, possibly avoiding altogether the infamous tables normally generated by ASP.NET for its Identity dirty work. Or will I unavoidably run into the need to persist at least some data myself?

If necessary, I might be able to convince the backend guy to grant my wish and store (POST) my arbitrary Claims (e.g. user adds his phone nr).

I've been working on my own ApplicationUser, UserStore, RoleStore, UserManager etc. classes. Is this the way to go? Will I even need them in this case?

At this point I'm pretty lost as to how I should proceed. Does anyone have any experience "shelling" an MVC 5 app on top of an external RESTful API without an ApplicationDbContext and what pitfalls should I be mindful of?

As you can imagine, I'm having a crisis of faith here. I'm "winging" a lot of unknowns and am glad I've gotten this far, but I'm wondering if, at all, it can be done completely, as I'm also learning Identity "on the go". It's not a great scenario, but it needs to be done within a limited time frame.

Information about what I'm attempting to endeavor is non-existent...

Any insight would thus be awesomely appreciated.

答:
The fact that the data store lies behind a RESTful API is irrelevant if your have an architecture that doesn't care about how the data is persisted. It only needs to know about an interface that promises that persistence. The Repository pattern excels at creating this abstraction.

Keep in mind that if you keep your interfaces small, it would be easy to even have multiple different persistence mechanisms if you later determine that you do need to keep some information in a "local" db. Some repositories could be implemented by calling the web service. Others could be implemented by reaching into a database, or even an XML file. Again, the point being that your controller shouldn't care about how the data is actually persisted. It just calls into an IFooRepository to get what it needs.


问:
Career guidance books for programmers
I am currently reading the recently published Being Geek by Michael "Rands" Lopp and I can't get enough of it.

Is there any other career guidance books aimed directly or indirectly at programmers that are worth reading?

答:
Code complete

The Pragmatic Programmer

Title: Career guidance books for programmers

Body:
Code complete

The Pragmatic Programmer


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I am Indonesian currently living in Kuwait.

In the first year of my computer science studies, I used Bahasa for almost everything except int main(). But I noticed that some of us code in english already.

All of our programming books are in english. I find it very difficult to find words in Bahasa that are equivalent for programming terms. So instead of using half-english-half-bahasa language, I (and most of my friends) started to make every possible effort to code in english.

In my first working experience in Jakarta, Indonesia, I was obliged to code in english.


答:
INAL, but I don't think it's even meaningful to talk about licensing a repository - at least not in the same way we talk about licensing code. A repository is just a container for managing code. Just like if you burn a GPL software on a CD, it does not make the entire CD GPL, forbidding you from burning proprietary software on it(though other things may forbid you from doing so). The same way with repositories - even if you put some GPL stuff in it, it doesn't force you to make the entire repository and everything in it GPL.

The only thing affected by the copyleft is other code - the actual application inside your repository - and how it is affected is determined by how it interacts with the GPL software.


答:
Enums are intended for use cases when you have literally enumerated every possible value a variable could take.  Ever.  Think use cases like days of the week or months of the year or config values of a hardware register.  Things that are both highly stable and representable by a simple value.

Keep in mind, if you're making an anti-corruption layer, you can't avoid having a switch statement somewhere, because of the design you're wrapping, but if you do it right you can limit it to that one place and use polymorphism elsewhere.

Title: When are enums NOT a code smell?


问:
Gödel's Incompleteness Theorem and Algorithms
According to Gödel's incompleteness theorem, not every problem can be solved using algorithms. How do we know if a problem can be solved using algorithm?

How do we know that NP problems are algorithmically solvable?

答:
According to Godel's incompleteness theorem, not every problem can be solved using algorithms.

That is incorrect, according to my understanding.  Godel's incompleteness theorems are not about algorithms.  They are actually about whether all mathematical statements can be proved or disproved.

(Godel's first theorem says that there is no algorithm that will enumerate all possible true mathematical statements ... but that is saying something very different to what you asserted.)

(There is a subtle relationship between decidability and computability, but once again that is not what Godel's theorems are saying ... directly.  Plainly, Godel's theorems are not directly about algorithms.)

How do we know if a problem can be solved using algorithm?

I don't know if there is an answer to that, either in the sense of all problems being solvable, or any specific problem being solvable.

(But it is also unclear what you mean by "problem" and "solve".  For example, if you equate "problem" with a mathematical theorem, and "solving" with finding a proof / disproof, then clearly Godel's theorem says that there is a class of problems that cannot be solved by any means ... including algorithmically ... because no solution exists.)

How do we know that NP problems are algorithmically solvable?

Again ... there is uncertainty in what you mean by "solveable".

@delnam comments thus:

"In an fixed NP problem, the time to check the solution is bounded above by some fixed polynomial T. Therefore the size of any solution to an instance of this NP problem is also bounded above by a fixed polynomial S. Therefore, for any given input of size n, the space of possible solutions is always finite (roughly 2^S(n) solutions) and can be searched exhaustively.   Therefore all NP problems are decidable."

If you exclude the impractical "exhaustive search" algorithm, then I don't think there is a general way to know ... apart from hard work, either to find an existing (better) algorithm (for the problem or an equivalent one), or develop one de novo.


问:
Fully Specifying #includes
I'm very fastidious about code. When I remove functionality from a file I remove the cooresponding #includes. I've hit several errors where I would remove a #include from a header, and another file that #included the header I was editing depended on that #include.

Depending on the error given by the compiler it can waste a fair amount of my time determining which dependency I actually removed.

I've been told by a coworker, that the problem is that I'm cleaning up #includes when I should just leave them alone even if nothing in their contents is used. He claims that if we fully specified our includes top level files would be ridiculously bloated.

I'd like a convincing argument to sway him to fully specify the necessary #includes. Or perhaps I'm in the wrong in which case I'd like to hear an argument against me cleaning up #includes. Is there an argument convincing enough to sway one of us?

答: You are following consensus expert practice in C++. A source file should #include the header files for all its direct dependencies. You are getting compile errors, so what's the problem? First you clean up a header file, then you go fix the broken .cpp files. Then you commit the code.</p>

Title: Fully Specifying #includes


答:
There are (at least) four options available:

1. Keep unnecessary #includes in the header files as the OP's colleague insists on

This has the following effects:

(positive) You do not break software that is currently working.

(positive) You do not have to do much work now.

(negative) Dependencies remain hidden: which part of the program depends on what other parts remain a mystery.

Hidden/implicit dependencies might cause:

Keeping dependencies on parts that are no longer used.  Which might cause you to have to work to keeps these parts integrated; e.g. "we have to update {unknowingly obsolete part} to the new {foo thingy}", or "we have to implement {very useful feature} in an awkward way since we cannot make use of the nice features in {foo thingy v2.0}  since {unknowingly obsolete part} has to use {foo thingy v1.7}.

Difficulties to understand the software and its structure: especially for new developers but seasoned team member will also spend more time finding were something went wrong.

(possibly positive) In some specific situations keeping the #includes as is may preserve the layout of the compiled binaries which allows parts of them to be patched.  But preserving the ABI requires you to be very careful with your changes and how you implement them.  I would be surprised if you team/company relies on binary compatibility between minor version of your software; to my assumption most software updates are done by replacing entire files or even collections of files (programmers.SE community, please correct me if my assumptions are wrong).

2. As the OP, Jonathan Mee, does and as Kevin Cline suggests:

when a file no longer depends on some headers, remove the #included headers one by one;

compile the code and see which .cpp files break;

#include the removed header in the .cpp files that break.

Note, always keep the header that defines the class implemented in the .cpp as the header included first (e.g. the file myClass.cpp should have #include "myClass.h" as its first non-comment line).  When adding an#includefor the removed header to a .cpp file does fix that file's compilation errors, a header depends on the removed head and you should add the#include` there.

This has the following effects:

You spend some effort now compiling and tracing errors caused by missing includes.

(negative) Code file may become bloated with a large list of includes, as the OP's colleague argues.

(negative) Tomorrow you will run into an other instance of this same problem.

Code has a little fewer implicit dependencies, but the overall difficulty/ease of understanding the code remains the same.

3. Create headers with #includes commonly used together

For example, when many .cpp or .h files #include "foo.h", #include "bar.h", and #include "baz.h, instead of adding these three lines to every .cpp file that uses the headers, create a header that only #includes these three headers (and does not define anything else) and #include that header.

(positive) You avoid your code files to become as bloated as your colleague fears; perhaps saying him to your (and the experts's side).

(negative) Both in your current situation with no longer directly used #includes still in header files and in this proposed «solution» not being bloated is appearance in reality it still is bloated and you're still suffering most negative effects in both this approach and that of your current situation.*

(positive) You can evolve the common headers as you are cleaning up unused functionality; so there is not that much more work to do as in approach #2.

(positive) As you «evolve» the common header files an organisation into package might reveal itself.  This improves the ease of understanding the software and its organisation of dependencies.

4. Reorganise the software such no longer everything depends on other parts all over the system

The stale includes and the .cpp files becoming bloated when they #include the headers they require are signs of the software not organised as well as it could be.

(positive) Better organisation leads to systems that are easier to understand.

(positive) Better organisation leads to systems that are easier to change.

(negative) Reorganising the system into packages with restricted dependencies is much work; it might require rewriting many parts.

(positive) You can remove unused #includes and move them to where they are needed without the source files becoming bloated with #includes (this time for real and not just mere appearances).

(negative) Reorganising the system and rewriting parts might cause you to introduce bugs.

Title: Fully Specifying #includes

Body:
I'm very fastidious about code. When I remove functionality from a file I remove the cooresponding #includes. I've hit several errors where I would remove a #include from a header, and another file that #included the header I was editing depended on that #include.

Depending on the error given by the compiler it can waste a fair amount of my time determining which dependency I actually removed.

I've been told by a coworker, that the problem is that I'm cleaning up #includes when I should just leave them alone even if nothing in their contents is used. He claims that if we fully specified our includes top level files would be ridiculously bloated.

I'd like a convincing argument to sway him to fully specify the necessary #includes. Or perhaps I'm in the wrong in which case I'd like to hear an argument against me cleaning up #includes. Is there an argument convincing enough to sway one of us?


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

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

答:
Don't code today what you can't debug tomorrow

from this blog's title

LastEditorDisplayName: Roger Pate


答:
When transmitting data enums are no code smell

IMHO, when transmitting data using enums to indicate that a field can have a value from a restricted (seldom changing) set of values is good.

I consider it preferable to transmitting arbitrary strings or ints.  Strings may cause problems by variations in spelling and capitalisation.  Ints allow for transmitting out of range values and have little semantics (e.g. I receive 3 from your trading service, what does it mean? LastPrice? LastQuantity? Something else?

Transmitting objects and using class hierarchies is not always possible; for example wcf does not allow the receiving end to distinguish which class has been sent.

In my project the service uses a class hierarchy for effects of operations, just before transmitting via a DataContract the object from the class hierarchy is copied into a union-like object which contains an enum to indicate the type.
  The client receives the DataContract and creates an object of a class in a hierarchy using the enum value to switch and create an object of the correct type.

An other reason why one would not want to transmit objects of class is that the service may require completely different behaviour for a transmitted object (such as LastPrice) than the client.  In that case sending the class and its methods is undesired.

Are switch statements bad?

IMHO, a single switch-statement that calls different constructors depending on an enum is not a code smell. It is not necessarily better or worse than other methods, such as reflection base on a typename; this depends on the actual situation.

Having switches on an enum all over the place is a code smell, oop provides alternatives that are often better:

Use object of different classes of a hierarchy that have overridden methods; i.e. polymorphism.

Use the visitor pattern when the classes in the hierarchy seldom change and when the (many) operations should be loosely coupled to the classes in the hierarchy.

Title: When are enums NOT a code smell?


问:
What are the advantages of matrix multiplication over individual variables (graphics)?
I am learning OpenGL and the tutorials (1, 2) I'm reading teach me that to scale/rotate/translate an object you have to know matrix multiplication. Why? Instead of 3x3 matrix you can use 6 floats: scale_x, scale_y, sin_a, cos_a, mov_x and mov_y. They would result in...

Less GPU and CPU usage (matrix multiplication takes 9 multiplications and 6 additions while individual variables need 6 multiplications and 4 additions. Also, if you want to move object, instead of having to multiply whole matrix you get to only change values of two floats.

Less memory bandwidth (1/3 cut!)

Easier to manipulate (at least in C, no need for matrix manipulation functions)

Easier information extraction to get object rotation or offset or scale

The only disadvantages that I know of are:

You cannot change the order of transformations, most importantly, rotation around some point, not the origin of the coordinate plain. You can simulate it, though, by altering mov_x and mov_y accordingly.

More code. You could put them into an array though, but that would mean you would lose the ability to update them one by one and only could update them all or the beginning of array, not the middle or the end. I could be wrong on this, though.

Could someone tell me what am I missing?

Edit: added my shader below.

```<code>#version 330

layout (location = 0) in vec2 pos;
layout (location = 1) in vec3 clr_in;

uniform float osclx, oscly, osina, ocosa, omovx, omovy;
uniform float msclx, mscly, msina, mcosa, mmovx, mmovy;
float oldx, oldy, x, y;

out vec3 clr_out;

void main() {
    x = pos.x;
    y = pos.y;

    x = x * oscly;
    y = y * osclx;
    oldx = x;
    oldy = y;
    x = oldx * ocosa - oldy * osina;
    y = oldx * osina + oldy * ocosa;
    x = x + omovx;
    y = y + omovy;

    x = x * msclx;
    y = y * mscly;
    oldx = x;
    oldy = y;
    x = oldx * mcosa - oldy * msina;
    y = oldx * msina + oldy * mcosa;
    x = x + mmovx;
    y = y + mmovy;

    gl_Position = vec4(x, y, 0.0f, 1.0f);
    clr_out = clr_in; }
</code>```

答: While I think the upsides you provided can be true, there is one particular upside for matrices that I think matters a lot: almost all transforms that one wants to do in graphics - scaling, rotation, translation, etc. - can be represented as matrix multiplication. It's nice to have a common format - an interface, if you will. Additionally, compositions of operations can also be represented as a single matrix. So if you want to do a scaling, a rotation, a scaling, a translation, and a rotation - it's still just one matrix. That's a pretty big win. That's not to say the individual transform types may not be preserved "on the side" in your hierarchy of objects being rendered, etc. - being able to adjust the "mov_x" is indeed valuable - but the graphics pipeline tends to depend on matrices internally.</p>


答:
Storage space is cheap, and so that's not a very convincing argument for why you should or shouldn't check files in.

Instead, You can appeal to the purpose of SCM.  Each file that is tracked by SCM represents some need to manage the parallel, distributed changes your team is doing.  None of that is really apparent until two team members try to change the same file.  Resolving those changes is what SCM is really for, preventing accidental overwrite of another dev's work, and hopefully, automating the process of merging those changes.

Merging binary files is usually a real challenge, because there's no sane way for a generic merge tool to guess how a merged binary file should work.  It can't know enough about how the indexes or offset pointers in the file work unless specially designed to recognize that particular file type.

That means it's up to the dev to merge the binary file by hand, and then tell the SCM that the file has been so merged.  Since it's a dev doing it, the merge may not really cover all of the changes of both prior check-ins, and since the file is binary, there's no automated way to verify the merge.

For binary formats that really represent project sources, such as art assets, this is an unfortunate, but neccesary step.  However, build outputs aren't sources.  There's no need to merge them, because the sources can be merged and a resulting build output can be regenerated.  Tracking and managing these changes is 100% waste.  It wastes the SCM's resources, though not terribly much, but it also wastes developer time getting past the spurious merge failures.  Developer time is very expensive, and anything that puts it to waste is a cancer.

On the other hand, there is a particular case where the build outputs should be archived.  Any version of the project that has ever been shipped or deployed should probably be retained, indefinitely.   Having an exact, byte for byte copy of the actual build that a customer is having issues with can make supporting that customer much easier, since you will have the exact version he has.

That backup probably shouldn't be in the same repository as the source code, since they will generally follow different schedules and have basically different structures.

Title: Arguments againts checking-in binary files into SCMs

Body:
I work for a company that primarily builds Java applications and I'm trying to convince everybody to stop checking-in binary files (dependencies and final products) to SCM.

They know it is a bad practice but they think that "it works" and it is not really a problem even when many people know about Maven and other tools for building besides Ant. Both PMs and programmers (around 50 people) are ready to listen to any argument against and even acknowledge that it is a waste of backup space but I want to be really convincing because the habit change would involve a lot of effort. What arguments do you use to support a change?

Edit: Okay, it makes sense to make a distinction between files that almost do not change, like dependencies, and generated files. Even so, I'm interested in reasons against the latter.


问:
Coded UI test Automation Technique
How is coded UI testing technique more favorable than any other testing technique? What is the main advantage of using a coded UI test?</p>

答:
The following are pros of UI testing:

if you have no unit testing in place and no ability to introduce it (legacy code or external delivery), you can do testing

good for integration and/or system level tests

(up to a certain degree) mimick real user behavior/input

There are also many cons, mainly that they are more fragile, thus more difficult to maintain and create - I have found this to usually be true.

One more thing against them is that typically UI tests need a dedicated system (you need the UI and no other program running), unlike for unit tests where you could have 5 executing in parallel. This makes them impossible to run on a developer's machine before each check-in.

Then you have execution time, which makes it very hard to execute them on each check-in. In most scenarios UI tests are only executed nightly, weekly or even manually.

There are many variations of the testing pyramid. Most people say that there should be a lot more unit tests than UI tests, and for reasonably complex applications other kinds of testing as well.

Title: Coded UI test Automation Technique