问:
How to simplify my complex stateful classes and their testing?
I am in a distributed system project written in java where we have some classes which corresponds to very complex real-world-business objects. These objects have a lot of methods corresponding to actions that the user (or some other agent) may apply to that objects. As a result, these classes became very complex.

The system general architecture approach has lead to a lot of behaviors concentrated on a few classes and a lot of possible interaction scenarios.

As an example and to keep things easy and clear, let's say that Robot and Car were classes in my project.

So, in the Robot class I would have a lot of methods in the following pattern:

sleep(); isSleepAvaliable();

awake(); isAwakeAvaliable();

walk(Direction); isWalkAvaliable();

shoot(Direction); isShootAvaliable();

turnOnAlert(); isTurnOnAlertAvailable();

turnOffAlert(); isTurnOffAlertAvailable();

recharge(); isRechargeAvailable();

powerOff(); isPowerOffAvailable();

stepInCar(Car); isStepInCarAvailable();

stepOutCar(Car); isStepOutCarAvailable();

selfDestruct(); isSelfDestructAvailable();

die(); isDieAvailable();

isAlive(); isAwake(); isAlertOn(); getBatteryLevel(); getCurrentRidingCar(); getAmmo();

...

In the Car class, it would be similar:

turnOn(); isTurnOnAvaliable();

turnOff(); isTurnOffAvaliable();

walk(Direction); isWalkAvaliable();

refuel(); isRefuelAvailable();

selfDestruct(); isSelfDestructAvailable();

crash(); isCrashAvailable();

isOperational(); isOn(); getFuelLevel(); getCurrentPassenger();

...

Each of these (Robot and Car) is implemented as a state machine, where some actions are possible in some states and some aren't. The actions changes the object's state. The actions methods throws IllegalStateException when called in an invalid state and the isXXXAvailable() methods tell if the action is possible at the time. Although some are easily deducible from the state (e.g, in the sleeping state, awake is available), some aren't (to shoot, it must be awake, alive, having ammo and not riding a car).

Further, the interactions between the objects are complex too. E.g, the Car can only hold one Robot passenger, so if another one try to enter, an exception should be thrown; If the car crashes, the passenger should die; If the robot is dead inside a vehicle, he can't step out, even if the Car itself is ok; If the Robot is inside a Car, he can't enter another one before stepping out; etc.

The result of this, is as I already said, these classes became really complex. To make things worse, there is hundreds possible scenarios when the Robot and the Car interacts. Further, much of that logic does needs to access remote data in other systems. The result is that unit-testing it became very hard and we have a lot of testing problems, one causing the another in a vicious circle:

The testcases setups are very complex, because they need to create a significantly complex world to exercize.

The number of tests is huge.

The test suite takes some hours to run.

Our test coverage is very low.

The testing code tends to be written weeks or months later than the code that they test, or never at all.

A lot of tests are broken too, mainly because the requirements of the tested code changed.

Some scenarios are so complex, that they fail on timeout during the setup (we configured a timeout in each test, in the worst cases 2 minutes long and even this time long they timeouts, we ensured that it is not an infinite loop).

Bugs regularly slips into production environment.

That Robot and Car scenario is a gross over-simplification of what we have in reality. Clearly, this situation is not manageable. So, I am asking help and suggestions to: 1, Reduce the classes complexity; 2. Simplify the interactions scenarios between my objects; 3. Reduce the test time and the amout of code to be tested.

EDIT:

I think I was not clear about the state machines. the Robot is itself a state machine, with states "sleeping", "awake", "recharging", "dead", etc. The Car is another state machine.

EDIT 2:
In the case that you are curious about what my system actually is, the classes that interact are things like Server, IPAddress, Disk, Backup, User, SoftwareLicense, etc. The Robot and Car scenario is just a case that I found that would be simple enough to explain my problem.

答:
I was reading the "Origin" section of the Wikipedia article on the Interface Segregation Principle, and I was reminded of this question.

I shall quote the article. The problem: "...one main Job class....a fat class with multitudes of methods specific to a variety of different clients." The solution: "...a layer of interfaces between the Job class and all of its clients..."

Your problem seems a permutation of the one Xerox had. Instead of one fat class you have two, and these two fat classes are talking to each other instead of lots of clients.

Can you group the methods by type of interaction and then create an interface class for each type? For example: RobotPowerInterface, RobotNavigationInterface, RobotAlarmInterface classes?


问:
How should I choose the right Android phone for testing my app?
I am looking to buy an Android phone to test my first Android app on.

What things should I pay attention to to make sure I pick the most suitable device?

答:
I see two ways to choose device for you:

A. If you have no statistic from previous version of app.

You should buy device from potentially most popular group of devices for your future app.

Steps:

Use statistic from android site (developer.android.com/about/dashboards/index.html) choose group that most interesting to you.

Go to http://choosedevice.com group android devices in the same way.

Find selected group from step 1.

Choose device from the list of devices for your group

B. If you have statistic for your app.

You should find device to cover as more android users as possible for your project.

Steps:

Find most popular devices for your project (for example using google analytics)

Group those devices by parameters on choosedevice.com

Find most popular groups

Find most popular devices in each group

So you should buy device from step 4, which will cover more android users than other.

ContentLicense: CC BY-SA 3.0


问:
Keyword Collection, ManyToOne or OneToMany relationship?
I hope this is the right place for this type of problem.

An Object of my class Movie can have several keywords ( like 'fight club', 'brad', 'fincher'),  and be part of different categories (like 'Drama', 'Best Movies Ever') I implemented them as ManyToMany:

```<code>@OneToMany(targetEntity = Keyword.class,fetch=FetchType.EAGER)
    private Set<Keyword> keywords;

@OneToMany(targetEntity = MovieCategory.class, fetch=FetchType.EAGER)
    private Set<MovieCategory> movieCategories;
</code>```

Somehow I don' think, this is not the correct relationshipmodel, how would you implement this? Right now hibernate wont allow me to fetch.eager. fetch.lazy is okay. I found this link http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/ but it didn't answered my question.

答:
Why not use @ManyToMany?
If different movies have different keywords and a keyword can be related to different movies then that requires @ManyToMany. The same goes for categories.</p>


问:
You're hired to fix a small bug for a security-intensive site. Looking at the code, it's filled with security holes. What do you do?
I've been hired by someone to do some small work on a site. It's a site for a large company. It contains very sensitive data, so security is very important. Upon analyzing the code, I've noticed it's filled with security holes - read, lots of PHP files throwing user get/post input directly into mysql requests and system commands.

The problem is, the person who made the site for him is a programmer with family and children who depend on that job. I can't just say: "your site is a script kiddie amusement park. Let me redo it for you and you'll be fine."

What would you do in this situation?

Update:

I followed some good advice here and politely reported to the developer that I've found some possible security flaws on the site. I pointed out the line and said there could be a possible vulnerability for SQL injection attacks there, and asked if he knew about it. He replied: "sure, but I think that to exploit it the attacker should have information on the structure of the database; I have to understand better".

Update 2:

I said that's not always the case and suggested he follows this Stack Overflow question link in order to deal with it properly: How to prevent SQL injection in PHP? He said he would study it and thanked me for telling him before. I guess my part is done, thanks guys.

答:
First and only; Management does not want to hear about problems. I got fired from the Office of Personnel Management (security clearances for the white house) because I pointed out how insecure their system was. That was awhile back, but management attitudes have not changed.

Address the problem with the developer, via email so you have a trail, then walk or run away. When they do eventually have a problem, as a contractor, they will try to blame you, regardless of having any involvement even remotely connected to the problem.

Having a problem as fundamental as a SQL injection, indicates they were cheap when they initially developed the system, and odds are they are at best cheap now. Get what you can from them while they are still in business, but seek business development elsewhere.


问:
Xerox SOLID example in PHP
There is a good example on Wikipedia regarding the violation of SOLID principles.

The ISP was first used and formulated by Robert C. Martin while
  consulting for Xerox. Xerox had created a new printer system that
  could perform a variety of tasks like stapling a set of printed papers
  and faxing. The software for this system was created from the ground
  up and performed its tasks successfully. As the software grew, making
  modification became more and more difficult so that even the smallest
  change would take a redeployment cycle of an hour. This was making it
  near impossible to continue development. The design problem was that
  one main Job class was used by almost all of the tasks. Anytime a
  print job or a stapling job had to be done, a call was made to some
  method in the Job class. This resulted in a huge or 'fat' class with
  multitudes of methods specific to a variety of different clients.
  Because of this design, a staple job would know about all the methods
  of the print job, even though there was no use for them. The solution
  suggested by Martin is what is called the Interface Segregation
  Principle today. Applied to the Xerox software, a layer of interfaces
  between the Job class and all of its clients was added using the
  Dependency Inversion Principle. Instead of having one large Job class,
  a Staple Job interface or a Print Job interface was created that would
  be used by the Staple or Print classes, respectively, calling methods
  of the Job class. Therefore, one interface was created for each job,
  which were all implemented by the Job class.

