问:
Using PDO with MVC
I asked this question at stackoverflow and received no response (closed as duplicate with no answer). I'm experimenting with OOP and I have the following basic MVC layout:

```<code>class Model {
    // do database stuff
}

class View {
    public function load($filename, $data = array()) {
        if(!empty($data)) {
            extract($data);
        }

        require_once('views/header.php');
        require_once("views/$filename");
        require_once('views/footer.php');
    }
}

class Controller {
    public $model;
    public $view;

    function __construct() {
        $this->model = new Model();
        $this->view = new View();

        // determine what page we're on
        $page = isset($_GET['view']) ? $_GET['view'] : 'home';
        $this->display($page);
    }

    public function display($page) {
        switch($page) {
            case 'home':
                $this->view->load('home.php');
            break;
        }
    }
}
</code>```

These classes are brought together in my setup file:

```<code>// start session
session_start();

require_once('Model.php');
require_once('View.php');
require_once('Controller.php');

new Controller();
</code>```

Now where do I place my database connection code and how do I pass the connection onto the model?

```<code>try {
    $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err) {
    die($err->getMessage());
}
</code>```

I've read about Dependency Injection, factories and miscellaneous other design patterns talking about keeping SQL out of the model, but it's all over my head using abstract examples. Can someone please just show me a straight-forward practical example?

答:
Like Falcon mentioned, the data access code should be in the Controller, at least the only access to a service layer or data access layer should be done from the Controller. The Model is mostly used to structure the data you want to show in the view, in other words it should mimic your domain model. Typically, you would query data from the database, create a Model with the data, load the Model onto the View, all within the your Controller (in general terms, implementation might differ).

In your example, it might look like this (again, just an overview example),

```<code>class Model {
    // domain model properties: id, name, age...
}

class View {
    // view stuff
}

class Repository {
    function __construct() {
       // connect to database and return a viable connection for data access
    }
}

class Controller {
    public $model;
    public $view;
    public $repository

    function __construct() {
        $this->repository = new Repository();

        $this->model = new Model();
        $this->model = $this->repository.LoadModelFromDatabase();

        // load your model onto the view
        $this->view = new View($this->model);

        // determine what page we're on
        $page = isset($_GET['view']) ? $_GET['view'] : 'home';

        // display your view with your model loaded
        $this->display($page);
     }

     public function display($page) {
         switch($page) {
             case 'home':
                 $this->view->load('home.php');
             break;
     }
}
</code>```

You should follow a similar pattern for other Views and Models, using your Controller to coordinate access to the database and interaction with your program.

Title: Using PDO with MVC

Body:
Like Falcon mentioned, the data access code should be in the Controller, at least the only access to a service layer or data access layer should be done from the Controller. The Model is mostly used to structure the data you want to show in the view, in other words it should mimic your domain model. Typically, you would query data from the database, create a Model with the data, load the Model onto the View, all within the your Controller (in general terms, implementation might differ).

In your example, it might look like this (again, just an overview example),

class Model {
    // domain model properties: id, name, age...
}

class View {
    // view stuff
}

class Repository {
    function __construct() {
       // connect to database and return a viable connection for data access
    }
}

class Controller {
    public $model;
    public $view;
    public $repository

    function __construct() {
        $this->repository = new Repository();

        $this->model = new Model();
        $this->model = $this->repository.LoadModelFromDatabase();

        // load your model onto the view
        $this->view = new View($this->model);

        // determine what page we're on
        $page = isset($_GET['view']) ? $_GET['view'] : 'home';

        // display your view with your model loaded
        $this->display($page);
     }

     public function display($page) {
         switch($page) {
             case 'home':
                 $this->view->load('home.php');
             break;
     }
}

You should follow a similar pattern for other Views and Models, using your Controller to coordinate access to the database and interaction with your program.


问:
Multiple parameters vs single parameter(object with multiple properties)
I have an Entity Student with following properties - (name, joinedOn, birthday, age, batch, etc.) and a function fetchStudents(<params>).
I want to fetch students based on multiple filters.

In my method I have two ways to pass filters.

Pass all filters as params to the method

Make a class StudentCriteria with filters as fields and then pass
    the object of this class

While working in java I always go with the second option but recently I'm working in php and I was advised to go with the first way. I am unable to figure out which way is better in maintaining the code, reusability and performance wise. Thanks.

答:
"Clean Code" says you have two have as few parameters as possible.

I use up to three parameters.

I recommend you use the StudentSearchCriteria class.

ContentLicense: CC BY-SA 3.0


答: I tend to use optional parameters and have some function filters to only check against the parameters I pass to the function. It will avoid the hassle of having a StudentSearchCriteria class, while keeping function calls fairly short.

Title: Multiple parameters vs single parameter(object with multiple properties)

Body:
I have an Entity Student with following properties - (name, joinedOn, birthday, age, batch, etc.) and a function fetchStudents(<params>).
I want to fetch students based on multiple filters.

In my method I have two ways to pass filters.

Pass all filters as params to the method

Make a class StudentCriteria with filters as fields and then pass
    the object of this class

While working in java I always go with the second option but recently I'm working in php and I was advised to go with the first way. I am unable to figure out which way is better in maintaining the code, reusability and performance wise. Thanks.


问:
What steps should be taken to make sure your software is usable by disabled people?
I want to make sure a piece of software I am writing is usable by people with various disabilities such as blindness and an inability to use a mouse and / or keyboard.

Unfortunately I have no experience with things such as screen readers or other methods that disabled people use to make using a computer easier / possible. I've never really had much experience with disabilities at all and unfortunately I don't know any disabled people who I can ask.

I was wondering what other people do to make sure that their software is available to a wide range of people with varying abilities?

This seems to be a subject matter that is often ignored by developers and I think it is a real shame.

Edit: If anyone has any specific information related to desktop development in addition to the information already provided in the answers below I would be grateful. Particularly methods that apply to cross platform development on Windows, Mac OS X and Linux.

答:
You can start with usability.gov.  There are also formal guidelines from the W3 accessibility initiative.

After you read the scores of documents from the 90's on usability, you can test some things like colorblindness with color filters.  Colorfilter lets your view a page or image as someone with different types of colorblindness would.  The W3 group also maintains a list of tools that are helpful when designing for inclusion.

For screen readers (and in general), don't link to cats.  Rather, link to a search for cats.  This is especially important for screen readers which often scan a document for all the links and read them back to the user.  It's not helpful to anyone if they just hear, "link, link, link, a link, this site, go here, link" repeated back to them from their screen reader.

Lastly, whether for disabled people or not, you should always make your applications and websites easily navigable with only a keyboard.


答:
I personally don't like having too many optional arguments if I can get away with it.  I can find it quite hard to read and when you end up passing things like

```<code>getOption($option1, "",0,"")
</code>```

where the method declaration is actually something like (of course real parameter names would be better named)

```<code>getOption($myoption, $textStr, $numberOf, %description = "", $name = "", $typeOf = 0)
</code>```

It's hard to know from reading this what exactly the values are and also what you are setting or leaving out.  Every time I want to call that method I have to be very careful to set the right parameters in the right place.

A possible alternative is to use something like the Builder pattern where you are building up the criteria you wish to add explicitly. For those parameters which are required you make part of the constructor.  For those optional ones you have a method to add.

Something like:

```<code>class StudentEnrollmentCriteriaBuilder {
   function __construct($id) {
      // id is always required for this criteria
   }

   function getCriteria() {
      // return the built up criteria
   }

   function addNameFilter($name) {
      // add the name to the filter
      return $this;
   }

   function addSexFilter($sex) {
      // add sex type as a filter

      return $this;
   }

   // etc
}
</code>```

I guess you could then use it like

```<code>$criteria = new StudentEnrollmentCriteriaBuilder ($id);

$query = $criteria.addNameFilter('bob').addSexFilter('M').getCriteria();
</code>```

// do stuff

Each method would be responsible for adding the filter if valid.  So I guess in the case of the name if it was an empty name you would not add it as a filter etc as it wasn't required, or throw an exception etc etc

If it came down to it, where there are many properties I prefer the object option.  If some are required at least make them part of the constructor.  If you at least made the optional ones method based you could add validity checking on the data at that point, or leave it up to the user of the object to do.

Just my 1 1/2 cents.

Body:
I personally don't like having too many optional arguments if I can get away with it.  I can find it quite hard to read and when you end up passing things like

getOption($option1, "",0,"")

where the method declaration is actually something like (of course real parameter names would be better named)

getOption($myoption, $textStr, $numberOf, %description = "", $name = "", $typeOf = 0)

It's hard to know from reading this what exactly the values are and also what you are setting or leaving out.  Every time I want to call that method I have to be very careful to set the right parameters in the right place.

A possible alternative is to use something like the Builder pattern where you are building up the criteria you wish to add explicitly. For those parameters which are required you make part of the constructor.  For those optional ones you have a method to add.

Something like:

class StudentEnrollmentCriteriaBuilder {
   function __construct($id) {
      // id is always required for this criteria
   }

