问:
Comparison of route formats
I'm developing a new application and I'm trying to come up with a convention for defining routes. Ideally, I would like it to be simple, flexible, and reversible.

Here are some from popular frameworks:

Backbone

```<code>route                           matches
-----------------------------------------------------
help                            help
search/:query                   search/kiwis
search/:query/p:page            search/kiwis/p7
file/*path                      file/nested/folder/file.txt
docs/:section(/:subsection)     docs/faq, docs/faq/installing
</code>```

Django

Uses regexes, but comes with a complex regex reverser

```<code>route                                                           matches
-------------------------------------------------------------------------------------
^articles/2003/$                                                /articles/2003/
^articles/(\d{4})/(\d{2})/$                                     /articles/2005/03/
^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$     /articles/2003/03/03/
</code>```

Ruby on Rails

```<code>:controller/:action/:id/with_user/:user_id
books/*section/:title
</code>```

ASP.NET / MVC 5

```<code>{controller}/{action}/{id}           /Products/show/beverages
{resource}.axd/{*pathInfo}           /WebResource.axd?d=...
{productId:int}/{productTitle}       /5/asp-net-mvc
books/{isbn?}                        /books, /books/1430210079
</code>```

Django's is probably the most flexible, and it's already familiar to people that know regexes, but it's also the most difficult to read and reverse.

Backbone, RoR and ASP.NET all allow optional and wildcard/splat parts, with various syntaxes. MVC 5 has some options for restricting the parameters inline ala :int.

Where might these schemes fall short, and how could they be fixed?

答:
I've used ASP.NET MVC for years. Lately I've been doing research on Rails and Django to see if they have something more to offer. I've done reading the routing part of their documentation, but I haven't done any real apps yet, so I'm not an expert. I have no experience with Backbone, so I'll leave that out.

In short, Rails has the most powerful routing system of the three, Django has the weakest and ASP.NET MVC is somewhere between.

All have:

 - named routes

 - wildcards (in ASP.NET MVC only the last parameter)

 - extra data (pass some values that are not part of the route)

 - regex constraints

 - helpers to create urls

 - some kind of route prefix (namespace/area)

Ruby on Rails and ASP.NET MVC have:

 - generic routing  (one route, multiple controllers/actions)

 - default values

 - code constraints

Ruby on Rails has:

 - resource routing

 - powerful redirection

Example of regex constraint in Ruby on Rails (id has to be a number)

```<code>get ':controller/:id/:action', constraints: {id: /^\d+/}
</code>```

Example of code constraint in ASP.NET MVC (check that {year}/{month}/{day} forms a valid date)

```<code>routes.MapRoute("date", "{year}/{month}/{day}",
          new { controller = "Test", action = "Date" },
          new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}", date = new DateConstraint() });

// -----
public class DateConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        try
        {
            var year = int.Parse(values["year"] as string);
            var month = int.Parse(values["month"] as string);
            var day = int.Parse(values["day"] as string);
            var date = new DateTime(year, month, day);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
</code>```

Example of redirection in Ruby on Rails

```<code>get '/stories/:name', to: redirect {|params, req| "/posts/#{params[:name].pluralize}" }
</code>```

Title: Comparison of route formats

Body:
I've used ASP.NET MVC for years. Lately I've been doing research on Rails and Django to see if they have something more to offer. I've done reading the routing part of their documentation, but I haven't done any real apps yet, so I'm not an expert. I have no experience with Backbone, so I'll leave that out.

In short, Rails has the most powerful routing system of the three, Django has the weakest and ASP.NET MVC is somewhere between.

All have:

 - named routes

 - wildcards (in ASP.NET MVC only the last parameter)

 - extra data (pass some values that are not part of the route)

 - regex constraints

 - helpers to create urls

 - some kind of route prefix (namespace/area)

Ruby on Rails and ASP.NET MVC have:

 - generic routing  (one route, multiple controllers/actions)

 - default values

 - code constraints

Ruby on Rails has:

 - resource routing

 - powerful redirection

Example of regex constraint in Ruby on Rails (id has to be a number)

get ':controller/:id/:action', constraints: {id: /^\d+/}

Example of code constraint in ASP.NET MVC (check that {year}/{month}/{day} forms a valid date)

routes.MapRoute("date", "{year}/{month}/{day}",
          new { controller = "Test", action = "Date" },
          new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}", date = new DateConstraint() });

// -----
public class DateConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        try
        {
            var year = int.Parse(values["year"] as string);
            var month = int.Parse(values["month"] as string);
            var day = int.Parse(values["day"] as string);
            var date = new DateTime(year, month, day);
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Example of redirection in Ruby on Rails

get '/stories/:name', to: redirect {|params, req| "/posts/#{params[:name].pluralize}" }


问:
Quickest way to split a delimited String in Java
I am building a Comparator that provides multi-column sort capability on a delimited String.
I am currently using the split method from String class as my preferred choice for splitting the raw String into tokens.

Is this the best performing way to convert the raw String into a String array? I will be sorting millions of rows so I think approach matters.

It seems to run fine and is very easy, but unsure if there's a faster way in java.

Here is how the sort works in my Comparator:

```<code>public int compare(String a, String b) {

    String[] aValues = a.split(_delimiter, _columnComparators.length);
    String[] bValues = b.split(_delimiter, _columnComparators.length);
    int result = 0;

    for( int index : _sortColumnIndices ) {
        result = _columnComparators[index].compare(aValues[index], bValues[index]);
        if(result != 0){
            break;
        }
    }
    return result;
}
</code>```

After benchmarking the various approaches, believe it or not, the split method was the quickest using the latest version of java. You can download my completed comparator here: https://sourceforge.net/projects/multicolumnrowcomparator/

答:
As @Tom writes, an indexOf type approach is faster than String.split(), since the latter deals with regular expressions and has a lot of extra overhead for them.

However, one algorithm change that might give you a super speedup.  Assuming that this Comparator is going to be used to sort your ~100,000 Strings, do not write the Comparator<String>.  Because, in the course of your sort, the same String will likely be compared multiple times, so you will split it multiple times, etc...

Split all the Strings once into String[]s, and have a Comparator<String[]> sort the String[].  Then, at the end, you can combine them all together.

Alternatively, you could also use a Map to cache the String -> String[] or vice versa.  e.g. (sketchy)  Also note, you are trading memory for speed, hope you have lotsa RAM

```<code>HashMap<String, String[]> cache = new HashMap();

int compare(String s1, String s2) {
   String[] cached1 = cache.get(s1);
   if (cached1  == null) {
      cached1 = mySuperSplitter(s1):
      cache.put(s1, cached1);
   }
   String[] cached2 = cache.get(s2);
   if (cached2  == null) {
      cached2 = mySuperSplitter(s2):
      cache.put(s2, cached2);
   }

   return compareAsArrays(cached1, cached2);  // real comparison done here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As @Tom writes, an indexOf type approach is faster than String.split(), since the latter deals with regular expressions and has a lot of extra overhead for them.

However, one algorithm change that might give you a super speedup.  Assuming that this Comparator is going to be used to sort your ~100,000 Strings, do not write the Comparator<String>.  Because, in the course of your sort, the same String will likely be compared multiple times, so you will split it multiple times, etc...

Split all the Strings once into String[]s, and have a Comparator<String[]> sort the String[].  Then, at the end, you can combine them all together.

Alternatively, you could also use a Map to cache the String -> String[] or vice versa.  e.g. (sketchy)  Also note, you are trading memory for speed, hope you have lotsa RAM

HashMap<String, String[]> cache = new HashMap();

int compare(String s1, String s2) {
   String[] cached1 = cache.get(s1);
   if (cached1  == null) {
      cached1 = mySuperSplitter(s1):
      cache.put(s1, cached1);
   }
   String[] cached2 = cache.get(s2);
   if (cached2  == null) {
      cached2 = mySuperSplitter(s2):
      cache.put(s2, cached2);
   }

   return compareAsArrays(cached1, cached2);  // real comparison done here
}


问:
S.O.L.I.D., avoiding anemic domains, dependency injection?
Although this could be a programming language agnostic question, I'm interested in answers targeting the .NET ecosystem.

This is the scenario: suppose we need to develop a simple console application for the public administration. The application is about vehicle tax. They (only) have the following business rules:

1.a) If the vehicle is a car and the last time its owner paid the tax was 30 days ago then the owner has to pay again.

1.b) If the vehicle is a motorbike and the last time its owner paid the tax was 60 days ago then the owner has to pay again.

In other words, if you have a car you have to pay every 30 days or if you have a motorbike you have to pay every 60 days.

For each vehicle in the system, the application should test those rules and print those vehicles (plate number and owner information) that don't satisfy them.

What I want is:

2.a) Conform to the S.O.L.I.D. principles (especially Open/closed principle).

What I don't want is (I think):

2.b) An anemic domain, therefore business logic should go inside business entities.

I started with this:

```<code>public class Person
// You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.
{
    public string Name { get; set; }

    public string Surname { get; set; }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract bool HasToPay();
}

public class Car : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class Motorbike : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public class PublicAdministration
{
    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.HasToPay());
    }

    private IEnumerable<Vehicle> GetAllVehicles()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main(string[] args)
    {
        PublicAdministration administration = new PublicAdministration();
        foreach (var vehicle in administration.GetVehiclesThatHaveToPay())
        {
            Console.WriteLine("Plate number: {0}\tOwner: {1}, {2}", vehicle.PlateNumber, vehicle.Owner.Surname, vehicle.Owner.Name);
        }
    }
}
</code>```

2.a: The Open/closed principle is guaranteed; if they want bicycle tax you just inherit from Vehicle, then you override the HasToPay method and you're done. Open/closed principle satisfied through simple inheritance.

The "problems" are:

3.a) Why a vehicle has to know if it has to pay? Isn't a PublicAdministration concern? If public administration rules for car tax change, why Car has to change? I think you should be asking: "then why you put a HasToPay method inside Vehicle?", and the answer is: because I don't want to test for the vehicle type (typeof) inside PublicAdministration. Do you see a better alternative?

3.b) Maybe tax payment is a vehicle concern after all, or maybe my initial Person-Vehicle-Car-Motorbike-PublicAdministration design is just plain wrong, or I need a philosopher and a better business analyst. A solution could be: move the HasToPay method to another class, we can call it TaxPayment. Then we create two TaxPayment derived classes; CarTaxPayment and MotorbikeTaxPayment. Then we add an abstract Payment property (of type TaxPayment) to the Vehicle class and we return the right TaxPayment instance from Car and Motorbike classes:

```<code>public abstract class TaxPayment
{
    public abstract bool HasToPay();
}