http://en.wikipedia.org/wiki/Interface_segregation_principle

I tried to find a good PHP solution for this, I got this far:

```
 class Job implements StampleJob, PrintJob {
 }

 class Print {
   protected $objPrintJob;
   public function __construct(PrintJob $objPrintJob) {
     $this->objPrintJob = $objPrintJob;
   }
 }

 class Staple {
   protected $objStapleJob;
   public function __construct(StapleJob $objStapleJob) {
     $this->objStapleJob = $objStapleJob;
   }
 }
```

I can understand how the interface will limit knowledge but this will not actually change the big Job class or remove the SRP violation. Can you clarify how this solution actually solves the problem: "The design problem was that
one main Job class was used by almost all of the tasks"?

答:
First, lets understand what was the issue:
The Staple job knows about many more methods which it doesn't use today, (e.g., the print method) but which are available for it to use, should it want to.
However, the Job class "thinks" that the Staple class will be "a good citizen" and never use the print method at all.

There are many potential big issues here -
For some reason, the Staple job may start using the print method - by accident or intentionally.

Then down the road, either any changes to the print method may go untested,

OR, any changes to the print method will trigger a regression test in the Staple job also,

AND, any impact analysis for changes to the print job will necessarily involve impact analysis of the staple job too.

This is just the issue of Staple knowing about the print functions. Then there's the case of the Print job knowing all about stapling functions. Same problems.

Very soon, this system would reach a point where any change will require a full blown impact analysis of each module and a full blown regression test.

Another problem is that today, all jobs which can be printed can be stapled, and vice versa on this particular printer.

However, tomorrow, there could be a need to install the same firmware on a device that only prints or only staples. What then? The code already assumes that all Jobs are printable and stapleable. So any further granular breakdown / simplification of responsibilities is impossible.

In more recent terms, imagine a class called "AppleDevice" which has functions for MakePhoneCall as well as PlayMusic. Now your problem is while you can easily use this on an iPhone, you cannot use it for an iPod since the iPod cannot make phone calls.

So, the issue is not that the Job class is all-powerful. In fact, that's how it should be, so that it can act as a common link in the entire "workflow" where someone may scan a job, then print it, then staple it etc.
The problem is that the usage of all its methods is not restricted. Anyone and everyone could use and abuse any method whenever they want to, thus making the maintenance difficult.

Hence, the Dependency Injection approach of only telling users "exactly what they need to know, and nothing more" ensures that calling modules only use the code that they are meant to.
A sample implementation would look like:

```<code>interface IStapleableJob { void stapleYourself(); }
interface IPrintableJob { void printYourself(); }
class Job implements IStapleableJob, IPrintableJob {
....
}

class Staple {
  public static void stapleAllJobs(ArrayList<IStapleableJob> jobs) {
    for(IStapleableJob job : jobs) job.stapleYourself();
  }
}

class Print {
  public static void stapleAllJobs(ArrayList<IPrintableJob> jobs) {
    for(IPrintableJob job : jobs) job.printYourself();
  }
}
</code>```

Here, even if you pass a Job object to the Staple and Print methods, they dont know that its a Job, so they cannot use any methods that they are not supposed to. Thus, when you make any changes to a module, your scope of impact analysis and regression testing is restricted. That's the problem that ISP solves.

Title: Xerox SOLID example in PHP

Body:
First, lets understand what was the issue:
The Staple job knows about many more methods which it doesn't use today, (e.g., the print method) but which are available for it to use, should it want to.
However, the Job class "thinks" that the Staple class will be "a good citizen" and never use the print method at all.

There are many potential big issues here -
For some reason, the Staple job may start using the print method - by accident or intentionally.

Then down the road, either any changes to the print method may go untested,

OR, any changes to the print method will trigger a regression test in the Staple job also,

AND, any impact analysis for changes to the print job will necessarily involve impact analysis of the staple job too.

This is just the issue of Staple knowing about the print functions. Then there's the case of the Print job knowing all about stapling functions. Same problems.

Very soon, this system would reach a point where any change will require a full blown impact analysis of each module and a full blown regression test.

Another problem is that today, all jobs which can be printed can be stapled, and vice versa on this particular printer.

However, tomorrow, there could be a need to install the same firmware on a device that only prints or only staples. What then? The code already assumes that all Jobs are printable and stapleable. So any further granular breakdown / simplification of responsibilities is impossible.

In more recent terms, imagine a class called "AppleDevice" which has functions for MakePhoneCall as well as PlayMusic. Now your problem is while you can easily use this on an iPhone, you cannot use it for an iPod since the iPod cannot make phone calls.

So, the issue is not that the Job class is all-powerful. In fact, that's how it should be, so that it can act as a common link in the entire "workflow" where someone may scan a job, then print it, then staple it etc.
The problem is that the usage of all its methods is not restricted. Anyone and everyone could use and abuse any method whenever they want to, thus making the maintenance difficult.

Hence, the Dependency Injection approach of only telling users "exactly what they need to know, and nothing more" ensures that calling modules only use the code that they are meant to.
A sample implementation would look like:

interface IStapleableJob { void stapleYourself(); }
interface IPrintableJob { void printYourself(); }
class Job implements IStapleableJob, IPrintableJob {
....
}

class Staple {
  public static void stapleAllJobs(ArrayList<IStapleableJob> jobs) {
    for(IStapleableJob job : jobs) job.stapleYourself();
  }
}

class Print {
  public static void stapleAllJobs(ArrayList<IPrintableJob> jobs) {
    for(IPrintableJob job : jobs) job.printYourself();
  }
}

Here, even if you pass a Job object to the Staple and Print methods, they dont know that its a Job, so they cannot use any methods that they are not supposed to. Thus, when you make any changes to a module, your scope of impact analysis and regression testing is restricted. That's the problem that ISP solves.


问:
Sorting an ArrayList by a Split Value
I am attempting to create an list which should be sorted by a particular field in a colon separated string.  I have an array of strings with the following values:

```<code>name1:535
name2:697
</code>```

After sorting this list, I would have it sorted by the number in the second field:

```<code>name2:697
name1:535
</code>```

How should I go about doing this, are there any issues I should be aware of when sorting this List of Strings?

答:
The naive answer is to have a type that has a String value in it that does the work in compareTo() from the comparable interface.

The code would look something like this...

The problem with this is that it is doing much more work than is needed.  A simple test:

```<code>public class Thingy implements Comparable<Thingy> {
    double value;
    public Thingy(double arg) {
        value = arg;
    }

    @Override
    public int compareTo(Thingy thingy) {
        Global.count++;
        return Double.valueOf(value).compareTo(thingy.value);
    }
}

public class Global {
    public static int count;
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Thingy> things = new ArrayList<Thingy>();
        for(int i = 0; i < 1000; i++) {
            things.add(new Thingy(Math.random()));
        }
        Collections.sort(things);
        System.out.println(Global.count);
    }
}
</code>```

shows that compareTo() was called 9015 times.  If one is doing any repeated calculation in compareTo() it is being called much more than it needs to and the work it does is unnecessary.

Coming from a perl background, one of the idiomatic calls is the Schwartzian transform - the "sort based on a computation" is something that is quickly recognized.  In this code, one does:

```<code>@sorted = map  { $_->[0] }
          sort { $a->[1] <=> $b->[1] }
          map  { [$_, split($_)[0]] }
               @unsorted;
</code>```

While the comparison is being called many times, it is being done on a stored value rather than a (re)computed value.  See also Memoization.

In Java, one would likely have the constructor for the class break the string up into the component parts, and sort based on the parts rather than the whole.

If you are dealing with unique values to be sorted on (balance isn't likely unique but I'm explaining it anyways), one could use a SortedMap - just insert the key and value.  If the key already has a natural ordering to it (Integers, Strings and the like), no more work need be done.  You've got a sorted structure that has quite a bit of additional things that you may find useful when you need them (which actually come from NavigableMap, but the TreeMap and the SkipListMap are a NavigableMap in addition to being a SortedMap).