   function getCriteria() {
      // return the built up criteria
   }

   function addNameFilter($name) {
      // add the name to the filter
      return $this;
   }

   function addSexFilter($sex) {
      // add sex type as a filter

      return $this;
   }

   // etc
}

I guess you could then use it like

$criteria = new StudentEnrollmentCriteriaBuilder ($id);

$query = $criteria.addNameFilter('bob').addSexFilter('M').getCriteria();

// do stuff

Each method would be responsible for adding the filter if valid.  So I guess in the case of the name if it was an empty name you would not add it as a filter etc as it wasn't required, or throw an exception etc etc

If it came down to it, where there are many properties I prefer the object option.  If some are required at least make them part of the constructor.  If you at least made the optional ones method based you could add validity checking on the data at that point, or leave it up to the user of the object to do.

Just my 1 1/2 cents.


答:
You don't specifically mention web stuff, but that's what my answer is targeted at.

Use the W3C's Accessibility Guidelines. Most of it is fairly straightforward, but it's important to understand it and implement it. In particular, focus on good semantic markup. E.g. actually use H1, H2, etc, instead of making a DIV look like an H1.

Create a site that works well without JavaScript, and then enhance some of the functions with JavaScript.

Using something like Web Developer's Toolbar, disable JavaScript and disable all styles. Refresh the page and imagine what it would be like for a screen-reader to try and convey it in any meaningful way to someone with vision challenges.

Make sure that all links work well with JS turned off. JS is evil when used for link activation. (This advice applies to search engine bots, too.)

Find a website that is talking about accessibility issues (e.g. accessibilityforum.com and ask for volunteers to test your site (or app, or whatever).

Title: What steps should be taken to make sure your software is usable by disabled people?

Body:
I want to make sure a piece of software I am writing is usable by people with various disabilities such as blindness and an inability to use a mouse and / or keyboard.

Unfortunately I have no experience with things such as screen readers or other methods that disabled people use to make using a computer easier / possible. I've never really had much experience with disabilities at all and unfortunately I don't know any disabled people who I can ask.

I was wondering what other people do to make sure that their software is available to a wide range of people with varying abilities?

This seems to be a subject matter that is often ignored by developers and I think it is a real shame.

Edit: If anyone has any specific information related to desktop development in addition to the information already provided in the answers below I would be grateful. Particularly methods that apply to cross platform development on Windows, Mac OS X and Linux.


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
What I've found important is to read the preface.  Often the author(s) will give you some suggestion on how to read the book.  Also, I try to read the introductory chapters straight through, even if I think I already have the necessary background.  I find that it often helps familiarize me with the book's vocabulary (e.g., "When we say 'server', we mean the physical hardware; when we say 'Web server' we mean the application server instance.").

I also have to fight the urge to skim.  Reading for comprehension is different from reading for reference.  Slow down, and take a break every couple of pages and review what you've just read.  Re-reading challenging sections often feels like a waste of time, but it pays off in the long run because it helps me comprehend later sections faster.

Title: How do people read big technical books?

ContentLicense: CC BY-SA 2.5


问:
What is the meaning of # in R5RS Scheme number literals
There is a partial answer on Stack Overflow, but I'm asking something a teeny bit more specific than the answers there.

So... Does the formal semantics (Section 7.2) specify the meaning of such a numeric literal? Does it specify the meaning of numeric operations on the value resulting from interpreting the literal?

If yes, what are the meanings (in English -- denotational semantics is all greek characters to me :))?

答:
Reading from the standard:

If the written representation of a number has no exactness prefix, the
  constant may be either inexact or exact. It is inexact if it contains
  a decimal point, an exponent, or a ``#'' character in the place of a
  digit, otherwise it is exact.

Basically remember they amount to insignificant figures. The compiler isn't required to have any specific value for them there but it must put something. (most use zero). It's a way of making a number imprecise.


问:
Does TDD lead to good design?
I'm in transition from "writing unit tests" state to TDD.

I saw as Johannes Brodwall creates quite acceptable design from avoiding any of architecture phase before. I'll ask him soon if it was real improvisation or he had some thoughts upfront.

I also clearly understand that everyone has experience that prevents to write explicit design bad patterns.

But after participating in code retreat I hardly believe that writing test first could save us from mistakes. But I also believe that tests after code will lead to mistakes much faster.

So this night question is asking for people who is using TDD for a long time share their experience about results of design without upfront thinking. If they really practice it and get mostly suitable design. Or it's my small understanding about TDD and probably agile.

答:
From experience:

TDD does not necessarily lead to good design. It's possible and really easy to get poorly designed program using TDD.

TDD is just a tool to help us design faster using refactoring, it will never make the design of the program appear magically. TDD is a design help tool. The quality of the design you will get out of TDD depend largely on the capacity of the developer to use refactoring to Design Patterns, or refactoring to SOLID principles.

The developer will make the design emerge using continuous refactoring. It's the most important aspect of TDD: Refactoring.

Applying TDD without doing constant refactoring will often lead to really poorly designed systems which is worst than applying BDUF.

TDD is often associated with the notion of "emergent design". In agile, you often build your software incrementaly, feature by feature. So you can't know right from the start what architecture you will need, it will evolves/emerge with time. So any time you add a new piece of functionality you do some refactoring to improve the design of your application. It's continuous/incremental design. That's why TDD is key in a agile processes.

BDUF is not incompatible with TDD. There is nothing wrong with starting a piece of sofware while having the design already in mind. TDD will then enable you to put that design in place quickly. And in the case the design you thought about was wrong, TDD will allow you to refactor it nicely and safely. Again, it's just a tool, it's there to help us develop our ideas faster and design stuff safely and faster.

So you can either do BDUF+TDD or Emergent Design+TDD, the later is the more common in the agile community because of the iterative way of working.

In all cases you should never try to do emergent design without being willing to do some constant refactoring, they both go together and It does really requires a lot of discipline. Things can quickly spin out of control if you keep adding new features without applying Refactoring.

Refactoring apply to both production code and test code.

An interesting article to read to get more insight on the question can be found  here:

Learning From Sudoku Solvers

Title: Does TDD lead to good design?


问:
Where can I learn more about JavaScript and Python?
Been teaching myself how to code over the past four months or so -- mainly in JavaScript, but just started Python -- and had a revelation today. I can write in JavaScript pretty well, but I don't actually know what JavaScript is. Basically I know how to use it, but not the advantages/disadvantages, its origination, its purpose, etc.

What is the purpose and background behind Javascript and why was it created?

答:
The ECMAscript specification goes into great detail about the underlying design and reasoning of the language. Being able to read BNF is a must.

The same holds true for Python, there is a substantial design document for both 2.7 and 3.x, while not a standard, is close enough. Guido Van Rossum also has essays on the language and it's styles and purposes as he sees them. Being that he's the BDFL of the language, his word by and large goes.


答:
This is a great list of ebook, links and material for a budding or even experienced developer. The URL is not politically correct, so be careful of using it at work if you work someplace sensitive.

At the very least Learn Python The Hard Way is one of the better places to start for Python.

For JavaScript I have purchased a the book, Eloquent JavaScript that I really thought was a great introduction to development and to JavaScript. Also I would be remiss not mentioning Douglas Crockford's classic JavasScript: The Good Parts.

Those are great links and books to get going on. Not to mention other excellent online resources like Code Academy to get going.

I also realize this might not be the exact answer for your question based on description, but I thought it might be helpful. Getting into something like language design for both of those languages is distinctly different. If that was what you were asking for.

Nothing beats just doing it though. Give it a shot to learn one and then go to Project Euler to try and solve a few problems with your language of choice. It is a great way to practice.

Title: Where can I learn more about JavaScript and Python?

Body:
Been teaching myself how to code over the past four months or so -- mainly in JavaScript, but just started Python -- and had a revelation today. I can write in JavaScript pretty well, but I don't actually know what JavaScript is. Basically I know how to use it, but not the advantages/disadvantages, its origination, its purpose, etc.

What is the purpose and background behind Javascript and why was it created?


问:
Is it appropriate for a class to only be a collection of information with no logic?
Say I have a class Person that has instance variables age, weight, and height, and another class Fruit that has instance variables sugarContent and texture. The Person class has no methods save setters and getters, while the Fruit class has both setters and getters and logic methods like calculateSweetness. Is the Fruit class the type of class that is better practice than the Person class. What I mean by this is that the Person class seems like it doesn't have much purpose; it exists solely to organize data, while the Fruit class organizes data and actually contains methods for logic.

答: If your person is actually not doing anything, then there is no need to have any actions on it. It is possible to have classes which only collects data and then there will be classes which operates on this data. In your case, it may be possible that you do not have any action on single person, but there may be action on group of persons, like CalculateAverageHeight(). In this case it makes sense to have only Person without action and then have another class (may be friend) which works on this. </p>


答:
It is difficult to come with a rule saying all classes must have some logic. In general classes without any logic are considered to be  AnemicDomainModel.

Even then, it is better to organize data if the related information is getting large. For example in this case you may still need a collection of Person than many unrelated collections.

Title: Is it appropriate for a class to only be a collection of information with no logic?

Body: Say I have a class Person that has instance variables age, weight, and height, and another class Fruit that has instance variables sugarContent and texture. The Person class has no methods save setters and getters, while the Fruit class has both setters and getters and logic methods like calculateSweetness. Is the Fruit class the type of class that is better practice than the Person class. What I mean by this is that the Person class seems like it doesn't have much purpose; it exists solely to organize data, while the Fruit class organizes data and actually contains methods for logic.


问:
Where did the estimation rule of thumb originate that time spent will be one-third in each of the following: design, implementation, and testing?
I'm looking for a reference to the following.  I commonly hear that one-third of a projects time will be spent in design, one-third in implementation, and one-third in testing.  The three phases of development seems to be derived from the waterfall model.  But, where did the time division originate (1/3, 1/3, 1/3)?  Is there a paper or book that this is from?</p>

答:
The rule of thumb you're describing sounds extremely similar to Brooks' rule of thumb, as presented in the Mythical Man-Month:

For some years I have been successfully using the following
  rule of thumb for scheduling a software task:

1/3 planning