public class CarTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class MotorbikeTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract TaxPayment Payment { get; }
}

public class Car : Vehicle
{
    private CarTaxPayment payment = new CarTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}

public class Motorbike : Vehicle
{
    private MotorbikeTaxPayment payment = new MotorbikeTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}
</code>```

And we invoke the old process this way:

```<code>    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.Payment.HasToPay());
    }
</code>```

But now this code won't compile because there's no LastPaidTime member inside CarTaxPayment/MotorbikeTaxPayment/TaxPayment. I'm starting to see CarTaxPayment and MotorbikeTaxPayment more like "algorithm implementations" rather than business entities. Somehow now those "algorithms" need the LastPaidTime value. Sure, we can pass the value to the constructor of TaxPayment, but that would violate vehicle encapsulation, or responsibilities, or whatever those OOP evangelists call it, wouldn't it?

3.c) Suppose we already have an Entity Framework ObjectContext (which uses our domain objects; Person, Vehicle, Car, Motorbike, PublicAdministration). How would you do to get an ObjectContext reference from PublicAdministration.GetAllVehicles method and therefore implement the funcionality?

3.d) If we also need the same ObjectContext reference for CarTaxPayment.HasToPay but a different one for MotorbikeTaxPayment.HasToPay, who is in charge of "injecting" or how would you pass those references to the payment classes? In this case, avoiding an anemic domain (and thus no service objects), don't lead us to disaster?

What are your design choices for this simple scenario? Clearly the examples I've shown are "too complex" for an easy task, but at the same time the idea is to adhere to the S.O.L.I.D. principles and prevent anemic domains (of which have been commissioned to destroy).

答:
I agree with the answer by @sebastiangeiger that the problem is really about vehicle ownerships rather than vehicles. I am going to suggest using his answer but with a few changes. I would make the Ownership class a generic class:

```<code>public class Vehicle {}

public abstract class Ownership<T>
{
    public T Item { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract TimeSpan PaymentInterval { get; }

    public virtual bool HasToPay
    {
        get { return (DateTime.Today - this.LastPaidTime) >= this.PaymentInterval; }
    }
}
</code>```

And use inheritance to specify the payment interval for each vehicle type. I also suggest using the strongly-typed TimeSpan class instead of plain integers:

```<code>public class CarOwnership : Ownership<Vehicle>
{
    public override TimeSpan PaymentInterval
    {
        get { return new TimeSpan(30, 0, 0, 0); }
    }
}

public class MotorbikeOwnership : Ownership<Vehicle>
{
    public override TimeSpan PaymentInterval
    {
        get { return new TimeSpan(60, 0, 0, 0); }
    }
}
</code>```

Now your actual code only needs to deal with one class - Ownership<Vehicle>.

```<code>public class PublicAdministration
{
    List<Ownership<Vehicle>> VehicleOwnerships { get; set; }

    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return VehicleOwnerships.Where(x => x.HasToPay).Select(x => x.Item);
    }
}
</code>```

OwnerDisplayName: David Robert Jones

Body:
I agree with the answer by @sebastiangeiger that the problem is really about vehicle ownerships rather than vehicles. I am going to suggest using his answer but with a few changes. I would make the Ownership class a generic class:

public class Vehicle {}

public abstract class Ownership<T>
{
    public T Item { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract TimeSpan PaymentInterval { get; }

    public virtual bool HasToPay
    {
        get { return (DateTime.Today - this.LastPaidTime) >= this.PaymentInterval; }
    }
}

And use inheritance to specify the payment interval for each vehicle type. I also suggest using the strongly-typed TimeSpan class instead of plain integers:

public class CarOwnership : Ownership<Vehicle>
{
    public override TimeSpan PaymentInterval
    {
        get { return new TimeSpan(30, 0, 0, 0); }
    }
}

public class MotorbikeOwnership : Ownership<Vehicle>
{
    public override TimeSpan PaymentInterval
    {
        get { return new TimeSpan(60, 0, 0, 0); }
    }
}

Now your actual code only needs to deal with one class - Ownership<Vehicle>.

public class PublicAdministration
{
    List<Ownership<Vehicle>> VehicleOwnerships { get; set; }

    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return VehicleOwnerships.Where(x => x.HasToPay).Select(x => x.Item);
    }
}


问:
Is this a correct implementation of an Immutable class in Java?
```<code>public final class ImmutableClass {

    private StringBuffer name;

    public ImmutableClass(StringBuffer name) {
        this.name=name;
    }
    public StringBuffer getName() {
        return name;
    }
}
</code>```

Points that I have considered:

Make the class final so that it cannot be extended

Do not provide public mutator methods

Keep the instance variables private

Are the above mentioned considerations sufficient?

答:
Whether the class is immutable or not depends upon whether you are intending it to encapsulate the identity of the StringBuffer or the contents thereof.  The design of the class suggests that it encapsulates the identity of the StringBuffer; because it will never identify any StringBuffer other than the instance identified to it at instantiation, the class ImmutableClass may be regarded as immutable.  Nonetheless, instances of ImmutableClass which encapsulate a particular StringBuffer should not be exposed to any code which cannot be trusted with an unguarded reference to that StringBuffer.

The pattern of having an immutable class identify a mutable object is not very common, but there are a few cases where it may be appropriate.  Perhaps the most natural example would be a class whose purpose is to set a mutable object to some particular state; such a class would encapsulate a reference to the object in question along with the desired state.  If the identity of the object and the state to which it should be set are both immutable, than the class encapsulating those things would likewise be immutable.  A key aspect of such designs is that the class which encapsulates the identity of the mutable object doesn't care regard the state of that object as being parts of its own state.  That situation is very different from a type which holds a reference to an unshared  mutable object for the purpose of encapsulating its own state therein.  An object which encapsulates mutable state anywhere, whether in itself or in another object, is mutable.  Merely holding a reference to a mutable object, however, does not imply encapsulating state thereof.


问:
Why doesn't Java 8 include immutable collections?
The Java team has done a ton of great work removing barriers to functional programming in Java 8.  In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations.  Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces?

Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the setter methods and make the existing interfaces extend from them, like this:

```<code>                  ImmutableIterable
     ____________/       |
    /                    |
Iterable        ImmutableCollection
   |    _______/    /          \   \___________
   |   /           /            \              \
 Collection  ImmutableList  ImmutableSet  ImmutableMap  ...
    \  \  \_________|______________|__________   |
     \  \___________|____________  |          \  |
      \___________  |            \ |           \ |
                  List            Set           Map ...