One could create a TreeMap with constructor that you pass a Comparator<String> into (javadoc for the constructor
 and javadoc for Comparator) and do the work on the String to do the ordering, though this could suffer from the problems of doing repeated calculations in the compareTo() method that I mentioned above. (An example where it doesn't is a Z-A sorted TreeMap as described in this question - one gets the general idea though - the general solution can be seen here).

If what you have isn't unique, you can still use it in a SortedMap structure, just that the value instead of being a String is a Set of Strings.

This then means two step adds (if the key doesn't exist, create it and then create the set, and then add the value to the set) and lookups (if the key exists, check to see if the value exists in the set).

It would be sensible to wrap that work in a class of its own so that you don't have copied boilerplate code for doing the multi-step add and lookup in multiple spots.

If you just have an array that you are going to sort once and then use, and be done with it and the extensibility of having an object (the name:balance represents an object that is more interesting than just a string), you could use the Comparator mentioned above as a parameter for the Collections.sort(List, Comparator) (javadoc).  Remember that for sizable lists the number of invocations to extract the field to compare on from a is much more than calculating it once and storing it in an associated object.

Title: Sorting an ArrayList by a Split Value

Body:
The naive answer is to have a type that has a String value in it that does the work in compareTo() from the comparable interface.

The code would look something like this...

The problem with this is that it is doing much more work than is needed.  A simple test:

public class Thingy implements Comparable<Thingy> {
    double value;
    public Thingy(double arg) {
        value = arg;
    }

    @Override
    public int compareTo(Thingy thingy) {
        Global.count++;
        return Double.valueOf(value).compareTo(thingy.value);
    }
}

public class Global {
    public static int count;
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Thingy> things = new ArrayList<Thingy>();
        for(int i = 0; i < 1000; i++) {
            things.add(new Thingy(Math.random()));
        }
        Collections.sort(things);
        System.out.println(Global.count);
    }
}

shows that compareTo() was called 9015 times.  If one is doing any repeated calculation in compareTo() it is being called much more than it needs to and the work it does is unnecessary.

Coming from a perl background, one of the idiomatic calls is the Schwartzian transform - the "sort based on a computation" is something that is quickly recognized.  In this code, one does:

@sorted = map  { $_->[0] }
          sort { $a->[1] <=> $b->[1] }
          map  { [$_, split($_)[0]] }
               @unsorted;

While the comparison is being called many times, it is being done on a stored value rather than a (re)computed value.  See also Memoization.

In Java, one would likely have the constructor for the class break the string up into the component parts, and sort based on the parts rather than the whole.

If you are dealing with unique values to be sorted on (balance isn't likely unique but I'm explaining it anyways), one could use a SortedMap - just insert the key and value.  If the key already has a natural ordering to it (Integers, Strings and the like), no more work need be done.  You've got a sorted structure that has quite a bit of additional things that you may find useful when you need them (which actually come from NavigableMap, but the TreeMap and the SkipListMap are a NavigableMap in addition to being a SortedMap).

One could create a TreeMap with constructor that you pass a Comparator<String> into (javadoc for the constructor
 and javadoc for Comparator) and do the work on the String to do the ordering, though this could suffer from the problems of doing repeated calculations in the compareTo() method that I mentioned above. (An example where it doesn't is a Z-A sorted TreeMap as described in this question - one gets the general idea though - the general solution can be seen here).

If what you have isn't unique, you can still use it in a SortedMap structure, just that the value instead of being a String is a Set of Strings.

This then means two step adds (if the key doesn't exist, create it and then create the set, and then add the value to the set) and lookups (if the key exists, check to see if the value exists in the set).

It would be sensible to wrap that work in a class of its own so that you don't have copied boilerplate code for doing the multi-step add and lookup in multiple spots.

If you just have an array that you are going to sort once and then use, and be done with it and the extensibility of having an object (the name:balance represents an object that is more interesting than just a string), you could use the Comparator mentioned above as a parameter for the Collections.sort(List, Comparator) (javadoc).  Remember that for sizable lists the number of invocations to extract the field to compare on from a is much more than calculating it once and storing it in an associated object.


问:
Design pattern for sharing Social Authentication across subdomains?
Right now building an app that authenticates using either email or different social accounts. Because it is going to function on multiple subdomains and domains, I'm wondering if there's a design pattern that's been used in the past to accomplish this without issue.

Basically, it's for authentication only as we are using profile information stored locally. I was originally thinking of doing something like an iframe pointed to accounts.domain.com that could always check login status of social accounts.

Thanks!

答:
From an architecture point of view, I would think of such a "single sign-on" problem like this:

Domain has many sub-domains

User authenticates with Domain, and then uses sub-domains

User auth token is shared among sub-domains

I imagine that you would have some sort of application level caching in step 2, so that even if say, you have a Google-authenticated user, you would not be hitting Google on every user action. Rather, you would authenticate the user once with Google, then cache the user's token for some interval and repeat.

You could embed this code in an auth module that could be invoked by the banners of your sites.


问:
How does one serve content with node.js without requiring a framework or library?
I'm trying to learn node.js and create a web application, and although I'm doing my best to just use only node.js to create it, I'm having a very difficult time finding resources and examples that describe the process without using other frameworks or libraries.

Specifically, how can I serve HTML and CSS content without using hard-coded string variables, but serving up HTML and CSS files dynamically using just node.js?

答:
From what I understand you are trying to build a static file server on you own.This gist can be a good starting point.It does not give any explanation of the code but it is easy to understand.For instance take a look at this piece of code

```<code>var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
</code>```

Here 4 modules are being required.Now to know more about these modules all you got to do is go the node js api docs and read more about them.Node js 's API is very small and this is the best way to learn it.

Also while it can be a very good learning exercise to build a server of your own you should use an already built library for production.

Body:
From what I understand you are trying to build a static file server on you own.This gist can be a good starting point.It does not give any explanation of the code but it is easy to understand.For instance take a look at this piece of code

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;

Here 4 modules are being required.Now to know more about these modules all you got to do is go the node js api docs and read more about them.Node js 's API is very small and this is the best way to learn it.

Also while it can be a very good learning exercise to build a server of your own you should use an already built library for production.


问:
Qt solutions have been re-licensed, can I use the src directly now
I have a commercial application that uses a Qt Solutions component. Until recently, this component was licensed under the LGPL license, so I was forced to use the component in the form of a shared library.
According to this post http://qt.digia.com/Product/Qt-Add-Ons/Qt-Solutions-Archive/, the Qt solutions have been re-licensed with the BSD license reproduced below.

My question is, can I mow use the source code directly in my application or do I still need to create a shared library? (the appropriate copyright notices will be reproduced regardless)

BSD lisence:

This sofware uses Qt Solutions component which is covered by the following license:

Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of Digia Plc and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

答:
Yes, the BSD license allows you to directly incorporate the (new version of the) Qt Solutions component in your closed-source application. There is no need to go the route of using it via a shared library.

Note that the new license only applies to new versions. You got your current version under the LGPL license, so as long as you use that version, you are bound by the LGPL license.


答:
Here you'll build a simple app without using any frameworks. Recommended to get a first touch at node: The Node Beginner Book » A comprehensive Node.js tutorial

The aim of this document is to get you started with developing applications with Node.js, teaching you everything you need to know about "advanced" JavaScript along the way. It goes way beyond your typical "Hello World" tutorial...

This document will probably fit best for readers that have a background similar to my own: experienced with at least one object-oriented language like Ruby, Python, PHP or Java, only little experience with JavaScript, and completely new to Node.js.

Aiming at developers that already have experience with other programming languages means that this document won't cover really basic stuff like data types, variables, control structures and the likes. You already need to know about these to understand this document.

However, because functions and objects in JavaScript are different from their counterparts in most other languages, these will be explained in more detail...

The URL router implemented there can easily be augmented to serve static files, using the fs module to read them on disk.

Title: How does one serve content with node.js without requiring a framework or library?

Body:
I'm trying to learn node.js and create a web application, and although I'm doing my best to just use only node.js to create it, I'm having a very difficult time finding resources and examples that describe the process without using other frameworks or libraries.

Specifically, how can I serve HTML and CSS content without using hard-coded string variables, but serving up HTML and CSS files dynamically using just node.js?


问:
Heap overflow vs stack overflow
So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?  </p>

答:
The answer is clearly platform dependent, compiler dependent and even library dependent.

But consider that in a process there is one stack per thread and as many heap as the process requires to the systems (normally 1, but there can be more: an OS can have API to allocate various "heaps").

There are OSs that gives to a process a given chunk, in which heap and stacks are taken by subtraction, and OSs that gives distinct blocks to the process each mapping a different block of physical memory.

On OSs and processors that implement virtual memory, the process address space is mapped to physical memory by some pointer tables invisible to the process itself.

When we say that the stack grows and shrink we are talking in the "process view". In the "OS view", a stack is just a block that doesn't grow or shrink upon every call/return. it is just more or less filled up. When it becomes full, it has to be reallocated on another physical memory area with more space. The cost of "reallocating a stack frame" is heavy (it must have no "holes" inside) so many OSs doesn't allow a stack to grow over a predefined size.  But heap dos not need that care: if a heap block is full, another block is added. No need to make it contiguous. This -on many platform- gives the perception (in the "process space") that a stack is limited (usually 4MB or similar) while the heap is "endless" (and limited only by the physical memory or swap area).

OwnerDisplayName: Rayhunter

Title: Heap overflow vs stack overflow


问:
Shared context: good or bad?
RSpec allows users to share context across tests / examples, which would reduce the number of code lines in my app by a significant amount.

On the other hand, somehow related to the question of sharing codebase between tests, one of the reasons why I'm using Factories and not Fixtures is because I don't want tests to be dependent on code stored outside the tests. Ryan Bates explains it better:

There’s a heavy dependency between the tests and the fixtures and we can cause the tests to fail just by changing the fixtures. External dependencies that are this strong aren’t a good idea and make the tests brittle.

What's best practice here, to share context across tests or to have an independent context for each test?

答:
The factory in of itself is supposed to seem stateless, in that from the caller point of view, the factory does the same thing each and every time.  So logically, the only way you could present a problem sharing a factory is if you somehow breached this contract and returned instances were somehow affected by previous calls to the factory.

In other words, a factory can and usually does perform optimizations for creating instances, but the caller can't be at all affected by this.  So in the simple case in which  a factory merely creates an instance and returns it would not cause you problems which you would have to worry about with a shared factory.

However, while a factory can optimize this by sharing instances, it's understood that the objects being shared are (or seemingly) stateless.  If they are not and if you are lucky, you see these errors immediately, though if you're not lucky, then you receive a series of bugs in your program that may not present themselves until many months later.  This is an anti-pattern and if I may add, a particularly nasty one.

So if you want to use a factory, just be sure it fits the pattern.  If you're not dealing with stateless objects, just don't take any shortcuts and instantiate each object when the factory is called to create an instance and you should be fine.

Title: Shared context: good or bad?


问:
Arithmetic coding issue
Since a few days I am fighting my way through implementing arithmetic coding. I found a really great source of information which made me understand how it should work. Long story short, it implements arithmetic coding on integers using two registers: HIGH and LOW. Those register store a fraction, ex.

```<code>HIGH = 98765 //means 0.98765(9)
LOW = 91234 // means 0.91234(0)
</code>```

Then comes magic, when the most significant numbers match (in this case it would be 9s) they are printed out. It's all clear to me.

However, when we take the following example

```<code>                         HIGH    LOW    RANGE   CUMULATIVE OUTPUT

Initial state           99999  00000   100000
Encode B (0.2-0.3)      29999  20000
Shift out 2             99999  00000   100000    .2
Encode I (0.5-0.6)      59999  50000             .2
Shift out 5             99999  00000   100000    .25
Encode L (0.6-0.8)      79999  60000   20000     .25 //here starts problems
Encode L (0.6-0.8)      75999  72000             .25 //how possible?
Shift out 7             59999  20000   40000     .257
Encode SPACE (0.0-0.1)  23999  20000             .257
Shift out 2             39999  00000   40000     .2572
Encode G (0.4-0.5)      19999  16000             .2572
Shift out 1             99999  60000   40000     .25721
Encode A (0.1-0.2)      67999  64000             .25721
Shift out 6             79999  40000   40000     .257216
Encode T (0.9-1.0)      79999  76000             .257216
Shift out 7             99999  60000   40000     .2572167
Encode E (0.3-0.4)      75999  72000             .2572167
Shift out 7             59999  20000   40000     .25721677
Encode S (0.8-0.9)      55999  52000             .25721677
Shift out 5             59999  20000             .257216775
Shift out 2                                      .2572167752
Shift out 0                                      .25721677520
</code>```

I really don't know how the marked lines are achieved on computers, on paper it's easy, since:

```<code>/*
    range, HIGH, LOw - integer
    symbol->high, symbol->low - real
*/
HIGH = HIGH - (range - symbol->high*range)
LOW = LOW + range*symbol->low
</code>```

But on computers? The real-number inaccuracy comes in and my intervals are much different.

```<code>[0; 99999)  100000  b   [0.2; 0.3)
[20000; 29999)  100000  ===> 2
[0; 99999)  100000  i   [0.5; 0.6)
[50000; 59998)  100000  ===> 5 //inaccuracy
[0; 99989)  99990   l   [0.6; 0.8)
[59993; 79990)  19998   l   [0.6; 0.8)
[71991; 75990)  19998   ===> 7
[19910; 59909)  40000       [0; 0.1)
[19910; 23908)  3999    g   [0.4; 0.5)
[21509; 21908)  3999    ===> 2
[15090; 19089)  3999    ===> 1
[50900; 90899)  40000   a   [0.1; 0.2)
[54900; 58898)  40000   ===> 5
[49000; 88989)  39990   t   [0.9; 1)
[84991; 88988)  39990   ===> 8
[49910; 89889)  39980   e   [0.3; 0.4)
[61904; 65900)  39980   ===> 6
[19040; 59009)  39970   s   [0.8; 0.9)
[51016; 55011)  39970   ===> 5
zakodowano: 257215865
</code>```

I would appreciate any help.

答:
You shouldn't use floating point in such cases.

Probabilities can be represented as rational numbers with denominator 10^something, this allows you to divide current interval exactly without rounding errors.

So in your case 0.6 becomes 6/10, 0.8 - 8/10. How you will store such things is your choice. Usually some kind of fixed point format is used. For example you store 60 and know that this is actually probability*100, so whenever you multiply by it, you also divide by 100.

Also note that later you will encounter another type of overflow - when you cannot shift out anything, but number of digits doesn't allow to divide interval without rounding errors. In such cases you either allow some inaccuracy in dividing interval or artificially narrow it to make shift out possible. If decode does everything in the same way, this doesn't impact correctness, but reduces compression a bit.

Title: Arithmetic coding issue


问:
What are the downsides of mixing tabs and spaces?
The advantage of using tabs for indentation is that people can configure their editor to use the tab width they are comfortable with. The only argument against this seems to be that people don't want their code to look differently based on editor settings. However, since code is ultimately being written to be easy to read later, it seems much more beneficial to allow the reader to set the width to their preferred value.

On the other hand, because tabs have a different width in different environments, you will get aligning issues when you use it to format multi-line statements and other things.

An example of this is:

```<code>print(name + " is now " + age +
      "years old!")
</code>```

But in this case the spacing in front of the second line has a very different purpose than that used to indent blocks. Since the purpose here is to align the second line with the print( characters, the best solution here is to use spaces, since they're guaranteed to be as wide as each character in the line above.

To summarize, what is wrong with

...using tabs for indentation where everyone can set their own preferred width

...using spaces for aligning multi-line code where the width does matter

Since most of these questions are typically just tabs vs spaces, I hope to gain some more insight here about the advantages/disadvantages of using each for their own separate use cases.

答:
1. The first downside is that it quickly becomes a mess.

One of the most used Visual Studio extensions is Productivity Power Tools. This extension has an option which alerts a person when the file uses both tabs and spaces, and suggests to replace either tabs by spaces, or spaces by tabs.

This is because when you open a file, you have no visual clue if it's using spaces or tabs. One developer will use only tabs, another developer - only spaces, including for indentation, and another one will use both, in a way you suggested.

When those three developers will work together, given that they all use different style, a fourth developer would have no clue whatsoever if one should use tabs or spaces, and when.

2. The second downside is that today's IDEs are not done for that.

Instead of solving, as you believe, the actual issue, it will only increase it.

Imagine the well-indented/aligned piece of code using your convention:

```<code> →  Some code here(firstArgument,
 →  ···············secondOne,
 →  ···············andTheLast);
</code>```

Actually, in practice, what may happen is:

```<code> →  Some code here(firstArgument,
 →   →   →   →  ···secondOne,
 →   →   →   →  ···andTheLast);
</code>```

because, honestly, I can hardly see myself taping repeatedly Space key, as well as determine exactly the moment where I should stop putting tabs and start using spaces (i.e. one tab, then spaces).

After a few modifications, the same code may quickly become:

```<code> →  Some code here(firstArgument,
 →   →   →   →  ···secondOne,
 →   →   →  ·······modified);
</code>```

Now, when somebody will open the file in an IDE where a tab is equal to two spaces instead of four, that's what he will see:

```<code>→ Some code here(firstArgument,
→ → → → ···secondOne,
→ → → ·······modified);
</code>```

in other words:

```<code>  Some code here(firstArgument,
           secondOne,
             modified);
</code>```

3. Finally, the problem doesn't exist in the first place.

You're assuming that the first argument should be on the same line as the method itself. But the easiest way would be to simply put all arguments to a new line when they are too long. The code above may simply be written like this:

```<code> →  Some code here(
 →   →  firstArgument,
 →   →  secondOne,
 →   →  andTheLast);
</code>```

See? It's all aligned, and would be no matter how much spaces the tab measures.

Conclusion:

Formatting should be the task of the IDE. Developers have already enough work to care about the size of tabs, how much spaces will an IDE insert, etc. The code should be formatted correctly, and displayed correctly on other configurations, without forcing developers to think about it.

By introducing the convention where tabs are used for indentation, and spaces, for alignment, you are mitigating the task of caring about tabs/spaces stuff from IDEs to developers. That's wrong.

Body:
1. The first downside is that it quickly becomes a mess.

One of the most used Visual Studio extensions is Productivity Power Tools. This extension has an option which alerts a person when the file uses both tabs and spaces, and suggests to replace either tabs by spaces, or spaces by tabs.

This is because when you open a file, you have no visual clue if it's using spaces or tabs. One developer will use only tabs, another developer - only spaces, including for indentation, and another one will use both, in a way you suggested.

When those three developers will work together, given that they all use different style, a fourth developer would have no clue whatsoever if one should use tabs or spaces, and when.

2. The second downside is that today's IDEs are not done for that.

Instead of solving, as you believe, the actual issue, it will only increase it.

Imagine the well-indented/aligned piece of code using your convention:

 →  Some code here(firstArgument,
 →  ···············secondOne,
 →  ···············andTheLast);

Actually, in practice, what may happen is:

 →  Some code here(firstArgument,
 →   →   →   →  ···secondOne,
 →   →   →   →  ···andTheLast);

because, honestly, I can hardly see myself taping repeatedly Space key, as well as determine exactly the moment where I should stop putting tabs and start using spaces (i.e. one tab, then spaces).

After a few modifications, the same code may quickly become:

 →  Some code here(firstArgument,
 →   →   →   →  ···secondOne,
 →   →   →  ·······modified);

Now, when somebody will open the file in an IDE where a tab is equal to two spaces instead of four, that's what he will see:

→ Some code here(firstArgument,
→ → → → ···secondOne,
→ → → ·······modified);

in other words:

  Some code here(firstArgument,
           secondOne,
             modified);

3. Finally, the problem doesn't exist in the first place.

You're assuming that the first argument should be on the same line as the method itself. But the easiest way would be to simply put all arguments to a new line when they are too long. The code above may simply be written like this:

 →  Some code here(
 →   →  firstArgument,
 →   →  secondOne,
 →   →  andTheLast);

See? It's all aligned, and would be no matter how much spaces the tab measures.

Conclusion:

Formatting should be the task of the IDE. Developers have already enough work to care about the size of tabs, how much spaces will an IDE insert, etc. The code should be formatted correctly, and displayed correctly on other configurations, without forcing developers to think about it.

By introducing the convention where tabs are used for indentation, and spaces, for alignment, you are mitigating the task of caring about tabs/spaces stuff from IDEs to developers. That's wrong.


答:
In principle, there is nothing wrong with using tabs for block-indentation and spaces for further alignment.

However, there are a few practical problems:

I believe there are editors that try to be helpful and will replace X spaces with a tab if they know you want to use tabs for indentation.

You only need one person on the team with an improperly configured editor to have it all end up in a big mess

for these reasons, it is in practice nearly impossible to build a consistent layout in a code-base that uses tabs for indentation and spaces for layout, so most teams just take the easy way out and require only spaces to be used.
Most programming editors can be configured to insert a number of spaces if you hit the <Tab> key, so as a programmer you can still use that key to get the required indentation.

Title: What are the downsides of mixing tabs and spaces?

Body:
The advantage of using tabs for indentation is that people can configure their editor to use the tab width they are comfortable with. The only argument against this seems to be that people don't want their code to look differently based on editor settings. However, since code is ultimately being written to be easy to read later, it seems much more beneficial to allow the reader to set the width to their preferred value.

On the other hand, because tabs have a different width in different environments, you will get aligning issues when you use it to format multi-line statements and other things.

An example of this is:

```<code>print(name + " is now " + age +
      "years old!")
</code>```

But in this case the spacing in front of the second line has a very different purpose than that used to indent blocks. Since the purpose here is to align the second line with the print( characters, the best solution here is to use spaces, since they're guaranteed to be as wide as each character in the line above.

To summarize, what is wrong with

...using tabs for indentation where everyone can set their own preferred width

...using spaces for aligning multi-line code where the width does matter

Since most of these questions are typically just tabs vs spaces, I hope to gain some more insight here about the advantages/disadvantages of using each for their own separate use cases.


问:
In C# what is lifetime or lifespan of constant variable?
In C# if i declare a constant variable is any memory allocated to it as it acts as a compile time replacement? How long is the variable's life?</p>

答:
Literal consts are compile time replacements. Section 14.16 in the spec I have handy:

A constant expression is an expression that shall be fully evaluated at compile-time.


问:
Fundamental TDD: stuck with writing a test so I can write code that I want
I have a Season class.  This Season has a few properties: among them, a list of Games.  This should be populated from the same source that populated the rest of the Season properties.

I have a test to ensure all items in that list are of type Game.

There is no hard requirement that a Season must contain any Games, so testing that the list is not empty would not be entirely correct -- however, the test Season I'm using has plenty of games in it.

Writing "the minimum amount of code to make a test pass" is already done, because it is the empty list (so there are no not-Game objects).

What would be the fundamental TDD way to get the production code to parse+add games to the Season object?

Would the pragmatic way be to test via the size?

An alternative would be to generate the list of Games in my test, and see if Season.games == list_of_games

The problem with that is that there are a crapload of Foreign relations that will be going into those games, making the test code equivilant to the method that I'm testing -- which I don't think is the way it should work.

Or should I build them "by hand" from the test data -- instead of parsing it?

答:
If I understand correctly, there is a requirement that states "a Season has a list of 0 or more Game objects. This list shall not contain objects of other types".

The easiest way to verify this requirement is via the method to add items to the list. You have a test to verify that it is possible to add Game objects to the list, and you have a second test to verify that adding non-Game objects fails.

(Exception: If you use a statically-type language, like C++, C# or Java, and you use the type system to ensure only Game objects can be added to the list, the second test is effectively performed by the compiler each time you write code to add an item to the list. There is no need then to write the test yourself.)


答:
"The advantage of using tabs for indentation is that people can configure their editor to use the tab width they are comfortable with."

This isn't necessarily true. For example, try configuring the Stack Exchange question and answer editor (which is often used as code editor, instead of copying code to real code editor, editing there, then pasting back to SE) for a specific tab width... There are way too many (newbie) questions especially at SO, where pasted source code contains tabs, and often result is a mess.

This is an example of what's wrong about using tabs in general. More often than not there's a situation where it will be a hassle, when source code becomes a mess. As a result, the whole question about mixing spaces and tabs is somewhat moot, IMO. Just use spaces and life is easier for everybody.

This is a pity really. It would be so elegant if "one tab means one indentation level, tab width is not specified" rule was universally obeyed. But are there any common, "named" indentation styles which have that? Are there any editors where you could do explicitly this, instead of having to specify indentation step in spaces, and then tab width in spaces, separately?


答: No memory is allocated since the value is put directly into code.  The compiler places the constant in the assembly metadata, so the lifetime of the constant is the lifetime of the assembly it's in.</p>

Title: In C# what is lifetime or lifespan of constant variable?

Body: In C# if i declare a constant variable is any memory allocated to it as it acts as a compile time replacement? How long is the variable's life?</p>


问:
Best place to write SQL queries
I've been working on this project for my company. Currently I am embedding my SQL statements inside the program itself as and when they are needed. I do have two seperate classes -

QueryBuilder Class (Contains all the queries)

DbConnection Class (Executes the queries against the database, takes care of connectivity and such)

What this does, is whenever I need to make the smallest adjustment in the query, I have to rebuild the entire application.

I'm hoping there are better ways to deal with this. Somewhere I can store these queries,  get them, pass the parameters as command parameters, then execute them and if I have to, change them without having to rebuild my application.

There are a couple of ideas in my head.

Resource files.

Seperate DLL/Class files - Disadvantage is that, I'll have to rebuild that class if I make a change to that code. But the seperation does have it's advantage.

Text files, May get unmanageable when queries increase.

I'd like to know if there is a better way to deal with this issue and if others have any way of circumventing this.

答:
Resource files, as well as a simple App.config file may do the work.

Having the queries in a separate library is a good way too, especially if you're using it as a plugin (and so you don't have to recompile the application itself, nor even restart it if it's currently running). Since the library contains only constants, compiling it would take at most a few milliseconds.

As for text files, I don't see any benefit, given that the drawback is that you have to reinvent the wheel, i.e. invent your own format, while resource files or App.config already provide that.

Note: be very, very careful. Changing queries is something that should be taken seriously, since it can radically change the behavior of the application (and, why not, wipe out the whole database or table because of a mistake like a forgotten where in a delete from). I would highly recommend not only to recompile the application, but also to rerun the integration tests (and unit tests, if there are unit tests which deal with the database directly).

Security is another concern. You have to be sure that only authorized persons would be able to modify the queries. For example, it would be a disaster to put SQL queries in a way that an ordinary user of a desktop application can modify them: users would imagine they are experts in SQL, modify the queries in a way that it will wipe out their database, and once a disaster occurs, they will blame your product instead of their own stupidity.

Title: Best place to write SQL queries


答:
Extracting data from XML or JSON always seems a bit difficult to do in a TDD manner. You end up with a lot of code that looks like:

```<code>void parseElement(XMLElement element)
{
     name = element.getAttribute("name");
     home_team = teams.lookup( element.getAttribute("home") );
     away_team = teams.lookup( element.getAttribute("away") );
}
</code>```

I can add assertions to check the name and teams, but it feels rather hard to justify. The code is so simple that attempting to verify that it actually works seems not worthwhile. Sure it makes sense to run the code and make sure it doesn't go up in flames, and it makes sense to check any non-trivial actions. But it is really worthwhile asserting each and every assignment? All you are really doing is redunandtly stating the same thing.

This is what I think you are hitting. Its a lot of work to verify that the deserialization was correct, but it doesn't really seem worthwhile. That's why you're hesitant to create a list of  Games to test against. That's a lot of effort for little gain.

My solution is to devise a framework for extracting information, test that, and mostly trust that it works when applied to your objects. I don't know what language you are using, but here is a pythonish version.

```<code>class Season(XMLExtractable):
    XML_FIELDS = {
         'name' : AttributeGetter('name', str),
         'games' : ChildNodeGetter('game', Game),
         ...
    }
</code>```

The XML_FIELDS dict tells me where each attribute should get its data. The objects constructed here have methods to fetch the value. I've tested all those objects, and I can mostly just trust that they work here. Basically, we move all the redundancy into data and operate on that data. We can test our operations on the data, but we'll assume the data is correct.

Title: Fundamental TDD: stuck with writing a test so I can write code that I want

Body:
I have a Season class.  This Season has a few properties: among them, a list of Games.  This should be populated from the same source that populated the rest of the Season properties.

I have a test to ensure all items in that list are of type Game.

There is no hard requirement that a Season must contain any Games, so testing that the list is not empty would not be entirely correct -- however, the test Season I'm using has plenty of games in it.

Writing "the minimum amount of code to make a test pass" is already done, because it is the empty list (so there are no not-Game objects).

What would be the fundamental TDD way to get the production code to parse+add games to the Season object?

Would the pragmatic way be to test via the size?

An alternative would be to generate the list of Games in my test, and see if Season.games == list_of_games

The problem with that is that there are a crapload of Foreign relations that will be going into those games, making the test code equivilant to the method that I'm testing -- which I don't think is the way it should work.

Or should I build them "by hand" from the test data -- instead of parsing it?

Body:
Extracting data from XML or JSON always seems a bit difficult to do in a TDD manner. You end up with a lot of code that looks like:

void parseElement(XMLElement element)
{
     name = element.getAttribute("name");
     home_team = teams.lookup( element.getAttribute("home") );
     away_team = teams.lookup( element.getAttribute("away") );
}

I can add assertions to check the name and teams, but it feels rather hard to justify. The code is so simple that attempting to verify that it actually works seems not worthwhile. Sure it makes sense to run the code and make sure it doesn't go up in flames, and it makes sense to check any non-trivial actions. But it is really worthwhile asserting each and every assignment? All you are really doing is redunandtly stating the same thing.

This is what I think you are hitting. Its a lot of work to verify that the deserialization was correct, but it doesn't really seem worthwhile. That's why you're hesitant to create a list of  Games to test against. That's a lot of effort for little gain.

My solution is to devise a framework for extracting information, test that, and mostly trust that it works when applied to your objects. I don't know what language you are using, but here is a pythonish version.

class Season(XMLExtractable):
    XML_FIELDS = {
         'name' : AttributeGetter('name', str),
         'games' : ChildNodeGetter('game', Game),
         ...
    }

The XML_FIELDS dict tells me where each attribute should get its data. The objects constructed here have methods to fetch the value. I've tested all those objects, and I can mostly just trust that they work here. Basically, we move all the redundancy into data and operate on that data. We can test our operations on the data, but we'll assume the data is correct.


问:
Working with Multiple Versions of Websites (Git)
I have a main template like website I have made that will allow me to quickly roll out and make new websites on demand when I need them, for my personal use.

I'm wondering what is the best practice when using a Git repo is for this practice. My goal is that if for example down the road I'd like to make a change to all the sites at once, I can simply change the master (Repo) and have this change applied to all other versions of the template.

Currently I have my template hosted privately on BitBucket. I'm assuming it is best to git clone the repo, and then makes changes on the clone. Then when I make changes to the template I do a git pull on the sites. Is this is the ideal approach, or are there better methods to do this?

答:
I think you're confusing the role of source control with the role of software architecture and proper dependency management.

If you've got a templating system, or just a template, that you want to be able to roll out to multiple sites, then you design it as a standalone framework which can be customized in certain predictable ways. This is how CMSes like WordPress already work. If you need to change the template and want that change to propagate to all sites, then you simply release a new version of the framework and update the sites that are based on it.

Cloning a repository is primarily meant as a tool to get multiple developers working on the same project. I think you're going to run into many headaches in the more distant future if you try to use that model for working on several completely different projects. Without the encapsulation provided by a real framework, it's almost certain that changes will be made to the templated sites that essentially rev-lock them, and while that's always a risk, it's exacerbated here by the ambiguity between modification and extension, a clear violation of the Open-Closed Principle. While that principle is specific to OOP, the general concept applies to all software.

Branches would probably make for a model that's easier to understand, although technically in Git you can still do all of the same things with multiple repositories, albeit more awkwardly, by simply adding local ones as remotes. I'm not sure why you'd want to, but it's possible.

It's not good design, though. In order to keep the sites maintainable, you want a clear separation of concerns between framework/templates, content/customization, and site deployment. It sounds like you're conflating them all and I'd urge you to reconsider before adopting a risky and bug-prone approach that depends entirely on source control. Git is great but it's not perfect, and even when a merge has 0 conflicts it can still break your site if the changes in both repositories are significant.


答:
What you might want to look at is multiple repositories here forked off of a main development template line. This lets you keep some centralized templating while letting the downstream projects keep a bit more in control of their own destiny -- including holding patches to the core if you need to roll that way.

We used a strategy like this for a half-dozen or so wordpress sites to great effect, we could get worpdress security updates deployed across all projects in minutes. I will echo @Aaronaught here -- unless you are very disciplined in the way you develop the core template this will be tricky to pull off. Wordpress, over the years, has got that discipline so it worked out great there.

Title: Working with Multiple Versions of Websites (Git)

Body:
I have a main template like website I have made that will allow me to quickly roll out and make new websites on demand when I need them, for my personal use.

I'm wondering what is the best practice when using a Git repo is for this practice. My goal is that if for example down the road I'd like to make a change to all the sites at once, I can simply change the master (Repo) and have this change applied to all other versions of the template.

Currently I have my template hosted privately on BitBucket. I'm assuming it is best to git clone the repo, and then makes changes on the clone. Then when I make changes to the template I do a git pull on the sites. Is this is the ideal approach, or are there better methods to do this?


问:
What is the origin and meaning of the phrase “Lambda the ultimate?”
I've been messing around with functional programming languages for a few years, and I keep encountering this phrase. For example, it is a chapter of "The Little Schemer, which certainly predates the blog by this name. (No, the chapter doesn't help answer my question.)

I understand what lambda means, the idea of an anonymous function is both simple and powerful, but I fail to understand what "the ultimate" means in this context.

Places that I've seen this phrase:

The title of chapter 8 of The Little Schemer

A blog: http://lambda-the-ultimate.org/

A series of "Lambda the ultimate X" papers: http://library.readscheme.org/page1.html (archived)

I feel like I'm missing a reference here, can anyone help?

答:
Lambda The Ultimate refers to the idea that the lambdas of lambda-calculus can effectively implement every builtin concept in every programming language, past, present, and future.  Classes, Modules, Packages, Objects, Methods, Control-Flow, Data Structures, Macros, Continuations, Coroutines, Generators, List Comprehensions, Streams, and so on.

As it happens, that ultimate nature includes standing for an Anonymous Function.  But lambdas are not, at their core, limited to just anonymous functions.  They get taught that way, but the essence of lambda goes far deeper than mathematical functions without names. In other words, I take issue with:

I understand what lambda means, the idea of an anonymous function is
  both simple and powerful, but I fail to understand what "the ultimate"
  means in this context.

As a practical matter, the use of lambdas as syntactic abstractions ('macros'), which are not call-by-value/applicative (which mathematical functions are), is absolutely crucial to buying into the idea that lambdas really can serve as the core of every programming language processing system.

For Theory: There is an interesting connection with Bertrand Russell's paradox and the Axioms of Comprehension (and Extension) in naive set theory.  A lambda is to functions what set-builder notation is to sets: lambdas are function-builder notation.  There is an important difference, usually ignored, between (lambda (x) (* x x)) and what that evaluates to (the function that squares).  If one fails to distinguish between the two in general, that is, between the notation and the denotation (a mistake that Church and Frege both made) then one runs afoul of paradoxes. For sets and Frege, it is Bertrand Russell's Barber of Seville that illustrates the error; for functions and Church, it is Alan Turing's Halting Oracle.

Note that the paradoxes are good, practical, things.  We want EVAL to be expressible, and we want lambdas to mean more than just functions.  That assuming the opposite leads to contradiction is the desirable result; it serves as a nice sanity test: lambdas can hardly be ultimate if they only express mere functions.

Racket (formerly PLT Scheme) continues to prosecute the idea that practical programming languages really can be built, from the ground up, on 'just lambda'.

Kernel, by Shutt, argues that lambda is not really the ultimate abstraction. He argues there is one concept more primitive still (for Greek, dubbed vau) which was known to Sussman as FEXPR.

Felleisin and company (for Racket) get much of the power of Shutt's vau by using the concept of phases, or metalevels, which approximately means running the source code through multiple stages of translation (as with preprocessing C, but using the same language at each 'step', and the 'steps' are not actually entirely distinct in time).  (So, they argue that a lambda in a higher phase approximates a vau well enough.)  In fact, they argue that phases are better than FEXPRs, precisely for being more limited; in short, "FEXPRs are too powerful" (see Wand's work, which Shutt argues against).

Brian Smith's 3-Lisp, "Procedural reflection in programming languages", attempts a rigorous reformulation of the theory of LISP-like languages along the lines of sharply distinguishing notations (symbols/language/programs) from denotations (things/referrents/values/results). http://dspace.mit.edu/handle/1721.1/15961

Mitchell Wand's "The Theory of FEXPRs is Trivial" sends more nails into the (temporary?) coffin that Kent Pittman wrought for FEXPRs (who, like Felleisen, argues against FEXPRs as making compilation too hard).

Paul Graham argues with strength and at length in "On Lisp" that the real power is lambdas as transformers of syntax (macros), rather than as transformers of values (mathematical functions).  Plotkin's development of the applicative lambda-calculus could be taken as somewhat contrasting, because Plotkin limits Church's calculus to its call-by-value/applicative subset.  Of course, handling the applicative part efficiently is very important, so it is important to develop theory specialized to that use of lambda.  (Plotkin and Graham do not argue against one another.)

In fact, in general, the notion of Lambda as Ultimate is just one such twist on the eternal debate between efficiency and expressiveness; it is the position that lambda is the ultimate tool for expressiveness, and, given enough study, will ultimately prove to be the ultimate tool for efficiency as well.  In other words, we can, if we want to, see the future of programming languages as nothing more and nothing less than the study of how to efficiently implement all of the practically relevant fragments of the lambda calculus.

Landin's "The Next 700 Programming Languages", http://www.cs.cmu.edu/~crary/819-f09/Landin66.pdf, is an accessible reference that contributes to the development of that concept that Lambda is Ultimate.

ContentLicense: CC BY-SA 4.0


问:
Is garbage collection necessary?
Do any languages really need garbage collection? Is there not a way to figure out when a object should be destroyed? I haven't had leaks in C++ and i dont use smart pointers or reference counters or anything special. I confirm this by attaching something for leak detection: whether its built in to the IDE or a header that uses magic (defines) to overloads new/free.

Is garbage collection necessary, or is it possible to have a leak-free application in a language without placing the memory burden on the programmer?

答:
Garbage collection per se is not necessary to the virtual machine of languages where it is commonly used. In such languages the assumption is actually that objects live indefinitely after creation. In one of the LISP machines of the '80's there was originally no garbage collection. Instead, one ran the machine until memory ran out, and then saved the image, restarted the machine and reloaded the image. Saving the image only saved the reachable data, so when you reloaded you'd be using less memory. After a little while a garbage collector was added to this system. For one reference of this, see "Evolution of LISP", "Evolution of LISP" in PDF form, page 27

Today I think it would be completely reasonable to prototype a language like that with no garbage collector, but eventually one will need to reclaim unused objects or else run out of memory.

Also, many neophytes have wondered if there was some way to avoid all this with the stack. This has been considered in academia using a derivation of arena-based memory management called Region Inference where the compiler determines the lives of references to objects based on scope information, which is where the stack comes in, and type information, which in a language like ML is already being analyzed. Some programs run more slowly under this system, but many do run faster, according to citations in the Wikipedia article.

Title: Is garbage collection necessary?


问:
Could we build a functional computer?
As mush as FP has done, in the end, all our programs are structured.
That is, it doesn't matter how pure or functional we make a them - they are always translated to assembly,
so what actually runs behind the hoods are instructions, states and loops.
We are kind of emulating FP.

As a hardware noob, my question is: why aren't we using computer architectures that actually computed things in a functional style? For example, a computer could consist of primitive "functional chips" such as "concat", "map" and "reduce", and a program would merely tell the computer how to flow the data between those chips in order to compute the desired result, such as in concatenative languages.

This doesn't really make sense but might illustrate what I'm thinking.

答:
They do make computers like that.  It's called an FPGA.  Of course, FPGAs support both sequential and combinational logic, but there's nothing preventing you from just using the combinational portion as you're suggesting.

In practice, however, sequential logic (the kind with state) is extremely useful even at the chip level.  For one thing, it significantly reduces the number of logic gates required to solve a problem.  For another, it solves a lot of design problems related to signals having different propagation delays.

If you're interested in that sort of thing, FPGAs are well worth checking out.  There's an inexpensive arduino-like board called papilio that's great for beginners.  People use it for everything from robot control to bitcoin mining.

Title: Could we build a functional computer?


问:
Overriding - Access to Members with Reference Reassignment
I have recently been moving through a couple of books in order to teach myself Java and have, fortunately, mostly due to luck, encountered very few difficulties. That has just changed.

I read a section on the following under inheritance and the whole superclass subclass setup

When a new superclass object is created, it is, like all objects, assigned a reference (superReference in this example)

If a new subclass object (with the defining subclass extending the superclass) is created, and then the superReference reference is set to refer to that instead of the original object, it is my understanding that, since the reference is made for a superclass, only members defined by the superclass may be accessed from the subclass.

First - is this correct?

Second:
If I am overriding a method and therefore have one in the super and one in the sub, and I create a superclass object and then assign its reference, as I did above, to a subclass object, by the principle called something like Dynamic Method Dispatch, a called overridden method should default to accessing the subclass method right?

Well, my question is:

If a reference to a superclass-object is retooled for a subclass-object and will deny direct object.member access to subclass-defined members, only supporting superclass-defined members, how can, if a superclass reference is retooled for a subclass object, an overridden method apply to the subclass-object if access is limited by the superclass-originated-reference

答:
You must distinguish between the (dynamic) run-time system in the VM, which holds actual instances of classes, and the (static) text of your program, which contains variables that hold references to objects. Thanks to run-time type information, an object always knows which class it belongs to; when the JVM executes the appropriate invoke* primitive, it will happily run any method of this class. The program text, on the other hand, only knows an upper bound on the type of any object that will be held by a reference.

The only difficulty with accessing methods in an object is to get the correct opcode issued. This is where the compiler comes in. The type system imposes limits on what your programs can do to references; in particular, it doesn't allow you to issue any method call that would be possible at run-time. Instead, it only allows method calls that it can prove to be correct at run-time. Because symbolic logic is incomplete (disclaimer: this is a terrible oversimplification!), no compiler can prove all things about your program that you can see to be true. Therefore it is common to get into situations where the programmer knows that a particular reference will be of a specific type, but the compiler cannot follow their logic and forbids a call that would cause no trouble.

This is a trade-off that buys improved program correctness (by disallowing a whole class of previously very common errors) at the cost of some flexibility. Note that if you're really, really sure that you know more than the compiler, you can cast a reference to a subtype and then invoke the method you wanted; if you were wrong, a ClassCastException occurs, but if you were right, the method is invoked by the run-time system without complaint.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Everyday meetings:

```<code>(meeting duration in hours) x (Y team members) x (average salary per hour) = ...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Everyday meetings:

(meeting duration in hours) x (Y team members) x (average salary per hour) = ...


问:
Modern REPL for Haskell - is anybody working on it?
It's time Haskell had a modern REPL like Mathematica's (or better).

Make each calculation run in a separate thread, so user has control over each computation box's resources (ability to pause, play, cancel, replay, set memory/stack/time limits,  etc). Allow for graphics output as well (how?).

Then detach these boxes from today's GHCi 1D canvas into 2D space, allow the boxes to be cloned (a clone receives same source, waits for the user to press "play" button...), their source code edited (allow for more than one line, too).

Then allow for these boxes to be assembled into chains - or networks - if types fit (deduce new constraints, if any, as in usual type inference). Make the joined boxes into one function/module, automatically produce the resulting source file, etc., etc.

Is this feasible? Can a community of experts self-organize to produce something like that, "for great good"?

答:
Yes.

ghc extension for IPython:

http://bfj7.com/posts/2013-04-22-innovation-week-days-1-2.html

Wolfgang Lambda:

http://www.reddit.com/r/haskell/comments/1d0151/haskell_in_ipython/c9mwa11


问:
Security through obscurity and storing unencrypted passwords
What exactly does "Security through obscurity" means in the context of stroing unencrypted passwords?

I'm using a small program (I won't name it, to not enlarge enough large shame on its author) that uses my Google account for some tasks. I've noticed, that it stores my password in plain-text unencrypted file. Just a string, clearly seen to everyone, that can drag&drop it to Notepad or use F3 in Total Commander.

I have risen a ticket asking program author to fix this ASAP. I haven't got any reply yet, but my issue got one comment, that includes only above mentioned link to Wikipedia's "Security through obscurity" page.

How should I understand this comment? Is it pro or con my issue? At first I thought, that it supports my statement of fixing this ASAP. But then I found a Eric Raymond's Fetchmail example (in "The Cathedral and the Bazaar"), who refused to implement config file encryption (passwords are stored in config file for Fetchmail), claiming that it is up to the user to assure security by not letting anyone "from the outside" access that configuration file.

This statement (or refusal) is often brought as example of Security through obscurity. And looking from this point of view, I'm completely wrong and that program author is right. He do not have to implement encryption of file with my password, it can remain there, stored unencrypted and it is I, who is responsible for assuring security by not giving anyone access to this file or by deleting it each time I stop using that soft.

(another question is, how can I achieve this on system as unsecure as Windows itself?)

These seems to be in a complete opposition, to what I've been told and learnt for years, so I would like to ask more experienced developers, who is right here and how exactly I should understand "StO"?

答:
"Security through obscurity" refers to the mistaken attempt to provide security by keeping the details of a mechanism secret (algorithms, cipher schemes, protocols, etc.). This is generally considered bad practice. Security practitioners should always assume that the enemy knows all details of their mechanisms, and build systems that remain secure even then.

But passwords, tokens, etc. should obviously be kept secret, in fact they are the only parts of secure systems that should be considered secret.

The principle therefore supports your point of view. But this is the Internet! It is entirely possible, that someone misunderstands this term badly enough, to think, that it refutes your ticket.


问:
Functional metrics in Agile methodologies
I'm preparing a presentation about Agile methodology for managers (not programmers) and I'm looking that, from a side, the Agile talks about functional perspective*^ (in Scrum we have planning game) but, from other side, it lacks any (standard) definition of **functional measure.

In my opinion it's strange: how I can give a magnitude of effort by functional needs of user if Agile methodology doesn't use a formal/univocal definition of functional needs and doesn't adopt any formal functional measurement (Function Point, COSMIC).

If you have played to planning game or User Story, what was your measure unit? Have you used the FP or COSMIC?

答:
The planning of a scrum sprint has two components.
On the one hand, you estimate the complexity of the stories and tasks on the backlog in the unit of Story Points. More on that later.
On the other hand, you how many story points the team can deliver in one sprint. This is called the velocity and it is based on the historical data of how many story points the team delivered in the previous sprints. Here, you can also factor in things like known absences, due to, for example, (public) holidays.

Story Points are a relative measure indicating how much effort a given task will need when compared to the other tasks in the project. The first few times you may need to designate a simple (but non-trivial) task as 'reference task' and define 1 Story Point as being the effort needed to complete that task, but after a while people will start saying: "Hey, this task/story looks similar to that one we did two sprints ago. It should have the same number of Story Points."

You should be aware of the risk of Story Point inflation. This is a risk with people who are used to estimate effort in manhours and it happens when they start giving consistently higher estimates than before, because previously they forgot to factor something in (for example, testing). If you consistently forget to factor something in in your Story Point estimates, then you should not adapt your estimates because the fact that you consistently forgot something will express itself in the velocity of the team, so adapting your estimates results in a double compensation.

And for managers especially, it is folly to think you can compare Story Points from different teams. If you have multiple teams working on a project, it is very well possible that their velocities differ by as much as a factor 3, but that the team with the lowest velocity number produces the most value, just because their unit of measurement (the Story Point) is so much bigger.


答:
From Eric Raymond's design notes on Fetchmail:

Password encryption in .fetchmailrc

The reason there's no facility to store passwords encrypted in the .fetchmailrc file is because this doesn't actually add protection.

Anyone who's acquired the 0600 permissions needed to read your .fetchmailrc file will be able to run fetchmail as you anyway -- and if it's your password they're after, they'd be able to rip the necessary decoder out of the fetchmail code itself to get it.

All .fetchmailrc encryption would do is give a false sense of security to people who don't think very hard.

The problem here is that if someone has access to the encrypted configuration file, they already have everything they need to impersonate you, as the only other thing they need is fetchmail itself. Therefore implementing password encryption on fetchmail is in fact "security through obscurity", and completely useless.

I suspect that's what the commenter meant. Regardless, you shouldn't really lose any sleep on the comment and wait for the developers to reply officially. If they refuse to encrypt the password, you could post a followup feature request asking for a way to use the tool without storing the password (on disk).

Title: Security through obscurity and storing unencrypted passwords

Body:
What exactly does "Security through obscurity" means in the context of stroing unencrypted passwords?

I'm using a small program (I won't name it, to not enlarge enough large shame on its author) that uses my Google account for some tasks. I've noticed, that it stores my password in plain-text unencrypted file. Just a string, clearly seen to everyone, that can drag&drop it to Notepad or use F3 in Total Commander.

I have risen a ticket asking program author to fix this ASAP. I haven't got any reply yet, but my issue got one comment, that includes only above mentioned link to Wikipedia's "Security through obscurity" page.

How should I understand this comment? Is it pro or con my issue? At first I thought, that it supports my statement of fixing this ASAP. But then I found a Eric Raymond's Fetchmail example (in "The Cathedral and the Bazaar"), who refused to implement config file encryption (passwords are stored in config file for Fetchmail), claiming that it is up to the user to assure security by not letting anyone "from the outside" access that configuration file.

This statement (or refusal) is often brought as example of Security through obscurity. And looking from this point of view, I'm completely wrong and that program author is right. He do not have to implement encryption of file with my password, it can remain there, stored unencrypted and it is I, who is responsible for assuring security by not giving anyone access to this file or by deleting it each time I stop using that soft.

(another question is, how can I achieve this on system as unsecure as Windows itself?)

These seems to be in a complete opposition, to what I've been told and learnt for years, so I would like to ask more experienced developers, who is right here and how exactly I should understand "StO"?


问:
How does Jump Point Search algorithm work and why is it so efficient?
While trying out the below applet, I saw that this path finding algorithm called Jump Point Search yields significantly faster result than A* and Dijkstra.

http://qiao.github.io/PathFinding.js/visual/

A*: 46 seconds

Dijkstra: 1 minute 39 seconds

Jump Point Search: Less than 3 seconds

Needless to say, I'm quite astounded at the result. From visual representation, Jump Point Search seems to be making a lot of random guesses (probably very intelligent ones) at finding the path (from the block selection at least), but I haven't yet found a test case where this algorithm yielded worse results than A* and Dijkstra.

How does this algorithm work? How is it so efficient in comparison with A* and Dijkstra?

答:
The basic idea is that JPS allows to throw away many candidate paths early, therefore reducing the amount of computations required.

In many maps, multiple paths with the same cost lead to same destination, such as a game map with large open areas. JSP allows pruning those paths.

An in-depth explanation can be found here.


问:
Show all definitions in Scheme?
I want to see all user-made definitions in a Scheme REPL, both loaded from files and entered at the REPL. Is there any way to "dump all definitions"?

E.g. if there is:

```<code>    (define (plusone x) (+ 1 x))
    (define (plustwo x) (+ 2 x))
    (define (plusthree x) (+ 3 x))
</code>```

then I want to see all of these definitions, but only those defined by the "user" - something like ",showmealldefs" or thelike. Can this be done, and if there is no general way, can this be done in Gambit-C?

(I tried (apropos ""), and this is not what I mean.)

答:
You're looking to manipulate the environment. Support of first class environments is not common in the various Schemes. MIT Scheme has support (I believe the function is gst), but I don't believe that Gambit-C does. Some discussion about first class environments are here.

If you were to write your own metacircular Scheme (Scheme written in Scheme) you'd write an eval function and an apply function which would have some sort of environment passed along with them. Since the environment would probably be an association list of name/function, you'd be able to manipulate them as you wished. However, I don't think you're going to find what you're looking for in most full-fledged Schemes because of performance/implementation reasons.

Title: Show all definitions in Scheme?


答:
Essentiall, yes, analog computers worked that way: you were changing parameters and an electric current was modified accordingly. That is what made them "faster", for a time, in the 1950s - you did not care about the slow creation and modification of separate "states" as in the olden digital behemoths.

And arguably, quantum computers might work that way, too: if the state of some quantum phenomena depends on the state of others, then changing some "initial" state will change the following states simultaneously - no "states" inbetween.

Title: Could we build a functional computer?

Body:
As mush as FP has done, in the end, all our programs are structured.
That is, it doesn't matter how pure or functional we make a them - they are always translated to assembly,
so what actually runs behind the hoods are instructions, states and loops.
We are kind of emulating FP.

As a hardware noob, my question is: why aren't we using computer architectures that actually computed things in a functional style? For example, a computer could consist of primitive "functional chips" such as "concat", "map" and "reduce", and a program would merely tell the computer how to flow the data between those chips in order to compute the desired result, such as in concatenative languages.

This doesn't really make sense but might illustrate what I'm thinking.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答: Being required to indent all code by four spaces ;)</p>


问:
Why are constructors not inherited?
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?

答:
You can use:

```<code>MyClass() : Base()
</code>```

Are you asking why you have to do this?

The sub-class could have additional properties which might need to be initialised in the constructor, or it might initialise the base class variables in a different way.

How else would you create the sub-type object?

Title: Why are constructors not inherited?

Body:
You can use:

MyClass() : Base()

Are you asking why you have to do this?

The sub-class could have additional properties which might need to be initialised in the constructor, or it might initialise the base class variables in a different way.

How else would you create the sub-type object?