  1/6 coding

  1/4 component test and early system test

  1/4 system test, all components in hand.

This differs from conventional scheduling in several important ways:

The fraction devoted to planning is larger than normal. Even so, it is barely enough to produce a detailed and solid specification, and not enough to include research or exploration of totally new techniques.

The half of the schedule devoted to debugging of completed code is much larger than normal.

The part that is easy to estimate, i.e., coding, is given only one-sixth of the schedule.

I don't know where exactly your rule of thumb comes from, but it certainly looks like a derivative of Brooks' rule of thumb.

OwnerDisplayName: zooropa


问:
Code Smell: Inheritance Abuse
It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful.  Delegation can often (though not always) be verbose and brittle.

The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle.  What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?

答:
I think battles like inheritance vs. composition, are really just aspects of a deeper core battle.

That fight is: what will result in the least amount of code, for the greatest expandability in future enhancements?

That's why the question is so hard to answer.  In one language it could be that inheritance is more quickly put into place than composition than in some other language, or vice-versa.

Or it could be the specific problem you are solving in code benefits more from expedience than a long-term vision of growth.  That's as much a business problem as a programming one.

So to get back to the question, inheritance could be wrong if it's putting you into a straight-jacket at some point in the future - or if it's creating code that does not need to be there (classes inheriting from others for no reason, or worse yet base classes that start to have to do a lot of conditional tests for children).

Title: Code Smell: Inheritance Abuse


问:
Liskov substitution and abstract classes / strategy pattern
I'm trying to follow LSP in practical programming. And I wonder if different constructors of subclasses violate it. It would be great to hear an explanation instead of just yes/no. Thanks much!

P.S. If the answer is no, how do I make different strategies with different input without violating LSP?

```<code>class IStrategy
{
    public:
        virtual void use() = 0;
};

class FooStrategy : public IStrategy
{
    public:
        FooStrategy(A a, B b) { c = /* some operations with a, b */ }
        virtual void use() { std::cout << c; }
    private:
        C c;
};

class BarStrategy : public IStrategy
{
    public:
        BarStrategy(D d, E e) { f = /* some operations with d, e */ }
        virtual void use() { std::cout << f; }
    private:
        F f;
};
</code>```

答:
Generally constructors are not considered to be part of the  Liskov substitution Principle (LSP). The LSP with objects, not classes:

What is wanted here is something like the following substitution property: If
for each object o1 of type S there is an object o2 of type T such that for all
programs P deﬁned in terms of T, the behavior of P is unchanged when o1 is
substituted for o2 then S is a subtype of T. (quoted this PDF file)

Since an object doesn't exist until after construction, the constructor itself is generally consider to be out of scope. The LSP wants all subclasses to behave the same. How they get to that behaviour is a different matter.

This means you're code example is not in violation of the LSP per se. The constructor and the private methods are not part of the public contract when viewed from a LSP perspective.

Do keep in mind that LSP goes a lot further than function signatures. If a parent throws an exception in a specific case, so should the children. If a parent doesn't children can't start throwing execptions all of a sudden, if a getStock function in a parent returns an integer, a child can't start returning stock objects, etc, etc

The LSP deals with every aspect of public behaviour an object has.

A common solution to creating strategies with different constructors is the factory pattern by the way.


问:
Is Extreme Programming (XP) the best way of learning from experts?
I have been involved in many development models, and have found XP to be the best for a new programmer from the aspect of learning, as the collaboration between the team members is very high and the opportunities to share knowledge are great.

What are the expert opinions on this?

答: It helps, but only when the more knowledgable programmer of a pair works to transmit that knowledge to the other. For instance, if he does all the programming while the newbie is watching, that won't help (much). However, if the new guy does some of the work with the more experienced programmer helping him, he will learn more and the more experienced programmer will be able to hone his teaching skills.</p>


问:
How to create contracts in python
I am currently learning Python (from Java) and have a question on contracts.

Example: an application defines an interface that all plugins must implement and then the main application can call it.

In Java:

```<code>public interface IPlugin {
  public Image modify(Image img);
}

public class MainApp {
   public main_app_logic() {
     String pluginName = "com.example.myplugin";
     IPlugin x = (IPlugin) Class.forName(pluginName);
     x.modify(someimg);
   }
}
</code>```

The plugin implements the interface and we use reflection in main app to call it. That way, there's a contract between the main app and the plugin that both can refer to.

How does one go about doing something similar in Python? And also, which approach is better?

P.S. I'm not posting this on SO because I'm much more concerned with the philosophy behind the two approaches.

答:
Python's approach to this problem is is about as opposite as you can get to Java's approach.

In Python there are no contracts, restrictions, agreements, or requirements with respect to objects and their capabilities. An object is assumed to have any given method or property until you actually try to use it. If it works then it works, but if the attribute doesn't exist, then it's a runtime error. You can either try to catch that AttributeError before it blows up your program, or you can debug from the resultant stack trace.

If the method exists but returns the wrong type of result, then hopefully either you'll get an exception somewhere down the road that you can catch, or perhaps you'll get some sort of output sometime later that you'll alert you to your mistake.

As mentioned, you can use the abc module to define an Abstract Base Class and register your class as an implementation. This will throw a TypeError when you instantiate your class if it doesn't implement all of the abstract methods described in your abstract base class. There's obviously no way to check return types, though, since Python doesn't really have a concept of return types.

This really underscores the need for 100% code coverage on your unit tests for Python code. These mistakes can lay quietly undetected unless you exercise every piece of code under every allowable set of circumstances.

Title: How to create contracts in python


答:
Models are no end to themselves - you should add functionalities to a class when you really need them in your program, not on guessing that you will need them probably in the future. So its natural that at one point in time you have classes with no "real" methods, and later, when you determine that it makes sense to add methods to the class, you do exactly that. The quality of a model is not measured by "do I have methods here and no methods there" - the quality is measured by "do I have all the methods my application actually needs in there".

For example, when your application in version 1.0  needs something like calculateSweetness for a Fruit, but does no operations on a Person except getting and setting the attributes, then your model should exactly reflect that by not having any logic in the class Person. In version 2.0, it may make sense to add some logic to a Person too, so when you are at that point, add the methods in question.


答:
Definitely, TDD leads to better design, TDD leads to better code quality, TDD leads to better maintainability of code.

But, TDD does not help to create bug-free code, in the same way it does not provide good design.

For me TDD is the way to solve the problem a bit faster, that's it. Maybe because I'm a bad upfront thinker. It's easier for me to start with some ideas and shape it up with tests a bit later.

TDD does not guarantee good design at the end of the day. As you mentioned, the 'Game of life' could be great example. I've implemented it once with pure TDD. Everything was great as soon I had a bunch of unit tests. But after I implemented some UI and tried to run the game on a 64x64 grid, it turned out that performance of the application completely sucked. That meant I had 100% code coverage - but the app would not fly in production. This case could easily be projected on some projects we work in office.

So, I prefer another approach. Let's call it post-prototype design. As soon as I have some working code with TDD (or not) I start to understand the task better, start to see different ways of implementation. I could spent some time with a piece of paper to find some design ideas. After that I can start the task from scratch, or re-use already created unit tests to implement those ideas.

Title: Does TDD lead to good design?

Body:
I'm in transition from "writing unit tests" state to TDD.

I saw as Johannes Brodwall creates quite acceptable design from avoiding any of architecture phase before. I'll ask him soon if it was real improvisation or he had some thoughts upfront.

I also clearly understand that everyone has experience that prevents to write explicit design bad patterns.

But after participating in code retreat I hardly believe that writing test first could save us from mistakes. But I also believe that tests after code will lead to mistakes much faster.

So this night question is asking for people who is using TDD for a long time share their experience about results of design without upfront thinking. If they really practice it and get mostly suitable design. Or it's my small understanding about TDD and probably agile.


答:
It all depends on how your programmers are thinking:

If they've used TDD before, then there is a chance of getting good design

If TDD is being imposed from the outside, then it can only break the existing pattern your programmers are comfortable using

On the other hand, the team should use common patterns so that everyone is creating part of the same design instead of randomly going to different directions

So it's a balance between how disruptive process you want to impose and how much you can trust programmers to use their own techniques to create the best possible design. Getting feedback on how broken the previous code was is a good quality metric for programmers.

Title: Does TDD lead to good design?


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
That's it's harder than you think.

While it's easy(ish) to put something together that works when used normally, coping with erroneous input, all the edge and corner cases, possible failure modes etc. is time consuming and will probably be the hardest part of the job.

Then you've got to make the application look good too.


问:
Difference between Atomic Operation and Thread Safety?
From the discussion I've seen it seems that atomic operation and thread safety are the same thing, but a lot of people say that they're different. Can anyone tell me the difference if there is one?

答:
An atomic operation is an operation that cannot be interrupted.

A safe thread is a thread that can safely be interrupted.

Thread safety is obtained with atomic operations, in particular in the logic that prevents critical resources from being accessed multiple times.

The basic atomic operation is Test-and-set, which is used for implementing semaphores, which in turn are used to implement thread safety.


答:
Atomic operations are a way to achive thread safety either by using some kind of locks like Mutexes or Semaphores which use atomic operations internally or by implementing lock free synchronization using atomics and memory fences.

So atomic operations on primitive data types are a tool to achive thread safety but do not ensure thread safety automatically because you normally have multiple operations that rely on each other. You have to ensure that these operations are done without interruption eg using Mutexes.

Yes, writing one of these atomic data types in c# is thread safe, but that does not make the function you use them in thread safe. It only ensures that the single write is correctly executed even if a second thread accesses it "at the same time". Never the less, the next read from the current thread is not ensured to get the value previously written as a different thread might have written to it, only that the value read is valid.

Title: Difference between Atomic Operation and Thread Safety?

Body: From the discussion I've seen it seems that atomic operation and thread safety are the same thing, but a lot of people say that they're different. Can anyone tell me the difference if there is one?


问:
If I release a program under GPL, do I have to continue to do so?
Consider this scenario:

I am developing a program FooSuite that uses a GPL-licenced library QuuxTools

I release the program FooSuite 1.0 under GPL

Later on I discover that, for some reason, I need to licence the program to someone on different terms.

Hence:

I remove the dependency on GPL via QuuxTools, by either...

rewriting the program not to use this library any longer

obtaining a different licence for QuuxTools (if it's dual-licenced; see PyQt)

I release FooSuite 1.1 under a non-GPL licence.

However, FooSuite 1.1 is still a derivative work from FooSuite 1.0. I understand that it's not legal for a stranger to do what I did, but am I myself - as the owner of FooSuite - free from this restriction?

答:
So long as you retain the copyright to all the code that is part of FooSuite (this gets problematic if you've incorporated code from the community unless you got the contributors to assign their copyright to you), you are free to distribute the code under as many different licenses as you'd like.  So you could release FooSuite 1.1 under a different license.

Of course, someone else could take the code to FooSuite 1.0 that is already released under the GPL and create their own OpenFooSuite 1.1 that would be under the GPL and incorporate whatever functionality you added for the 1.1 release.  If there is a reasonably large community interested in FooSuite, it can be very difficult for your closed source version to compete with the open version.


问:
Are there bots that download new iOS apps without being asked?
I noticed on the first day my iOS app hit the app store I got a download from Albania and another one from China.   The app is only useful to a specific group, all of which are in a certain U.S. city.  Are there bots that automatically download every new app?  If so, to what end?</p>

答:
Yes, there are bots that auto down applications in order to boost rankings of applications:

View Article Here

Your downloads were most likely used as a way to mask the fact they are downloading specific apps to boost rankings. So 20 bots download Angry Birds (for example), 2 of those also download yours and some others to make it look like normal usage.

You could also account for these as simply random downloads, at a previous employer we created a very specific application to monitor solar panels, whilst they were only sold to specific people we had downloads (and subsequent uninstalls) from random countries around the globe.


问:
Using PDO with MVC
I asked this question at stackoverflow and received no response (closed as duplicate with no answer). I'm experimenting with OOP and I have the following basic MVC layout:

```<code>class Model {
    // do database stuff
}

class View {
    public function load($filename, $data = array()) {
        if(!empty($data)) {
            extract($data);
        }

        require_once('views/header.php');
        require_once("views/$filename");
        require_once('views/footer.php');
    }
}

class Controller {
    public $model;
    public $view;

    function __construct() {
        $this->model = new Model();
        $this->view = new View();

        // determine what page we're on
        $page = isset($_GET['view']) ? $_GET['view'] : 'home';
        $this->display($page);
    }

    public function display($page) {
        switch($page) {
            case 'home':
                $this->view->load('home.php');
            break;
        }
    }
}
</code>```

These classes are brought together in my setup file:

```<code>// start session
session_start();

require_once('Model.php');
require_once('View.php');
require_once('Controller.php');

new Controller();
</code>```

Now where do I place my database connection code and how do I pass the connection onto the model?

```<code>try {
    $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err) {
    die($err->getMessage());
}
</code>```

I've read about Dependency Injection, factories and miscellaneous other design patterns talking about keeping SQL out of the model, but it's all over my head using abstract examples. Can someone please just show me a straight-forward practical example?

答:
It all depends on how much design and abstraction you want to put in your code.
Your code is fine if you want to keep things relatively simple, and have flexibility without to much headaches or code writing.  Put your database access in a dedicated object, which will pull data of the DB and construct your Model object for you (it's a factory). Then, within the controller method query that factory to retrieve the correct model instance to populate your view. The model itself doesn't really need to know where it is coming from, so the factory is free to construct it from a file based storage instead. The only things that your factory will need is some parameters (say the $_GET relevant fields in your code), to figure out which data it must fetch.

```<code>class ModelFactory {
    private $dbhandle;
    function __construct(){
          // open db etc...
    }
   function loadModel($params){
         // run db queries and construct/fill up the Model instance
   }
   function saveModel($model){
        // pull out model fields to fill the insert/update query
   }
   // etc...you get the idea
}
</code>```

Next, if you have a basic model layer where domain objects are direct transpositions of database rows, as it's mostly the case with direct use of the ActiveRecord pattern, and you only need to let the end user do CRUD operations, then just do that. Get inspiration from that pattern to build your ORM on top of it, and you get basic Master/Detail, one to many, many to many relationships handled for you. That would be a first step in the right direction (you can have look at early versions of cakephp or code igniter to get a feeling of how this works), but if you want to do it the right way(TM), then you will see that MVC can be much more complicated.

The MVC architecture is actually more abstract than that. The model part is a "layer" in the application, comprising a set of different services, in a very broad sense, which basically let you embody "higher level" functionalities (think authentication for instance, where you need to pull data from different places, but these details should not leak out to the controller level), which may be used in different requests, then domain objects (like a user), then data mappers (like the ActiveRecord pattern).

There are excellent posts on SO on that topic, like this one, covering that topic in details.

Title: Using PDO with MVC

Body:
It all depends on how much design and abstraction you want to put in your code.
Your code is fine if you want to keep things relatively simple, and have flexibility without to much headaches or code writing.  Put your database access in a dedicated object, which will pull data of the DB and construct your Model object for you (it's a factory). Then, within the controller method query that factory to retrieve the correct model instance to populate your view. The model itself doesn't really need to know where it is coming from, so the factory is free to construct it from a file based storage instead. The only things that your factory will need is some parameters (say the $_GET relevant fields in your code), to figure out which data it must fetch.

class ModelFactory {
    private $dbhandle;
    function __construct(){
          // open db etc...
    }
   function loadModel($params){
         // run db queries and construct/fill up the Model instance
   }
   function saveModel($model){
        // pull out model fields to fill the insert/update query
   }
   // etc...you get the idea
}

Next, if you have a basic model layer where domain objects are direct transpositions of database rows, as it's mostly the case with direct use of the ActiveRecord pattern, and you only need to let the end user do CRUD operations, then just do that. Get inspiration from that pattern to build your ORM on top of it, and you get basic Master/Detail, one to many, many to many relationships handled for you. That would be a first step in the right direction (you can have look at early versions of cakephp or code igniter to get a feeling of how this works), but if you want to do it the right way(TM), then you will see that MVC can be much more complicated.

The MVC architecture is actually more abstract than that. The model part is a "layer" in the application, comprising a set of different services, in a very broad sense, which basically let you embody "higher level" functionalities (think authentication for instance, where you need to pull data from different places, but these details should not leak out to the controller level), which may be used in different requests, then domain objects (like a user), then data mappers (like the ActiveRecord pattern).

There are excellent posts on SO on that topic, like this one, covering that topic in details.


答:
If I get one of those big ol' reference type books, I read it as a reference. Meaning, I skim it looking for the key points, and trying to learn the book so that I know where to look something up when I need it. A good example is my C reference manual. I have read it through, but I couldn't quote the C specs to you. However, I know most of the important things, and I can look up anything I need to quickly because I'm familiar with the layout of the book.

If I'm reading a how-to or introductory book, I generally do it in front of the computer so I can try the stuff as I go. My favorite intro books have lots of code in them to try - and I'm telling you, Don't use the code samples on the CD!!! You'll gain much more practical knowledge by typing it yourself.

Title: How do people read big technical books?

Body:
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?


问:
How to create a Request Specific Thread Safe Static int Counter?
In one of my server application I have a class that look like,

```<code>class A
{
   static int _value = 0;
   void DoSomething()
   {
         // a request start here
          _value = 0;
         _value++;
         // a request end here
   }
   // This method can be called many time during request
   void SomeAsyncMethods()
   {
         _value++;
   }
}
</code>```

The problem is SomeAsyncMethods is async. Can be called many times. What I need when a request start set _value = 0 and then asynchrosnously increment this. After end of request I need the total. But the problem is that another request at the same time can access the class.

答:
use

```<code>System.Threading.Interlocked.Increment( ref _value );
</code>```

instead of

```<code>_value++;
</code>```

Interlocked.Increment

If multiple requests share this class and each one should get its own counter you need a non static counter that you pass to all threads working on this request.

Like this

```<code>class A
{
    void DoSomething()
    {
        // a request start here
        RequestData data = new RequestData();
        request.IncrementValue();
        // a request end here
    }

    // This method can be called many time during request
    void SomeAsyncMethods( RequestData request )
    {
        request.IncrementValue();
    }
}

class RequestData
{
    int _value = 0;

    public void IncrementValue()
    {
        System.Threading.Interlocked.Increment( ref _value );
    }
}
</code>```

Body:
use

System.Threading.Interlocked.Increment( ref _value );

instead of

_value++;

Interlocked.Increment

If multiple requests share this class and each one should get its own counter you need a non static counter that you pass to all threads working on this request.

Like this

class A
{
    void DoSomething()
    {
        // a request start here
        RequestData data = new RequestData();
        request.IncrementValue();
        // a request end here
    }

    // This method can be called many time during request
    void SomeAsyncMethods( RequestData request )
    {
        request.IncrementValue();
    }
}

class RequestData
{
    int _value = 0;

    public void IncrementValue()
    {
        System.Threading.Interlocked.Increment( ref _value );
    }
}


问:
Organizing ASP.Net Single Page Application with Nancy
As a personal project, I'm creating a single page, asp.net web application using Nancy to provide RESTful services to the single page. Due to the complexity of the single page, particularly the JavaScripts used, I've think creating a dedicated project for the client side of web development and another for service side will organize and simplify the development.

```<code>solution
  |
  +-- web / client side (single html page, js, css)
  |    - contains asp.net project, and nancy library
  |      to host the modules in application project folder
  |
  +-- application / service (nancy modules, bootstrap for other layer)
  |
  .
  .
  . and other layers (three tier, domain driven, etc)
  .
</code>```

Is this a good way of organizing a complex single page application? Am I over-engineering the web app, incurring too much complexity?

答: There is really nothing wrong with splitting them apart or keeping them together.  If you plan on reusing you nancy services for other front ends it would make since to keep them separate.  It would be trivial to factor out a single page with no backend later on if needs change, so just do what makes the most since to you -its just personal preference.</p>


答: The DataTransferObject is a good example of a class that has no logic, only data.  That's its purpose, though; it's explicitly an exception to the general rule that all classes should implement the business logic that  affects their internal state.  Having a class whose internal state is changed by external logic is often a design smell.  It's not always wrong, but it's almost always something that you should consider refactoring.


问:
How to choose a development method?
There are many academic/industrial researchs about various development methods (Scrum, XP, waterfall, ect.), telling us how to do it right and stuff. But I never saw something that suggest how to choose a method, what will be better for a given project.

I know that what the developers are used to is an very important aspect. But lets say that I am assembling a new group from scratch, and that every programmer in the world is willing to work with me. :)

What aspects of the project should I consider to decide between Scrum, XP, TDD, ect.? Or is that an entirely human thing, regardless of what is being developed?

I said that all programmers are available, but you may comment they're knowledge about the domain, or other characteristics in the answers. E.g. "If you chose to hire people with no domain knowledge, MethodX is better than MathodY, beacause ...." is a completely welcomed answer.

答:
There is something like a continuum between agile methods and the old, rigid, strongly formal "waterfall" approach. The more you walk away from agile developement, the more you add structure and design to your development process.

This means that moving closer to a waterfall model, you will need more knowledgable designers, more knowledgable programmers and more knwoledgable project managers. More important, the closer you move to a waterfall model, the more you need knowledgable customers.

Customers are probably the deciding factor. If you have a customer that does not actually know what he/she really need or want, you are practically forced to adopt a development model that is able to accomodate for a large amount of change. This is usually the case for web development, for example. If you have a strongly technical, mature, knowledgable customer, as is usually the case in the embedded development field, you are usually requested to adopt a strongly formal method (something like a waterfall).

Programmers are another major selection point. You cannot actually adopt a strongly formal method with a group of college part-time workers. The more you need a formal approach ("waterfall" as an extreme example), the more you will need seasoned programmers with a large and strong set of skills.

The type of system being developed is less relevant. There are web application so complex they need a development model very similar to the one used by NASA to go on the Moon (Amazon.com, for example) and embedded systems so simple that a single college programmer can develop it in a few weeks alone with any dev method at all (like many Arduino-based toy projects).

Despite this, usually the systems that imply some kind of hardware dependency (embedded systems of any type) require a strongly formal approach because any error will be paied in $ or € by the developing company.

This is another continuum: the more you walk away form hardware, the less you need a formal approach. The more you move away from money-related stuff (bank systems, e-commerce systems, POS, etc.), the more you can have an agile, iteractive approach. The limit is probably represented by the typical web-based brochureware where you do not actually need any formal approach to development (as long as you have mature and conscientious people).

Title: How to choose a development method?


问:
Interaction of a GUI-based App and Windows Service
I am working on personal project that will be designed to help manage my media library, specifically recordings created by Windows Media Center.

So I am going to have the following parts to this application:

A Windows Service that monitors the recording folder.  Once a new recording is completed that meets specific criteria, it will call several 3rd party CLI Applications to remove the commercials and re-encode the video into a more hard-drive friendly format.

A controller GUI to be able to modify settings of the service, specifically add new shows to watch for, and to modify parameters for the CLI Applications

A standalone (GUI-based) desktop application that can perform many of the same functions as the windows service, expect manually on specific files instead of automatically based on specific criteria.

(It should be mentioned that I have limited experience with an application of this complexity, and I have absolutely zero experience with Windows Services)

Since the 1st and 3rd bullet share similar functionality, my design plan is to pull the common functionality into a separate library shared by both parts of the application, but these 2 components do not need to interact otherwise.

The 2nd and 3rd bullets seem to share some common functionality, both will have a GUI, both will have to help define similar parameters (one to send to the service and the other to send directly to the CLI applications), so I can see some advantage to combining them into the same application.

On the other hand, the standalone application (bullet #3) really does not need to interact with the service at all, except for possibly sharing a few common default parameters that can easily be put into an XML in a common location, so it seems to make more sense to just keep everything separate.

The controller GUI (2nd bullet) is where I am stuck at the moment.

Do I just roll this functionality (allow for user interaction with the service to update settings and criteria) into the standalone application?  Or would it be a better design decision to keep them separate?  Specifically, I'm worried about adding the complexity of communicating with the Windows Service to the standalone application when it doesn't need it.

Is WCF the right approach to allow the controller GUI to interact with the Windows Service?  Or is there a better alternative?  At the moment, I don't envision a need for a significant amount of interaction, maybe just adding a new task once in a while and occasionally tweaking a parameter, but when something is changed, I do expect the windows service to immediately use the new settings.

答:
I would recommend you look at ASP.NET MVC instead of using WCF.  ASP.NET services are generally easier to setup and get running, and it doesn't sound like you need the additional complexity that WCF can offer.  If you're concerned about security, run the ASP.NET services over https and that should be good enough for your usage.

For the controller that you described, it's really up to you to decide on what it needs and how to structure it.  If you're worried about adding unnecessary complexity to one of the two UIs, then don't do that.  You can always add that functionality later on when it actually is required.  Get it working first before you worry about adding every last bell and whistle into the application.

You'll get to a point while building the application to where it will either make sense to keep the two UIs separate or to join them together.  You won't really know that answer until you get to writing the application though.  You may find that one application with two tabs solves that particular issue for you.


问:
How many bits' address is required for a computer with n bytes of memory?
How many bits of address is required (for the program counter for example) in a byte-addressed computer with 512 Mbyte RAM?

What does the formula look like?

How is this connected with the fact that 32 bits can address no more than 4 GB RAM?

答: You need log2(n) bits to address n bytes. For example, you can store 256 different values in an 8 bit number, so 8 bits can address 256 bytes. 210 = 1024, so you need 10 bits to address every byte in a kilobyte. Likewise, you need 20 bits to address every byte in a megabyte, and 30 bits to address every byte in a gigabyte. 232 = 4294967296, which is the number of bytes in 4 gigabytes, so you need a 32 bit address for 4 GB of memory.


问:
Questions to ask a 3rd party API provider
I'm due to meet with a developer/sales person from a new 3rd party resource we're about to start using.  The main topic I'll be interested in, is their API as I will be the developer making use of it and explaining it to the rest of the team.

What questions would you recommend asking?

Things I'm already thinking about are:

What happens and how will I be notified when they depreciate a method?

Is there ever any downtime?

Who will I deal with first when I have API issues?

答:
Besides the things you suggested by yourself (among which "who will I deal with first when I have API issues" is IMHO the most important question) I would ask

What kind of documentation do you provide?

Do you provide samples how to use the API?

How often do you provide new releases?

Do you provide a detailed and complete (!) change list for a new release with special hints on breaking changes?

Do your developers have a test suite in place (for example, to detect breaking changes)? (if the answer is no or "just for parts", you may consider bringing your own test suite in place)

Which requirements for the OS environment or run time environment does the lib have? What happens if there is a new version of the OS / run time environment, how quick can you test the lib / provide a new version if necessary?

What requirements on resources (memory, network, file system space, processor speed etc.) does the lib have?


答:
You need the log (base 2) of the N bytes in order to address N bytes of RAM directly.

```<code>4 GB = 2^32 bytes
log_2( 2^m ) = m
</code>```

so

```<code>log_2( 2^32 ) = 32
</code>```

So a 32-bit address lets you directly reference 2^32 bytes (4 GB).  A 64-bit address lets you directly reference 2^64 bytes (16 exabytes).

Title: How many bits' address is required for a computer with n bytes of memory?

Body:
How many bits of address is required (for the program counter for example) in a byte-addressed computer with 512 Mbyte RAM?

What does the formula look like?

How is this connected with the fact that 32 bits can address no more than 4 GB RAM?

Body:
You need the log (base 2) of the N bytes in order to address N bytes of RAM directly.

4 GB = 2^32 bytes
log_2( 2^m ) = m

so

log_2( 2^32 ) = 32

So a 32-bit address lets you directly reference 2^32 bytes (4 GB).  A 64-bit address lets you directly reference 2^64 bytes (16 exabytes).


问:
Is it appropriate for a class to only be a collection of information with no logic?
Say I have a class Person that has instance variables age, weight, and height, and another class Fruit that has instance variables sugarContent and texture. The Person class has no methods save setters and getters, while the Fruit class has both setters and getters and logic methods like calculateSweetness. Is the Fruit class the type of class that is better practice than the Person class. What I mean by this is that the Person class seems like it doesn't have much purpose; it exists solely to organize data, while the Fruit class organizes data and actually contains methods for logic.

答: Reverse the question, look at the other end. If you have a collection of information that obviously belongs together, should you keep it apart just because there are no methods which you could add to that class? Should you be forced to invent arbitrary methods just to justify the class?


答:
Thread-safety is more a framework or a "concept", atomic operation is a subset, a means (one of many) of achieving status as being classed 'thread-safe'.

Thread safety refers to a process that can be accessed by separate threads, where the access of one (and manipulation of data), wont corrupt the integrity of the operation of the other.

Much of the skill of the programmer is knowing how to achieve this, depending on the situation and key objective, you may need to implement, for example: locks, semaphores, latches, atomic objects, synchronization rules etc...


答:
Though there is a laundry list of potential questions, the answer to your question is simply:

Read the API documentation before the initial meeting on the API and ask for any additional information that you will need for the success of the project.

Title: Questions to ask a 3rd party API provider

Body:
I'm due to meet with a developer/sales person from a new 3rd party resource we're about to start using.  The main topic I'll be interested in, is their API as I will be the developer making use of it and explaining it to the rest of the team.

What questions would you recommend asking?

Things I'm already thinking about are:

What happens and how will I be notified when they depreciate a method?

Is there ever any downtime?

Who will I deal with first when I have API issues?


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
I'd highly recommend How to Read a Book. It gives general advice on how to get the most out of your reading by taking notes, asking questions, determining the authors goals, etc. It also gives advice on how to make the most of your time by determining what can be skimmed or skipped early on.

It's not aimed specifically at technical books, but the advice certainly applies. And it's a fairly easy read itself, though lengthy. But a number of the chapters on specific types of reading can be skipped.

Title: How do people read big technical books?


问:
Is there a difference between a component and a module
I have a little problem with the terms module and component.
In my mind, a module are bundled classes, which are only accesable via a well defined interface. They hide all implementation details and are reusable. Modules define modules on which they depend.

What is the difference to components? I looked it up in some books, but the description of components is very similar.

答:
It depends on your context. Module is already used to refer to DLL level groups in some languages, akin to 'package' or 'assembly' in others. Component is used for COM things as well as Entity Based Component stuff common in game development.

In general architectural terms, module and component do both tend to refer to some bundle of code behind a well defined interface. In general, module tends to refer to larger bundles. There's often a set of interfaces and the module tends to be able to stand on its own.

Components on the other hand tend to be smaller bundles of code, often smaller than a full class. By their name, they tend to be a component of something larger. Sometimes that is the application itself, but with the increasing usage of composition in class design it more often means a component of a larger object. The well defined interfaces for components also tends to allow the app to swap components in for each other. Modules tend not to have that swapability.


问:
Store image as logic file (in db by using binary format) or physical file (in the server)

Possible Duplicate:

  what are the best tips for storing images in a database?

In those study cases of image storage,

An image that change only once in a while, if it changes at all (like an image for an article)

The image case from above is not only one image but over 10, that link to the same article

An image that have changes very often (like a banner image for a website)

The image above is huge

What is the best approach for each case? What is the "right/faster" way to do this task in each scenario ?

答:
Sorry to provide a link only answer, but this microsoft research paper goes into great detail on the advantages of file system vs database for file storage:

To BLOB or Not To BLOB


答:
The terms are similar. I generally think of a "module" as being larger than a "component". A component is a single part, usually relatively small in scope, possibly general-purpose. Examples include UI controls and "background components" such as timers, threading assistants etc. A "module" is a larger piece of the whole, usually something that performs a complex primary function without outside interference. It could be the class library of an application that provides integration with e-mail or the database. It may be as large as a single application of a suite, such as the "Accounts Receivable module" of an ERP/accounting platform.

I also think of "modules" as being more interchangeable. Components can be replicated, with new ones looking like old ones but being "better" in some way, but typically the design of the system is more strictly dependent upon a component (or a replacement designed to conform to that component's very specific behavior). In non-computer terms, a "component" may be the engine block of a car; you can tinker within the engine, even replace it entirely, but the car must have an engine, and it must conform to very rigid specifications such as dimensions, weight, mounting points, etc in order to replace the "stock" engine which the car was originally designed to have. A "module", on the other hand, implies "plug-in"-type functionality; whatever that module is, it can be communicated with in such a lightweight way that the module can be removed and/or replaced with minimal effect on other parts of the system. The electrical system of a house is highly modular; you can plug anything with a 120V15A plug into any 120V15A receptacle and expect the thing you're plugging in to work. The house wiring couldn't care less what's plugged in where, provided the power demands in any single branch of the system don't exceed safe limits.

Title: Is there a difference between a component and a module

Body:
I have a little problem with the terms module and component.
In my mind, a module are bundled classes, which are only accesable via a well defined interface. They hide all implementation details and are reusable. Modules define modules on which they depend.

What is the difference to components? I looked it up in some books, but the description of components is very similar.


答:
The generic meaning of module is a group of reusable code, not tied to one specific program.  This could be everything from an entire set of GUI libraries down to a single class.

The generic meaning of component is a module with the additional restriction of substitutability using a specific interface.  If you create a GUI Widget component, it can be used anywhere a Widget is expected, without having to do anything special in the calling code.    Modules in general have no such restriction.  Qt and GTK+ are modules, but I can't swap out one for the other without considerable work in the code calling it, therefore they are not components.

Many frameworks or programming languages use the terms to mean something much more specific, which is why people are asking about context.  Something may be a component in the generic sense, but if it doesn't implement a very specific IComponent interface, it may not be considered a component in context.  In python, module has the very specific technical meaning of something you can get using an import command.  Usually people are referring to these context-specific meanings.


答:
Atomicity and thread-safety are two different things. Atomicity refers to an operation's "all-or-nothing" quality; if an operation cannot be performed 100% successfully, then the system should remain in the overall state it had been in before any part of the operation began. The classic example is a database transaction; When saving an invoice, including its header and multiple line items, every single part of every single database row must be put in place successfully; if not, data is lost or corrupted. If a line item cannot be inserted, then not only should no other rows remaining be inserted, but none of the rows already processed should remain.

Thread-safety refers to a combination of things, including atomicity, that allows an operation to be "reentrant"; multiple workers can be performing the same operation, starting at the same or different times, without effect on any other. There are many models for thread-safe operation; most of them boil down conceptually to either running multiple parallel tasks in complete isolation (two workers can perform the same task on two different objects or collections of objects without ever knowing the other worker even exists), or setting up a "pipeline" within which multiple workers each perform one task out of an entire operation (either each worker progresses from the first task to the next and so on, or else focuses on one task and hands off its intermediate "work product" to the next worker).


答:
I think this depend on the language and how you are using the language.

In the trivial case some languages insist on everything being in a class, so e.g. collections of constants have to go into a class which then may or may not have any logic, in other languages they might end up in a namespace instead.

In multi-paradigm languages it can also depend on what paradigm you want your design to adhere to. Borrowing the example of CalculateAverageHeight(), as is it probably should reside in a PersonCollection class, however that presupposes an OOP solution. in a more Functional design you might use a higher order function with a generic collection, e.g. in C#

```<code>List<Person> personList = GetListOfPeople();
personlist.Average(p => p.Height);
</code>```

and then the logic is not in PersonCollection or even statically in Person. Indeed higher order functions and generic data types in general mean you are more likely to end up with objects that are just bags of data, as the logic is operating at a higher level of abstraction then your specific data model.

Body:
I think this depend on the language and how you are using the language.

In the trivial case some languages insist on everything being in a class, so e.g. collections of constants have to go into a class which then may or may not have any logic, in other languages they might end up in a namespace instead.

In multi-paradigm languages it can also depend on what paradigm you want your design to adhere to. Borrowing the example of CalculateAverageHeight(), as is it probably should reside in a PersonCollection class, however that presupposes an OOP solution. in a more Functional design you might use a higher order function with a generic collection, e.g. in C#

List<Person> personList = GetListOfPeople();
personlist.Average(p => p.Height);

and then the logic is not in PersonCollection or even statically in Person. Indeed higher order functions and generic data types in general mean you are more likely to end up with objects that are just bags of data, as the logic is operating at a higher level of abstraction then your specific data model.


答: I don't find much time to read books. "Real World Haskell" took me about a year to finish. I usually skip the passages which i can not apply in the short term. I read the interesting pages bit by bit. What helps is outlining the most important insights with a pencil so that i don't forget what i was reading when i finally pick it up again.</p>

Title: How do people read big technical books?


答: My default answer to the default image storage question is to do both -- store the original in the database, but use caching to serve it out of the filesystem. It gives you all the advantages of the database -- that is transactional updates, easier backup management and transportability as you can just deploy from the database while also preserving the filesystem's advantages of speed of serving static content.</p>

Title: Store image as logic file (in db by using binary format) or physical file (in the server)

Body:
Possible Duplicate:

  what are the best tips for storing images in a database?

In those study cases of image storage,

An image that change only once in a while, if it changes at all (like an image for an article)

The image case from above is not only one image but over 10, that link to the same article

An image that have changes very often (like a banner image for a website)

The image above is huge

What is the best approach for each case? What is the "right/faster" way to do this task in each scenario ?


问:
Why do operating systems do low level stuff in C and C++? Why not just C++?
On the Wikipedia page for Windows, it states the Windows is written in Assembly for the bootloader and task switcher, and C and C++ for kernel routines.

IIRC, you can call C++ functions from an extern "C"'d block. I can get using C for the kernel functions so pure C apps can use them (like printf and such), but if they can just be wrapped in an extern "C " block, then why code in C?

答:
Because C is arguably a better language than C++. And because some of the code was written before C++ became popular and people haven't had a reason to replace it.

And because C++ has lots of features that can break your code if you're not careful when using it in a kernel.


答: I think you have it backwards -- the extern "C" block ensures that the C calling conventions are used for all functions within the block.  So you can call pure C functions from C++, not C++ functions from C.  Regardless, I imagine that the reason people use both C and C++ is because a lot of low-level libraries are written using C, and it's easier to use something that already exists (and is presumably debugged and optimized) than writing your own.  OTOH, C++ offers a lot of nice high-level features that people would rather work with, so they use that for the rest.

Title: Why do operating systems do low level stuff in C and C++? Why not just C++?

Body:
On the Wikipedia page for Windows, it states the Windows is written in Assembly for the bootloader and task switcher, and C and C++ for kernel routines.

IIRC, you can call C++ functions from an extern "C"'d block. I can get using C for the kernel functions so pure C apps can use them (like printf and such), but if they can just be wrapped in an extern "C " block, then why code in C?


答:
I see a couple of possible reasons:

C is a little bit more efficient if compared to the C++ equivalent.

Some libraries they use are written in C.

They use some parts of Linux kernel, which is written in C.

Edited:
As it turns out, third argument is not true (see comments).


问:
Is it a bad practice to include all the enums in one file and use it in multiple classes?
I'm an aspiring game developer, I work on occasional indie games, and for a while I've been doing something which seemed like a bad practice at first, but I really want to get an answer from some experienced programmers here.

Let's say I have a file called enumList.h where I declare all the enums I want to use in my game:

```<code>// enumList.h

enum materials_t { WOOD, STONE, ETC };
enum entity_t { PLAYER, MONSTER };
enum map_t { 2D, 3D };
// and so on.

// Tile.h
#include "enumList.h"
#include <vector>

class tile
{
    // stuff
};
</code>```

The main idea is that I declare all enums in the game in 1 file, and then import that file when I need to use a certain enum from it, rather than declaring it in the file where I need to use it. I do this because it makes things clean, I can access every enum in 1 place rather than having pages openned solely for accessing one enum.

Is this a bad practice and can it affect performance in any way?

答:
I'm not a C++ dev, so this answer will be more generic to OOA&D:

Typically, code objects should be grouped in terms of functional relevance, not necessarily in terms of language-specific constructs. The key yes-no question that should always be asked is, "will the end coder be expected to use most or all of the objects that they get when consuming a library?" If yes, group away. If not, consider splitting the code objects up and placing them closer to other objects that need them (thereby increasing the chance that the consumer will need everything they are actually accessing).

The basic concept is "high cohesion"; code members (from methods of a class all the way up to classes in a namespace or DLL, and DLLs themselves) should be organized such that a coder can include everything they need, and nothing they don't. This makes the overall design more tolerant of change; things that must change can be, without affecting other code objects that did not have to change. In many circumstances it also makes the application more memory-efficient; a DLL is loaded in its entirety into memory, regardless of how much of those instructions are ever executed by the process. Designing "lean" applications therefore requires paying attention to how much code is pulled into memory.

This concept applies at virtually all levels of code organization, with varying degrees of impact on maintainability, memory-efficiency, performance, build speed, etc. If a coder needs to reference a header/DLL of rather monolithic size just to access one object, which doesn't depend on any other object in that DLL, then that object's inclusion in the DLL should probably be rethought. However it is possible to go too far the other way as well; a DLL for every class is a bad idea, because it slows build speed (more DLLs to rebuild with associated overhead) and makes versioning a nightmare.

Case in point: if any real-world use of your code library would involve using most or all of the enumerations that you're putting into this single "enumerations.h" file, then by all means group them together; you'll know where to look to find them. But if your consuming coder could conceivably need only one or two of the dozen enumerations you are providing in the header, than I would encourage you to put those into a separate library and make it a dependency of the larger one with the rest of the enumerations. That allows your coders to get just the one or two they want without linking to the more monolithic DLL.


答:
It's mostly for historical reasons. Some parts of the windows kernel were originally written in C, because 1983, over three decades ago, when Windows 1.0 was unleashed, C++ was barely released.
Now these C-libraries will stay there "forever", because Microsoft made backward-compatibility a selling point and rewriting a bug-compatible version of the C-parts in C++ requires an awful lot of effort for no effective benefit.</p>


答:
C is a very low-level language, by its design. It's one step away from assembler; knowing the chipset you're targeting, you could, with a little knowledge, manually "compile" C into ASM. This kind of "close-to-the-metal" language is key for high levels of optimization (for performance, memory-efficiency, etc). However, because it's this close to the metal, you don't get much for free with this language; it is a procedural, non-object-oriented language, and thus to work with such constructs involves a lot of boilerplate code to create and consume multi-value constructs in memory.

C++ is "C one better", adding a number of ease-of-use features such as dynamic memory allocation, built-in structure marshalling, a large library of predefined code, etc, at the expense of some efficiency losses (still much better than managed-runtime environments). For the average coder, the advantages far outweigh the disadvantages in areas of the codebase that don't need anal-retentive control of memory allocation etc.

The combination of the two is a pretty traditional one; you use C to write the most performance-critical, memory-efficient areas of the codebase, which you can then work with in a more abstracted fashion via method calls from C++ code, which can be more elegantly organized and designed than the uber-performant, uber-oogly optimized C code.


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
I've written a parser for commercial application once and I used yacc.  There was a competing prototype where a developer wrote the whole thing by hand in C++ and it worked about five times slower.

As for the lexer for this parser, I wrote it entirely by hand.  It took -- sorry, it was almost 10 years ago, so I don't remember it precisely -- about 1000 lines in C.

The reason why I wrote the lexer by hand was the parser's input grammar. It was a requirement, something my parser implementation had to comply with, as opposed to something  I designed.  (Of course I would have designed it differently.  And better!)  The grammar was severely context-dependent and even lexing depended on semantics in some places.  For example a semicolon could be part of a token in one place, but a separator in a different place -- based on a semantical interpretation of some element that was parsed out before.  So, I "buried" such semantical dependencies in the hand-written lexer and that left me with a fairly straightforward BNF that was easy to implement in yacc.

ADDED in response to Macneil: yacc provides a very powerful abstraction that lets the programmer think in terms of terminals, non-terminals, productions and stuff like that.  Also, when implementing yylex() function, it helped me to focus on returning the current token and not worry about what was before or after it.  The C++ programmer worked on the character level, without the benefit of such abstraction and ended up creating a more complicated and less efficient algorithm.  We concluded that the slower speed had nothing to do with C++ itself or any libraries.  We measured pure parsing speed with files loaded in memory; if we had a file buffering problem, yacc wouldn't be our tool of choice to solve it.

ALSO WANT TO ADD: this is not a recipe for writing parsers in general, just an example of how it worked in one particular situation.


答:
The reasons aren't technical.  A little bit of assembly is unavoidable, but they aren't forced to use the occasional C, they want to.  My company uses its own proprietary kernel, written almost entirely in C++, but we don't need to support a C interface to the kernel like most everyone else, because our embedded kernel is monolithically compiled with our C++ applications.  When you have a C interface, it's often easier to write the interface code in C, even though it's possible to use extern "C" to write it in C++.

Even we have a smattering of C files, mostly due to third-party code.  Third-party low-level code is almost always provided in C, because it's much easier to incorporate C code into a C++ app than the other way around.


问:
Browser support for internal corporate tools
We are on the verge of a conversion.  For years, our company supported only IE for its internal (intranet) home-built tools.

Since a few of our users are still on XP, which means IE only goes up to 8... a heavily JS / jQuery site wont even load!

We have been in the process of converting to use Chrome instead, to make use of its javascript performance.

But, it has now been suggested that we support all common browsers... internally for these tools.  Which means more development time to scale-back some of these new applications, more time to test in all browsers, and we are already under staffed.

Are there any good informational sites/posts out there, that already make this argument?

答:
It would probably be more effective if you put together a simple document that explained what it would require for you to support multiple browsers.  Realistically, different organizations with different sets of applications can end up with very different experiences.  Organizations that build lots of internal tools (rather than buying third-party tools that they host on the intranet) often end up building relatively simple front ends with relatively minimal amounts of Javascript that support multiple browsers relatively easily.  If you have a relatively bleeding-edge front end, though, you may have a much more difficult challenge.  Organizations that have automated testing tools that can run the full regression suite in every browser engine relatively quickly will have a much easier time supporting multiple browsers than an organization that requires lots of manual testing.

I would tend to put together a quick 1-page document laying out exactly what you would need to support multiple browsers.  Estimate the time required to tweak the Javascript, list the hardware, software, VMs, etc. you would need, estimate how much time that requirement would add for new development (both in terms of additional overhead that reduces the number of hours you have to develop and the additional complexity required to develop and test against multiple browsers), and estimate what sort of impact that might have on the UI if you would expect to need to simplify the UI to make it work across browsers.  Then compare that to the benefits of allowing internal users to use whatever browser they want.  If you show meaningful drops in productivity or declines in user interface quality, it may make perfect sense to limit support.


问:
How do I express subtle relationships in my data?
"A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?

Example:

Here are a few headlines about a recent Broadway play:

David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway

Al Pacino in 'Glengarry Glen Ross': What did the critics think?

Al Pacino earns lackluster reviews for Broadway turn

Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard

Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?

Problem:

Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.

How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.

Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?

Goal:

Given 1,000 headlines, a system that automatically suggests that these 5 items are all probably about the same thing.

To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).

This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers!

答: It's called cluster analysis, which is basically grouping objects into clusters with similar properties.  It's a huge topic, but that should give you a place to start.</p>


答:
You're entering the world of Semantics. There are public services that will parse text and pull out the major concepts (a quick search for Semantic API turned up a few) that will parse a free form document and return the major topics encountered including people, places, things, dates, and concepts. Some of the better ones will return in a format known as [RDF]

If you want to build your own system that can do this, the field is Natural Language Processing and that is a very intriguing rabbit hole to dive down.

Title: How do I express subtle relationships in my data?

Body:
"A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?

Example:

Here are a few headlines about a recent Broadway play:

David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway

Al Pacino in 'Glengarry Glen Ross': What did the critics think?

Al Pacino earns lackluster reviews for Broadway turn

Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard

Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?

Problem:

Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.

How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.

Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?

Goal:

Given 1,000 headlines, a system that automatically suggests that these 5 items are all probably about the same thing.

To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).

This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers!


问:
Setting up ASP.NET structure for code
I've always coded in C# MVC3 when developing web applications. But now i wanted to learn a bit more about developing web sites with just ASP.NET.

But now i'm wondering what a good setup for my code would be. For me, an MVC like pattern seems to be a good way to go. But obviously ASP.NET doesn't have any router and controller classes. So i guess people have a different way of setting up their code when they do ASP.NET.

So i'm looking for more information on how to get started with this. So not really the basics of ASP.NET, but something that focuses on a good code setup.

Any good tutorials/information about this/?

答:
If what you're referring to is ASP.Net Web Forms, best practices are somewhat of an opinionated and difficult to find topic (given that its conventions are very one-sided). However in your case I would highly recommend getting familiar with what's new in ASP.Net 4.5 for web forms first. Features like Model Binding will help you cross-over into familiar territory. If you have used aspx views in any of your MVC projects you'll have a great head start too. For web forms design in general, many of the older conventions on best practices still hold true from days past. There are some more unconventional approaches to web forms that may be worth a look. Web forms MVP is one and also the Spring Framework for .Net has a very nice adaptation that makes excellent use of Spring's features to improve the web forms model greatly.

All in all web forms is good to know but IMHO you should stick with MVC and shoot for learning MVC4 and the new Web Api.

Title: Setting up ASP.NET structure for code