</code>```

Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed.  Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature.  But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry().  The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method.  Over time, the old methods could be deprecated.

Wins of immutable collections:

Simplicity — reasoning about code is simpler when the underlying data does not change.

Documentation — if a method takes an immutable collection interface, you know it isn't going to modify that collection.  If a method returns an immutable collection, you know you can't modify it.

Concurrency — immutable collections can be shared safely across threads.

As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation.  Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams).  Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them).  I don't see how Java can continue to compete without immutable collections.

Can someone point me to the history or discussion about this? Surely it's public somewhere.

答:
A mutable collection is not a subtype of an immutable collection.  Instead, mutable and immutable collections are sibling descendants of readable collections.  Unfortunately, the concepts of "readable", "read-only", and "immutable" seem to get blurred together, even though they mean three different things.

A readable collection base class or interface type promises that one may read items, and does not provide any direct means of modifying the collection, but does not guarantee that code receiving the reference cannot cast or manipulate it in such a way as to permit modification.

A read-only collection interface doesn't include any new members, but should only be implemented by a class which promises that there is no way to manipulate a reference to it in such a way as to mutate the collection nor receive a reference to something that could do so.  It does not, however, promise that the collection won't be modified by something else which has a reference to the internals.  Note that a read-only collection interface may not be able to prevent implementation by mutable classes, but can specify that any any implementation, or class derived from an implementation, which allows mutation shall be considered an "illegitimate" implementation or derivative of an implementation.

An immutable collection is one which will always hold the same data as long as any reference to it exists.  Any implementation of an immutable interface which does not always return the same data in response to a particular request is broken.

It is sometimes useful to have strongly-associated mutable and immutable collection types which both implement or derive from the same "readable" type, and to have the readable type include AsImmutable, AsMutable, and AsNewMutable methods.  Such a design can allow code which wants to persist the data in a collection to call AsImmutable; that method will make a defensive copy if the collection is mutable, but skip the copy if it's already immutable.

ContentLicense: CC BY-SA 4.0


问:
What does using (vec col) or (vector arg1 & args) cost?
I am working through some Lisp exercises using Clojure. If I were to convert Lisp lists to Clojure vectors, solving some of the problems would be simpler, so here is my question:

Does using vec or vector cost a lot in terms of time and/or processing? Does using either function cause a meta state change, or are the values converted and moved to a vector?

答:
I am using criterium library to measure performance.
I'm seeing better performance for vec than for apply vector</p>

```<code>user=> (use 'criterium.core)
nil
user=> (def mylist (range 100))
#'user/mylist
user=> (bench (apply vector mylist))
WARNING: Final GC required 4.142753917114324 % of runtime
Evaluation count : 8356800 in 60 samples of 139280 calls.
             Execution time mean : 7.271515 µs
    Execution time std-deviation : 112.366680 ns
   Execution time lower quantile : 7.066423 µs ( 2.5%)
   Execution time upper quantile : 7.485808 µs (97.5%)
                   Overhead used : 11.772233 ns
nil
user=> (bench (vec mylist))
Evaluation count : 8949480 in 60 samples of 149158 calls.
             Execution time mean : 6.647705 µs
    Execution time std-deviation : 83.691653 ns
   Execution time lower quantile : 6.473123 µs ( 2.5%)
   Execution time upper quantile : 6.796003 µs (97.5%)
                   Overhead used : 11.772233 ns
nil
</code>```

Body:
I am using criterium library to measure performance.
I'm seeing better performance for vec than for apply vector

user=> (use 'criterium.core)
nil
user=> (def mylist (range 100))
#'user/mylist
user=> (bench (apply vector mylist))
WARNING: Final GC required 4.142753917114324 % of runtime
Evaluation count : 8356800 in 60 samples of 139280 calls.
             Execution time mean : 7.271515 µs
    Execution time std-deviation : 112.366680 ns
   Execution time lower quantile : 7.066423 µs ( 2.5%)
   Execution time upper quantile : 7.485808 µs (97.5%)
                   Overhead used : 11.772233 ns
nil
user=> (bench (vec mylist))
Evaluation count : 8949480 in 60 samples of 149158 calls.
             Execution time mean : 6.647705 µs
    Execution time std-deviation : 83.691653 ns
   Execution time lower quantile : 6.473123 µs ( 2.5%)
   Execution time upper quantile : 6.796003 µs (97.5%)
                   Overhead used : 11.772233 ns
nil


问:
How is indirection different from aliasing?
Take from wikipedia, aliasing is defined as accessing a data location through different names.

Also taken from wikipedia, indirection is defined as referencing something "using a name, reference, or container instead of the value itself". Am I missing something here - Are these two one and the same? If not, how are they different?

答:
To my understanding, "indirection" is a very general term decribing all kind of forms of using alternate names, references, containers, wrappers, and so on - every kind of non-direct access. Aliasing is IMHO a special case of indirection, because aliasing is specifically about using different names, nothing else.

For example, in programming, accessing a library or a device through a public interface may allow to add some kind of indirection "behind the scenes", within the library, but without any visible change in the API (or names) from the viewpoint of a user of that library. For example, think of a network library which allows to activate or deactivate a "proxy". The public interface keeps staying the same, so there is no "aliasing" here, but its is indeed a form of indirection.


答:
Aliasing is when there are several names (or expressions) to designate the same object.

Indirection is when there are additional steps to reach the object.

Both are usually present, but not always.  As an example of aliasing without indirection

```<code>namespace X {
   int x;
}
namespace Y {
   using namespace X;
}
</code>```

X::x and Y::x are two different names for the same objects, there are aliases and no indirection is present.

As an example of indirection without aliases

```<code>int* p = new int;
</code>```

To access the allocated object, you have to go through p with *p, the access is indirect and there are no aliases.

But indirection is usually present when there are aliases (visibly with q=p, *p and *q are aliases, or more or less hidden in the implementation or the language rules, see references in C++ or with the fact that a[i] and a[j] which are aliases if i==j.)

Title: How is indirection different from aliasing?

Body:
Take from wikipedia, aliasing is defined as accessing a data location through different names.

Also taken from wikipedia, indirection is defined as referencing something "using a name, reference, or container instead of the value itself". Am I missing something here - Are these two one and the same? If not, how are they different?

Body:
Aliasing is when there are several names (or expressions) to designate the same object.

Indirection is when there are additional steps to reach the object.

Both are usually present, but not always.  As an example of aliasing without indirection

namespace X {
   int x;
}
namespace Y {
   using namespace X;
}

X::x and Y::x are two different names for the same objects, there are aliases and no indirection is present.

As an example of indirection without aliases

int* p = new int;

To access the allocated object, you have to go through p with *p, the access is indirect and there are no aliases.

But indirection is usually present when there are aliases (visibly with q=p, *p and *q are aliases, or more or less hidden in the implementation or the language rules, see references in C++ or with the fact that a[i] and a[j] which are aliases if i==j.)


问:
To load or not to load data for unit tests from external files
When unit testing I often find myself debating how much of the data I feed to, and expect back from my units under test, I should include in the actual test files.

The tradeoff I constantly struggling with is:

If a large portion of the test (in code volume) consists of input and output data, it seems difficult to actually read the test, but I can easily see the actual in-and outputs.

If I load the test data from files, I can easily test a bunch of variations on possible data input, easily reuse test data for multiple tests, but I have to leave the source code to look at another file to see what exactly the inputs are.

Is either one of these an anti-pattern?

答:
I don't see a trade-off here. Source code is supposed to describe algorithms, or at least business logic, not big amounts of data. If you write a Fourier transform, you want to verify that a sinus tone is correctly mapped to a single peak, a mixed sound to more peaks etc., but for that it is completely sufficient to feed a file named sinus.wav into the routine and verify that the output structure is what you expect.

Sure, technically you don't have an immediate assurance that sinus.wav really does contain a sinus tone, but as you said, listing the 100,000 amplitude values in the source doesn't really give you that either - in fact, it is worse, because you can at least play an external file with an audio player to check, while data values buried in source code are essentially impossible to do anything with.


问:
Detecting travel patterns in geospatial data
I need to analyze data uploaded from vehicle GPS devices to detect travel patterns and then attempt to learn about the normal travel patterns for that vehicle so that predictions can be made about maintenance, refueling etc. Some vehicles are domestic (exhibiting normal home->work->home travel patterns) and some are commercial with scheduled routing.

I have loaded the GPS lats and longs to a database, and then constructed an ST_LineString with the data points for each vehicle (approx 1k points per vehicle per day).

Vehicles will never have identical travel patterns (GPS accuracy, irregular ping times etc) and the patterns will be visible as subsets of pings - for example a one hour commute between point A (home) and point B (work) between 8am and 9.30am each morning, Mon-Fri.

Now the difficult part - I am considering the options. I have to write this in a database procedural language using the usual toolbox of procedures, cursors, iteration etc. I could use Python if it is helpful - I'm a database guy trying to think laterally and spatially.

A travel pattern could be identified by

(i) a similar sequence of points that can differ by a tolerance (say +/- 300 meters)

(ii) parking locations - if a car is parked at the same location for 8 hours a day

(iii) temporal- the vehicle starts at trip at 0830 every day, +/- 10 minutes.

I am planning to write a procedure that checks for each of these patterns for each point (or set of n points) by comparing it with all other points (or set of points) by iterating through the pings for each day in sequence.

The easiest use case is to find recurrences of a vehicle parked at the same place each day. Detecting similar movement patterns is more complex. What could be a technique for this?

答:
This is a general form of pattern recognition, and pattern recognition is hard - it was under scientific research for years.

I think the first thing you need to do here is to find formal definitions for all "travel patterns" you want to identify - I guess those examples are only the tip of the iceberg. Your definitions (2) and (3) are easy cases, but I guess they are not so interesting.

Case (1) is IMHO not a real pattern definition, but I guess you want to detect a pattern like "the same route is repeated at regular time intervals on a daily or weekly basis". But here the problem starts - what time intervals do you want to compare? What if the driver makes a detour at some days going out of your 300m radius? Do you want to identify the top 10 routes taken by each car over the year (and why)? Are two routes identical regardless of their time stamp, or should the time stamp matter? Is the direction of the route important, or not?

So my first advice is: start asking yourself the right questions - analyse the problem more in depth, not from a technical point of view ("what things are easy to compare"), but from the domain point of view ("what do I really want to know")?

One point you mentioned is "maintenance and refueling". For these things IMHO the routes are typically irrelevant. The general statistical information should be more interesting (how many miles/kilometers per year was the car on the road), the exact routes are neglectable.

For the problem of route comparing, without the temporal component: I would suggest not to compare "single points". Your points describe a 2D path, and you need a metrics to compare those paths, regardless of the number of points on that paths. There are some scientific papers on that topic, looking at google for "comparing two paths distance" will show up some of them.

Adding the temporal component could be seen as a 3D extension of the 2D problem, but I guess it will be easier when you start with the 2D case, and when you can identify paths which are similar on the plane, you can add some time comparisons afterwards.


问:
Programming beginner: Options for small program interfaces?
I have been a Rails developer for a year now, and I really want to start diving in to Ruby and pure programming without using a framework. However I am having trouble conceptualizing little programs I can build on my own. I guess it's because I'm so used to having a GUI (the web browser) to interact with the classes that I write that I don't really get how I would interact with classes without clicking, going to different pages, etc.

In terms of pure Ruby (without Rails), I've only built a blackjack game you play through the console through typing Y/N for hitting and staying. I would like to know what types of interfaces you guys use for your small programs? Are they all just ran once from your console using something like ruby myclass.rb? I have the motivation but I don't know what I would do after writing a few classes. All I do is have a separate file that requires all my other classes, instantiate my classes like so:

```<code>myclass = MyClass.new
myclass.part = ClassPart.new(1,2,3)
myclass.do_something # puts "value of instance_variable = #{@instance_variable}"
</code>```

And then what? The program finishes. It's not interactive. It doesn't do much. I don't see myself building anything cool/powerful like that. Can anyone enlighten me?

答:
The classes is just small or not small entities, that implements a defined set of functions. That functions can be realized by single or multiple set of methods. Mostly ruby scripts is used as console applications, which bring to mind console linux application like: ls, true, etc. And ruby apps also can be run by cron to perform daily work, like backup or etc, and you can automize some of you work on your PC by creating a simple application that you be able to use manually or by run from that cron.

Usually that application replesents a so called ruby gem, and is reshared with open source license. List of gems you can see at rubygems.org site.

For example, you can write an application that...., then turn it into a gem, and publish it. I'll describe steps do have to do from a scratch:

Install rvm.

Install some ruby version, for example any revision of ruby 2.0.0:

```<code>$ rvm install ruby-2.0.0
</code>```

Install a gem bundler:

```<code>$ gem install bundler
</code>```

Generate a gem sketch with bundler:

$ bundle gem yourgem
    $ cd yourgem

Edit .gemspec, and Gemfile accoring your needs.

Install all required gems:

```<code>$ bundle install
</code>```

Define your class in the /lib folder of your gem:

```<code>$ vim lib/yourgem.rb
</code>```

Define your binary (if needed) in the /bin folder of your gem:

```<code>$ vim bin/yourgembin.rb
</code>```

Change your gem version:

```<code>$ vim lib/yourgem/version.rb
</code>```

Release your gem with rake. it publishes the gem into rubygems:

```<code>$ rake release
</code>```

For example install the gem for your system:

```<code>$ sudo gem install yourgem
</code>```

Use it:

```<code>$ yourgembin
</code>```

If you wish to contribute to open source community you can pushlish you gem source into github.

Also you you are not forced to accomlish the all f the points. it is the sketch only.

Of course if you are the beginner of ruby you shell to think about not only valid syntax during the program write, but you shell to think about usability, and readability of your code syntax also. The good style you can find here.

Body:
The classes is just small or not small entities, that implements a defined set of functions. That functions can be realized by single or multiple set of methods. Mostly ruby scripts is used as console applications, which bring to mind console linux application like: ls, true, etc. And ruby apps also can be run by cron to perform daily work, like backup or etc, and you can automize some of you work on your PC by creating a simple application that you be able to use manually or by run from that cron.

Usually that application replesents a so called ruby gem, and is reshared with open source license. List of gems you can see at rubygems.org site.

For example, you can write an application that...., then turn it into a gem, and publish it. I'll describe steps do have to do from a scratch:

Install rvm.

Install some ruby version, for example any revision of ruby 2.0.0:

$ rvm install ruby-2.0.0

Install a gem bundler:

$ gem install bundler

Generate a gem sketch with bundler:

$ bundle gem yourgem
    $ cd yourgem

Edit .gemspec, and Gemfile accoring your needs.

Install all required gems:

$ bundle install

Define your class in the /lib folder of your gem:

$ vim lib/yourgem.rb

Define your binary (if needed) in the /bin folder of your gem:

$ vim bin/yourgembin.rb

Change your gem version:

$ vim lib/yourgem/version.rb

Release your gem with rake. it publishes the gem into rubygems:

$ rake release

For example install the gem for your system:

$ sudo gem install yourgem

Use it:

$ yourgembin

If you wish to contribute to open source community you can pushlish you gem source into github.

Also you you are not forced to accomlish the all f the points. it is the sketch only.

Of course if you are the beginner of ruby you shell to think about not only valid syntax during the program write, but you shell to think about usability, and readability of your code syntax also. The good style you can find here.


问:
What exactly happens on a LAMP machine when I request a php file?
I am a .NET developer who has recently started working in a LAMP environment. I know that if I go to www.somedomain.com/files/test.php, then (1) DNS resolves the URL to my server (2) my server handles the request on a given port (3) the server looks in /files/test.php and somehow runs test.php and returns the output of the file to the client.

But it would be really great to understand this process in much more detail. For instance, does Apache/nginx actually run the php file or does it pass it to the php interpreter? Does every php file run every time or does the server cache its output? It would be really helpful to know the major details/decisions that a LAMP environment makes during this process. Kind of like this answer, which explains in detail how SSL works...

https://security.stackexchange.com/questions/20803/how-does-ssl-work/20847#20847

答:
What exactly happens depends a lot on the needs and configuration of the individual application or server.

For instance, does Apache/nginx actually run the php file or does it pass it to the php interpreter?

Both are possible, but for performance reasons, the PHP interpreter is typically integrated into the server as a module (such as mod_php for Apache and php-fpm for nginx). Additionally, the PHP code is typically not interpreted but instead compiled into bytecode and stored in a cache such as APC, and then only the bytecode is executed.

Does every php file run every time or does the server cache its output?

This is very much application-specific. High-traffic websites have to employ aggressive caching strategies and wherever possible will cache fully rendered HTML pages via a reverse proxy setup, so the LAMP server itself will not even get involved in most requests.

Within the LAMP environment, it is also common to use memcached to cache partially rendered HTML fragments or the results of SQL queries; typically this requires manual tuning in the code or (if supported via some framework) configuration.


问:
Can a pure-functional solution to this problem be as clean as the imperative?
I have an exercise in Python as follows:

a polynomial is given as a tuple of coefficients such that the powers are determined by the indexes, e.g.: (9,7,5) means 9 + 7*x + 5*x^2

write a function to compute its value for given x

Since I am into functional programming lately, I wrote

```<code>def evaluate1(poly, x):
  coeff = 0
  power = 1
  return reduce(lambda accu,pair : accu + pair[coeff] * x**pair[power],
                map(lambda x,y:(x,y), poly, range(len(poly))),
                0)
</code>```

which I deem unreadable, so I wrote

```<code>def evaluate2(poly, x):
  power = 0
  result = 1
  return reduce(lambda accu,coeff : (accu[power]+1, accu[result] + coeff * x**accu[power]),
                poly,
                (0,0)
               )[result]
</code>```

which is at least as unreadable, so I wrote

```<code>def evaluate3(poly, x):
  return poly[0]+x*evaluate(poly[1:],x) if len(poly)>0 else 0
</code>```

which might be less efficient (edit: I was wrong!) since it uses many multiplications instead of exponentiation, in principle, I do not care about measurements here (edit: How silly of me! Measuring would have pointed out my misconception!) and still not as readable (arguably) as the iterative solution:

```<code>def evaluate4(poly, x):
  result = 0
  for i in range(0,len(poly)):
      result += poly[i] * x**i
  return result
</code>```

Is there a pure-functional solution as readable as the imperative and close to it in efficiency?

Admittedly, a representation change would help, but this was given by the exercise.

Can be Haskell or Lisp aswell, not just Python.

答:
There is a general set of steps you can use to improve readability of functional algorithms:

Put names on your intermediate results, instead of trying to cram everything on one line.

Use named functions instead of lambdas, especially in languages with verbose lambda syntax.  It's much easier to read something like evaluateTerm than a long lambda expression.  Just because you can use a lambda doesn't necessarily mean you should.

If one of your now-named functions looks like something that would come up pretty frequently, chances are it's already in the standard library.  Look around.  My python is a little rusty, but it looks like you basically reinvented enumerate or zipWith.

Often, seeing the functions and intermediate results named makes it easier to reason about what's going on and simplify it, at which point it might make sense to put a lambda back in or combine some lines back together.

If an imperative for loop looks more readable, chances are a for-comprehension would work well.


问:
Is using "out" or "ref" parameters in Java methods to return extra values bad?
I happened to create a mutable class like this:

```<code>class Mutable<T> {
    private T value;
    public Mutable() { this.value = null; }
    public Mutable(T value) { this.value = value; }
    T get() { return this.value; }
    void set(T value) { this.value = value; }
}
</code>```

And then it's often used in a method like this:

```<code>boolean operation(String input, Mutable<Set<String>> dataOut) throws ... {
    boolean result;
    try {
         String data = doSomething(input);
         result = validate(data);
         if (result && dataOut != null) {
             List<String> values = Arrays.asList(data.split(", "));
             Collections.sort(values);
             dataOut.set(new LinkedHashSet<String>(values));
         }
    } catch(SpecificIgnorableException ex) {
         result = false;
         logger.debug(ex);
    }
    return result;
}
</code>```

...which is just an example, could be any use case, where one would use ref or out parameters in C#, or non-const reference parameters in C++, or pointers to output parameters in C.

First, same could be done by using an array (with one element) instead of above custom type. Does it make sense to have this custom type which clearly states mutable, instead of using an implicitly mutable array?

Second, is this pattern bad and code smell in Java? Let's limit to cases where using out parameter would make sense in C#. Should every instance of this kind of Java code be replaced? With what?

答:
First of all, I don't think the get/set methods for the Mutable<T> accomplish much versus simply using an exposed field.  If a class will have any behavior, using get/set methods will allow the class much more flexibility in how it implements that behavior, but your Mutable<T> has no behavior.

Secondly, while generics are nice, they do cannot handle most primitives efficiently in Java.  You may thus need a MutableInt, MutableDouble, etc. in addition to the generic mutable [use of the generic form for Boolean may be okay, since there are only two possible Boolean values and both are cached].

Thirdly, calling a method which returns data in such fashion is somewhat awkward because it requires the caller to create a new object to accept the return data.

Given those constraints, however, I would posit that there are nonetheless cases where giving the caller an object it can mutate is nonetheless the right approach.  If an object wants to provide a means of asking its location, having a method which return Point will have an inherent ambiguity as to whether the returned object is "attached" to the object's position and also whether it will remain so.  By contrast, a method which accepts a Point from the caller and updates its coordinates to match the object's position implies no such ambiguity, since there would be no plausible reason for a point which was independent of the object's position not to remain so.


问:
What format is the data going to Windows print drivers?
I have been tasked with writing a print driver.  I have no experience with this and have been researching it for a few days.  The goal of this is to essentially write the data coming to the driver to a file and then do some additional processing of it.

If I understand it correctly, I can start other processes to do most of the work, but I'll need the driver itself to generate the initial file/data.  I am confused about what state the data is in when it comes to the driver from an application.  Is this something that is determined by the application, or is there a standard of some kind?

答: It is quite a while since I developed a printer driver for a customer but I will try to give you an idea of what happens. When your application communicates with an output device such as a printer or the display it opens a DC and starts sending GDI commands to draw an image on the page. The image can contain anything from picture drawing or text. The. Driver collects all this and when your are done with the page it starts transmitting the generated image using the printer language, postscript pcl or anything else to the device. This is the general idea behind these devices and the way they communicate with windows.</p>


问:
Legal issues of creating a version of a classic game (Snake)
I recently created a version of Snake, the classic game popularized by Nokia, and I am planning on using it as an example of my game development skills. I just want to know if there are any copyright issues that could come up if I do this?</p>

答:
As long as you make it a Snake-like game you should be OK. There are plenty of games in this genre and they do well. </p>

<p>A quick check and I couldn't turn up any specific copy write but it is best to make the game your own and not a direct copy.  </p>

Body:
As long as you make it a Snake-like game you should be OK. There are plenty of games in this genre and they do well.

A quick check and I couldn't turn up any specific copy write but it is best to make the game your own and not a direct copy.


答:
I am not a lawyer.  Do not take this as legal advice.

There are three realms of intellectual property protection.  Copyright, Trademark, and Patent.

You specifically asked for copyright in this question.  Copyright protects the actual code, the actual art resources (including music), the actual wording in the instructions, and the actual runnable executable.

It is unlikely you are infringing upon any of these things.

A notable bit to be aware of when reimplementing games and copyright is that somehow The Tetris Company makes copyright infringement claims which noted infringement on the shapes of the blocks and the play field dimensions.  I'm not a lawyer, and don't fully understand the grounds for that - just something to avoid and note that just because its not the things that are typically copyrightable that someone won't try to go after you.  Another example of this can be found in the Triple Town / Yeti Town suit.

Lest this worry you that Nokia will come down and try to fuss about things, the game Snake is a rather old one.  I played a game called Snake Byte in the days of the 6502 - a video of a remake of the game I played.  That this game is so old and redone so many times, that you likely don't have much concern about reimplementing it again yourself - there's not one company that is holding on to the property and continue to gain from it.

Trademark is a minefield in IP.  The use of the name 'snake' in reference to a game was trademarked - trademark search: name snake; owner nokia for computer games.  The key thing there is the disclaimer: "NO CLAIM IS MADE TO THE EXCLUSIVE RIGHT TO USE "SNAKES" APART FROM THE MARK AS SHOWN" - you should be ok there too.  Its also the only trademark that Nokia claims on Snakes.  Note also that trademark is still active.  Trademarking the word would likely have been problematic as lots of things use the word 'snake' as part of a game.

Patent is also a minefield.  Typically, however you won't typically find the patent for a video game.  On the other hand, there are numerous patents for board games.  If you were trying to reimplenet a board game, say Khet You would run into patent 7,264,242 (which was upheld recently against a big name company).  That said, trawling expired patents and deciphering the legalese back into rules can find some unpublished games that might be something to implement (5,145,182 was filed in 1990, expired in 2010, and had the patent fee lapse in 2000).

Title: Legal issues of creating a version of a classic game (Snake)

Body: I recently created a version of Snake, the classic game popularized by Nokia, and I am planning on using it as an example of my game development skills. I just want to know if there are any copyright issues that could come up if I do this?</p>


问:
PHP composer question
just getting started with composer and I have a couple of questions.

When I use composer to add a dependency, the dependency gets added to my folder's Vendor directory.  The newly added package not only comes with the source code for that package, but all packagist required files for the developer to test and add that package to packagist repo (composer.json, .travis.yaml, license, readme.md, etc).

For my project, do I need to keep the vendor's required packagist files in my project?

Can I clean the package folder structure up a little?

I added the package, Slim micro framework, which nests the source files three directories deep upon installation, ../vendor/slim/slim/Slim/(source Files).  Is it worth moving these files to the top Slim directory like: ../vendor/Slim/(source files)?  Or will this ruin the integrity of the package?

答:
The answer is simply: You shouldn't mess with the directories.

Here's why:
Every Composer package is structured like the following vendor/packageName/[actualCode].

If you have multiple packages from the same vendor, let's say package A from C and package B from C, it'll look this way:

vendor/C/A/

vendor/C/B/

If you now put the code directly to the vendor directory, composer won't find the package anymore.

Title: PHP composer question


问:
Understanding unit testing concept
I've just started writing unit tests and I'm not sure am I doing it the "right way." Should I test every class "by removing dependencies"? In other words, does unit testing mean: "test part of a code with assumption that provided dependencies to other modules are correct and test these dependencies as single modules later in other unit test classes"?

For example, I write WinRT application in Model-View-ViewModel manner and I have MainViewModel class. This class has dependency to IDataRepository which is injected in constructor. MainViewModel is responsible for handling commands and connecting model with view. MainViewModel has commands like CopyItems, LoadData etc which are relying on IDataRepository implementation.

Should I pass fake (mock/fake it??) IDataRepository in MainViewModel_Tests and test just is data loaded, copied etc. on command execution? Should one test check just things what class really do - not what dependencies do?

答:
Should I pass fake (mock/fake it??) IDataRepository in MainViewModel_Tests and test just is data loaded, copied etc. on command execution?

Yes.  As far as possible unit tests should test a single class.  Any dependency that connects to any data source outside the test process should be mocked.  This includes local system state like the system clock.

Should one test check just things what class really do - not what dependencies do?

Yes, otherwise your tests will become very fragile.  A change in the behavior of a dependent class may require changes to all tests that depend on that class.  Ideally each behavior is tested exactly once.

Of course you will still need to do integration testing.

Title: Understanding unit testing concept


问:
How much of my time will be taken in planning sprints etc?
I am senior developer/architect who knows the business domain really well.

My new manager wants me to manage a team (yet to recruit of around 5 people) and in the past I have worked in an agile environment but as a developer. So I was involved in the writing user stories, working with stake holders, estimating via story points and all the development work involved in getting to the end of a sprint/project.

I would like to carry on working as a developer and spend most of my time in the depth of writing code but my manager believes only 10% of my time will involved in the management side (i.e. creating product logs, agile estimation etc). He has never worked on an agile project. I am still reading up on all that involved in managing an agile project so it is hard for me to say how much of my time will be involved.

My question is how much of my time will be spent on working on the side of managing an agile project?

This is something I would like to do but I am not sure if I want to do this if I spend all my time on the management side.

答:
There are several things to consider in determining this stuff:

estimates: these should always be bottom up--if you do a user story approach, figure on having a regular meeting with your team and SMEs sometime near the end of each sprint to update your product backlog with estimates for enough user stories to cover the next several sprints.  Figure on a 2-3 hour meeting for this in early sprints, maybe going down to an hour in later sprints.

administrative tasks: try to spread (diffuse) the pain as much as you can that is, delegate if possible, perhaps having a different team member do X each sprint.  Have a task board that the team can update throughout each sprint.

enforcement:  that is, making sure the team is helping with estimates and updating the task board.  This will take more time to start, then become trivial.

training/mentoring: you've got to do as much as the team needs.  This is very hard for an outsider to judge.

removing obstacles:  this can be a full time job, depending.  Is your manager helping with this?

So, you should probably let your manager know that initially, you're going to be spending 25-50% of your time getting the regular flow of the project into gear, along with some amount of time training/mentoring.  Hopefully, after a couple months, this will be reduced to 10-15%.  The real question then becomes how much support you will get removing the obstacles the team runs into.  If you're on your own there, you will not be doing any coding.


问:
Why do most programming languages only support returning a single value from a function?
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

答:
It started with math.  FORTRAN, named for "Formula Translation" was the first compiler. FORTRAN was and is oriented to physics/math/engineering.

COBOL, nearly as old, had no explicit return value; It barely had subroutines.  Since then it's been mostly inertia.

Go, for example, has multiple return values, and the result is cleaner and less ambiguous than using "out" parameters.  After a little bit of use, it is very natural and efficient.  I recommend multiple return values be considered for all new languages. Maybe for old languages, too.


答:
I was a software architect who transitioned to being a technical product owner for a team. In my experience, I needed to spend a good 25% of my time or more working strictly as product owner. It took a surprising amount of time to do the job right, and when I didn't, it affected the team.

Some weeks I spent 50% of my time, or more. It's  hard to say for certain, because I also acted as architect -- this let me cut out the normal PO/Architect meetings since I was just meeting with myself. Between being the architect and being the PO, I rarely spent more than 6-8 hours of coding a week.

Don't forget that grooming the backlog and keeping it up to date takes real time and requires real thought. It isn't just a little extra work you have to do. Also, preparing for sprint demos and retrospectives takes real time as well. For me, on demo days my time was 100% spent on non-coding activities, and the day before a good 50%-75% or more.

So, here's one bit of anecdotal evidence that says you'll need to spend at least a quarter of your time, and possibly more depending on your organization, your team, and the product you are building.

Title: How much of my time will be taken in planning sprints etc?

Body:
I am senior developer/architect who knows the business domain really well.

My new manager wants me to manage a team (yet to recruit of around 5 people) and in the past I have worked in an agile environment but as a developer. So I was involved in the writing user stories, working with stake holders, estimating via story points and all the development work involved in getting to the end of a sprint/project.

I would like to carry on working as a developer and spend most of my time in the depth of writing code but my manager believes only 10% of my time will involved in the management side (i.e. creating product logs, agile estimation etc). He has never worked on an agile project. I am still reading up on all that involved in managing an agile project so it is hard for me to say how much of my time will be involved.

My question is how much of my time will be spent on working on the side of managing an agile project?

This is something I would like to do but I am not sure if I want to do this if I spend all my time on the management side.


答:
I think it heavily depends on the nature and current state of the project:

Optimistic:
All of the new (5) developers joining the team will be from similar domains and instantly grok the challenges in the features you are building.  Since you understand the domain and the architecture (and the project is not too large), you can easily answer questions about it without drawn out whiteboard sessions etc.  Plus the system is written very well (using TDD) and fully documented.

Pessimistic:
Over the years, the system has been has been built by several teams and each team thought they were following their best practice. This means that the code base now has several strategies for solving similar issues.  Also, the project management up to now has centred around pushing out new features fast, so the technical debt has stacked up.  Also, unit testing has always been an after thought.  Adding to this, the domain is very niche and all the new developers will need extensive training before they will understand parts of the domain.

So, in the optimistic scenario, you probably could be coding alongside the new developers fairly quickly.  The only main issue is personalities and working behaviours as the team forms into a cohesive unit. While in the pessimistic scenario, being the main link both for the domain (business) and the architecture (technical) you will be having extensive conversations and writing a lot of wiki entries or documentation.

You can probably see where this is going, something like, "Hope for the best, plan for the worst".

Having been in a similar situation in the past, I would say that you shouldn't plan on coding at all for at least 4-6 months.  Taking on the responsibility for both the architecture and business link for a large project can be a lot of work (even for a team of 5).  This doesn't mean that you won't be coding at all. However, the times you are coding should be interrupted frequently by people asking questions. (You might want to look into things like Pomodoro Technique etc)

Ok, now a few more things with my pessimistic hat on. :)

Your manager says it will only take 10% of your time. So, that roughly equates to 4 hours a week. If that is the case, why does your manager not just manage the project?  Probably because he or she knows that it will end up taking more time then that.

As developers, IMO, we tend to severely underestimate good management.  Now, SCRUM is far from perfect, but there is a reason why 2 of the 7 full time jobs go to managing (scrummaster and product owner).


问:
Does Clojure borrow concurrency ideas from Haskell?
In code quarterly interview with Rich Hickey, Michael Fogus hints that Clojure borrows a lot from Haskell:

Fogus:

As someone who only knows Haskell enough to read the papers, Clojure appears to be influenced by it substantially. From the names and operation of core functions—take, drop, iterate, repeat, etc.—to its protocols facility, there is a lot in Clojure that a Haskell programmer would recognize. Can you elaborate on Haskell’s influences on Clojure both positive and negative?

Hickey:

I think Haskell is a fantastic, awe-inspiring piece of work. I haven’t used it in anger, but it certainly was a positive influence. Haskell obviously goes much further than Clojure in pursuing the ideals of functional programing. In particular they differ in the approach to using types to enforce things.

My question is - Does Clojure borrow concurrency ideas from Haskell? Fogus hints at some syntax, and there is obviously functional laziness. What about the STM and concurrency operators?

Assumptions:

I'm asking this question in a positive tone. I think it is great that Rich could see some of the treasures in Haskell and use them.

答:
The vibe I'm getting is that the biggest influence on Concurrency in Clojure is Multiversion Concurrency Control - which comes from the database world. We see this with refs, which are part of the MVCC Software Transactional Memory. </p>

<p>What is interesting is the critiques of Clojure's concurrency model by Martin Thompson. His claim is that ultimately the scalability model is limited by Amdahl's law. This is as the refs depend on a Compare and Swap (CAS) operation - which is ultimately sequential, and will eventually become a bottleneck. </p>

Body:
The vibe I'm getting is that the biggest influence on Concurrency in Clojure is Multiversion Concurrency Control - which comes from the database world. We see this with refs, which are part of the MVCC Software Transactional Memory.

What is interesting is the critiques of Clojure's concurrency model by Martin Thompson. His claim is that ultimately the scalability model is limited by Amdahl's law. This is as the refs depend on a Compare and Swap (CAS) operation - which is ultimately sequential, and will eventually become a bottleneck.


答:
It's possible it will only take 5%.

I am basing it on my experience in a following setup: 2-week sprints, planning takes half of a day, demo + retro take half of a day, daily scrums - 15 mins each, full code review. All these you would do anyway as any team member so we shouldn't count them. Here are things that will differentiate your position from simple senior:

prepare for planning (ensure backlog is in good state, with all the fields filled in, print cards, secure a meeting room, gather everyone) - about 2 hours

fill scrum board after planning (reprint cards, prepare burn-down diagram) - about 1 hour

prepare for demo - almost no time, you can arrange that everyone prepares his/her part.

And a couple of things that you should estimate yourself:

interacting with project owner, support, designers, etc. In prefect scrum you do that directly only on planning and demos and use project backlog all other time. In practice you will occasionally talk to them during sprint.

shielding your team from managers, support and project owner. Ideally, these guys should not interrupt you during sprint, but they will, so you need to listen to them and either ask them to add whatever they are talking about to backlog or add an new urgent task to your board.

Both things become easy and not time-consuming once you educated everybody to respect your process.


答:
... as an example of my game development skills

In most creative fields, ignoring the legal rights and creating an unsellable version of a work strictly for portfolio development is perfectly fine.  Especially if you're attempting to demonstrate your proficiency in some other area, such as with either graphic design or programming, rather than actual game design.

The story changes if you're attempting to demonstrate actual game design skills, which would require some actual creativity on top of "snake" that would keep the project form being mere plagiarism.  And the story changes again if you want to actually distribute the game, such as in a smartphone app-store.

Placing your game development portfolio online is probably OK, especially if it's not a for-profit site and have sufficient contact information for someone who wants to present a IP claim so you can comply and simply take down the offending project.


问:
Why is the following naming guideline different between OO and non-OO languages?
I am working with a non-OO language and I'm trying to name my routines consistently. I came acrross the following guideline from Steve McConnell's Code Complete:

To name a procedure, use a strong verb followed by an object

McConnell gives the following good and bad examples:

good, non-OO --> PrintDocument(doc)

good, OO -->       doc.Print()

bad, OO -->          doc.PrintDocument()

For an OO language, doc.PrintDocument() is non-recommended on the basis that it is redundant.

I'm having a hard time wrapping my head around this guideline. Why is PrintDocument(doc)recommended, and doc.PrintDocument() non-recommended?

Also, what would be the problem with the simpler name Print(doc) in a non-OO language?

Am I missing something very basic here?

答:
In any kind of programming, it's helpful to have identifiers semantically divided into groups according to the kinds of things upon which they operate.  In an object-oriented framework, the identifiers for different types are inherently divided into different groups regardless of what they're called, but in a non-object-oriented framework the system lumps all identifiers together.  If names don't include something to identify what part of the program they belong to, it can be difficult to keep track of which type uses a delete, which uses free, which uses release, which uses close, which uses shutdown, etc. while if the functions were instead named DeleteDrawingContext, FreeMemHandle, ReleaseLock, CloseFile, ShutdownSocket, it would be much clearer.  Things could be clearer yet if they used similar verbs (since one wouldn't have to make the verbs unique to avoid naming collisions).

It's worth noting that some people prefer to prefix identifier name with the a tag related to the subsystem that defines them (e.g. identifers related to the Foo Manager subsystem might be FM_Create, FM_Release, etc.)  Such usage isn't necessary in languages where one can logically subdivide the namespaces, but can be helpful in those where everything gets lumped together in one global namespace.  Note that it doesn't really matter if everyone follows the convention; if half the identifiers have prefixes and half don't, the presence or absence of a prefix may become in and of itself an indication of the subsystem that defines an identifier.


答:
As others have stated, there are a lot of factors at work here. I guess I'd like to start by trying to make a list of which ones I think will affect your time the most:

Where does your company draw the lines for project management? For example, is your manager some form of a project manager that you expect to be heavily involved in driving the project management or does all of that fall to you? The more they are involved, the less time you may have to spend - to a point. The fact that your manager thinks this will only take 10% of your time strikes me as one of three things: 1) he is indirectly communicating his level of involvement - which would be quite a bit, 2) he is new to the role of manager and may not be communicating realistic expectations, or 3) he is trying to offload work to you and this is his way of convincing you.

How well-defined is the project? If you are joining the project with well-thought out requirements in-hand, that is quite different than joining in the early stages. Who's managing the requirements document? If it's you or someone on your team and not your manager or some other person, that's a good litmus test of the expectations for you and your team.

How decisive is the customer? How needy are they? Some clients (if this is an external project) can be quite needy and demand lots of time. Again this also comes back to how management is divided in your company. On a similar note...

How many different customers are involved in the project? If it is just your company and the client, great. But if there are other entities like say, an external design company, prepare for a lot more communication churn.

Is the end size of the team you plus five others? One team lead at my work place goes by the rule of thumb that he tends to go to almost 100% management time once he has at least four people on his team. For me it would probably be about 80% with four, but that largely depends on your team as well - so getting to that...

How experienced are the people joining you? If any are new hires, my gut says 10% of your time for each new hire should be set aside for at least a few months. For anybody straight out of school, make that 20-25% per person.

So to review from a high level. The agile project management truly doesn't take that long, but I personally find it highly unlikely that that is all you will do in this role. I suspect that you will also be a leader that helps mentor and guide your team as well as possibly a customer liaison. So the agile project management could be done in perhaps 10% of your time (although 15% at least sounds more reasonable). But for the team lead part alone, expect 25-75% of your time depending on circumstances. For customer liaison, that's extremely variable based on your involvement and can be anything from 10% to nearly a full time job. On the whole, I find your manager's suggestion of 10% like a lowball answer. Please evaluate question #1 very carefully and act accordingly.

If this is your first opportunity at having a chance to lead, I recommend taking it. I think a lot of technical folks (but certainly not all!) are surprised by how much they like the technical lead role - I know I thought I wanted to hide in a cave and code but the reality is that I have found being a team lead to be a fantastic experience.


答:
It probably has more to do with the legacy of how function calls are made in processor machine instructions and the fact that all programming languages derive from machine code: for example, C -> Assembly -> Machine.

How Processors Perform Function Calls

The first programs were written in machine code and then later assembly. The processors supported function calls by pushing a copy of all of the current registers to the stack. Returning from the function would pop the saved set of registers from the stack. Usually one register was left untouched to allow the returning function to return a value.

Now, as to why the processors were designed this way... it was likely a question of resource constraints.

Title: Why do most programming languages only support returning a single value from a function?

Body:
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?


答:
I just want to build on Harvey's answer. I originally found this question on a news tech site (arstechnica) and found an amazing explanation that I feel really answers the core of this question and is lacking from all the other answers(except Harvey's):

The origin of single return from functions lies in the machine code. At the machine code level, a function can return a value in the A (accumulator) register. Any other return values will be on the stack.

A language that supports two return values will compile it as machine code that returns one, and puts the second on the stack. In other words, the second return value would end up as an out parameter anyway.

It is like asking why assignment is one variable at a time. You could have a language that allowed
a, b = 1, 2
for instance. But it would end up at the machine code level being a = 1 followed by b = 2.

There is some rationale in having programming language constructs bear some semblance to what will actually happen when the code is compiled and running.


问:
How to maintain a forked git repo with feature branches that upstream won't pull?
So here's a typical workflow on Github...

Like some project -> fork it -> git clone https://github.com/you/someproject.

Open project.  Like what you see, but make some changes.

Having been careful to work only in a feature-branch (git checkout -b some-feature), you decide to make a pull request with the upstream maintainer - after having pushed your feature-branch to your Github fork.

Maintainer, for whatever reason, declines the pull.

For example.. here is a failed pull request that I submitted that matches the above scenario...

Now typically, if the maintainer HAD merged the pull... the workflow would be simple...  On my local machine, I would commit any local changes on whatever feature-branch I was on at the time... git fetch --all, git checkout master, git pull upstream --ff-only.  Then replay my changes on top of that, as desired...

BUT...

What if I decide that you want to continue working off the changes to my fork, regrdless... yet still want to be able to track + merge changes that happen upstream?  Ordinarily, I would delete the feature branch, and go on my way..  How can you maintain a master branch that is able to be merged upstream, yet maintains your fork's features while being "permanently detached" from upstream's HEAD?

答:
Regardless of the use of your scenario, here is how you can do it:

master is exactly of the version the upstream master has

custom is your own "master" branch in which you have applied the formatting changes

all feature branches are branched off custom if you don't want them to be pulled into upstream master

Once master is updated, you rebase custom to master and then you rebase your feature branches to custom

With this strategy it should work. But keep in mind that every change you make in a feature branch based upon custom won't be accepted into upstream master.


问:
What is the significance of the output of Function Point analysis
I am a beginner in Software Engineering principles. This question have only academic significance.

I read about Function Point analysis.We will be getting an integer value as output for Function Point analysis.

What all things can be inferred from that output?

I know that it is an estimation technique. But couldn't understand how to read that output

答:
from http://en.wikipedia.org/wiki/Function_point_analysis

A function point is a unit of measurement to express the amount of
  business functionality an information system (as a product) provides
  to a user. The cost (in dollars or hours) of a single unit is
  calculated from past projects

May be an example helps:

past: in the last 300 workingdays peter finished implementing features with a calculated total of 600 functionpoints.

from the past on average peter implemented 2 functionpoints per day.

presence: There is a new software feature X to be implemented that has 100 functionpoints.

Assuming that peter still has the same development velocity you can predict that the new feature will riquire 200 days.

Why using functionpoints?

calulating function point is much easier than estemaiting effort to implement a feature.

If a manager knows how to calulate the functionpoints and he knows from the past that

susan can do 5 functionpoints per day

peter can do 2 functionpoints per day

The manager can estimate how long it will take to implement the project and decide if peter or susan should do the job.


答:
I think it's because of expressions, such as (a + b[i]) * c.

Expressions are composed of "singular" values. A function returning a singular value can thus be directly used in an expression, in place of any of the four variables shown above. A multi-output function is at least somewhat clumsy in an expression.

I personally feel that this is the thing that's special about a singular return value. You could work around this by adding syntax for specifying which of the multiple return values you want to use in an expression, but it's bound to be more clumsy than the good old mathematical notation, which is concise and familiar to everyone.


问:
Optimal way to implement this specific lookup table in C#?
I want to create a lookup table for this data:

The "input variables" (what is used to "lookup") are 4 different doubles that can each take on 1 of 200 numbers (the numbers range from 1-1000 but there are only 200 possible numbers that each can be (these 200 possible numbers that each of them can be are known to me)) the doubles are all 2 decimal places. If any one of the four were changed it would slightly change the output variables. There is also 1 integer (enum really) that can take on a value from 1-5.

There is a condition on 3 of the input variables that (1/x + 1/y + 1/z must be less than 1.02). Could this be used in a hashing algorithm?

The "output variables" (what is returned) are ~30 doubles (mostly 2 decimal places but one has 10 decimal places). (will be packaged in an object) ranging from 1 to 1000 (2 decimal places).

I expect there to be ~150 million records.

Should I use a big dictionary and load it into memory then I start the program?

Would a Database and LINQ be best?

Can I use Trees or Hashing in some way to speed it up?

I've never had to make a LUT this big before, where speed is a major factor.

Clarification: Because of the condition that (1/x + 1/y + 1/z must be less than 1.02, see above) there is only ~150 million combinations of input variables. Not ~(200)^4.

Update:

I have looked at some stats (min and max observed values and discovered some relationships) for my input variables and have found that if we call the 4 input doubles A, B, C, D: A and B have ~200 possible values each,

C has ~50 possible values, and

D has ~120 possible values

Of these, there are several relationships that mean that there are only ~27 million combinations of these rather than the ~150 million I originally thought. So there will be ~27 million records in the LUT. There is also definitely a relationship that I haven't been able to figure out between (A, B, C) and D which will also bring down the number of combinations.

Would it be optimal to run the LUT from RAM now that I have reduced the entries from 150 to 27 million (and probably lower)?

Now that it's down to 27 million would storing them as ints by multiplying them by 100 (2 decimal places) still be optimal?

As DocBrown suggested, I should store the doubles as ints (multiply by 100 because they have 2 decimal places) and then combine the 5 different ints (4 doubles (see above) and 1 enum (value:1-5)) into a key for the LUT.

How to do this such that I will have a unique value for each combination of my 5 input variables (the 5 ints) AND this method is open to expansion of each of the input variables, i.e. should I need to expand the double C's combinations to 70 instead of 50 I will need unique key values for the new entries that are result of the expanded number of total combinations of the input variables.

答:
Ideally a LUT should be quick to reference but can be slow to generate. Unfortunately I don't think your scenario is going to be quick to reference. Given five different input variables, this would require some sort of hash mechanism that guarantees a unique value for every possible combination. This is not going to be very quick to generate.

I think looking into tree based structures will be your best bet.

Perhaps a "tree" where each of your input elements is used as a index into a smaller LUT which then references another LUT....etc, until you reach the final LUT giving you your output data.

From your inputs description it looks like you could have as many as 8 billion records (200^4)*5.


答:
Generally, this kind of pattern should be avoided because its usability. It is not so obvious how to call it correctly, comparing to simple single return value function.

However, it has its own merit performance-wise for returning value of primitive types or an instance that already exists, especially in Java where you cannot return struct and returning new instance of an object every time might not be an option for tight loop. Let's compare it to .Net C# Dictionary<T,U>'s TryGetValue method:

```<code>public bool TryGetValue(
    TKey key,
    out TValue value
)
</code>```

It is the same pattern as yours, and it is there for performance reason because without this method the code must be

```<code>if (dictionary.ContainsKey(key)) {
    int value = dictionary[key];
}
</code>```

Which is slower because same lookup will occur twice (let alone multithreading for now). However, using ContainsKey is more clear in this case and most coders will use it for trivial lookup rather than using TryGetValue.

So the bottom line is, it depends on how would you use it. From your code, the overhead of return value initiation seems to outweigh the performance benefit of the pattern already. However, you might want to provide this function to leave the room for some optimisation later.

Title: Is using "out" or "ref" parameters in Java methods to return extra values bad?

Body:
I happened to create a mutable class like this:

```<code>class Mutable<T> {
    private T value;
    public Mutable() { this.value = null; }
    public Mutable(T value) { this.value = value; }
    T get() { return this.value; }
    void set(T value) { this.value = value; }
}
</code>```

And then it's often used in a method like this:

```<code>boolean operation(String input, Mutable<Set<String>> dataOut) throws ... {
    boolean result;
    try {
         String data = doSomething(input);
         result = validate(data);
         if (result && dataOut != null) {
             List<String> values = Arrays.asList(data.split(", "));
             Collections.sort(values);
             dataOut.set(new LinkedHashSet<String>(values));
         }
    } catch(SpecificIgnorableException ex) {
         result = false;
         logger.debug(ex);
    }
    return result;
}
</code>```

...which is just an example, could be any use case, where one would use ref or out parameters in C#, or non-const reference parameters in C++, or pointers to output parameters in C.

First, same could be done by using an array (with one element) instead of above custom type. Does it make sense to have this custom type which clearly states mutable, instead of using an implicitly mutable array?

Second, is this pattern bad and code smell in Java? Let's limit to cases where using out parameter would make sense in C#. Should every instance of this kind of Java code be replaced? With what?

Body:
Generally, this kind of pattern should be avoided because its usability. It is not so obvious how to call it correctly, comparing to simple single return value function.

However, it has its own merit performance-wise for returning value of primitive types or an instance that already exists, especially in Java where you cannot return struct and returning new instance of an object every time might not be an option for tight loop. Let's compare it to .Net C# Dictionary<T,U>'s TryGetValue method:

public bool TryGetValue(
    TKey key,
    out TValue value
)

It is the same pattern as yours, and it is there for performance reason because without this method the code must be

if (dictionary.ContainsKey(key)) {
    int value = dictionary[key];
}

Which is slower because same lookup will occur twice (let alone multithreading for now). However, using ContainsKey is more clear in this case and most coders will use it for trivial lookup rather than using TryGetValue.

So the bottom line is, it depends on how would you use it. From your code, the overhead of return value initiation seems to outweigh the performance benefit of the pattern already. However, you might want to provide this function to leave the room for some optimisation later.


答:
To understand what's going on it's best to look at the Common Gateway Inteface.  For efficiency reasons almost no one uses it anymore, but the modern substitutes (mod_php, fastcgi) were designed to be backwards compatible with it.

Basically, the web server receives a http request, figures out by lookingat the URL that it's supposed to run a php script to satisfy it, then runs the php interpreter on that script with a bunch of environment variables set with the query information.  The output of the php interpreter is sent back to the http client.

Title: What exactly happens on a LAMP machine when I request a php file?

Body:
I am a .NET developer who has recently started working in a LAMP environment. I know that if I go to www.somedomain.com/files/test.php, then (1) DNS resolves the URL to my server (2) my server handles the request on a given port (3) the server looks in /files/test.php and somehow runs test.php and returns the output of the file to the client.

But it would be really great to understand this process in much more detail. For instance, does Apache/nginx actually run the php file or does it pass it to the php interpreter? Does every php file run every time or does the server cache its output? It would be really helpful to know the major details/decisions that a LAMP environment makes during this process. Kind of like this answer, which explains in detail how SSL works...

https://security.stackexchange.com/questions/20803/how-does-ssl-work/20847#20847