问:
GIT and different versions of a project: what are the best practices?
I'm very new in using GIT as a versioning system and despite a lot of searches, I can't seem to really understand how to handle my scenario.

I have this web project that needs to be developed in two versions:

the first is a general version used for demos

the second is a customized version for my client.

As for now, the second versions differs in minor things, mainly branding (i.e. icons, some titles) and database connections.

The idea is to enhance its code with suggestions and real use cases provided by the client and, as we progress with bugfixes and new features, port the changes to the "general/unbranded version" - but keeping those minor differences.

In the future the "general" version could be forked and enhanced more with some independent features.

Are branches an useful way to deal with this scenario? I think they're not, as (at least so I understood) they're more meant to make changes to be merged back in short- or mid-term.

答:
Push/pull and forking...

Having thought about this for a while, I believe that "forking" pattern - with a push/pull system for specific features you wish to migrate - might be your best option.

It is this pattern that is used by large open source communities to have a single 'master' (official copy?) and many many development branches/repos etc.

It is possible to do this using only git (eg adding an upstream remote and also this). It is extremely easy to do it within Github however, so for simplicity I shall describe only the Github workflow.

Setup:

You create your 'master' repository

this is your 'polished' / 'demo copy

You 'fork' this repository

this is your 'development' copy

Development workflow:

You develop in this second repository, and then when you are ready to "push" features to your 'demo' repository, you can submit a pull request from your development repo (containing the desired changes) to your demo repo.

Branches?

This can all be done via branches however, in my mind at least, I prefer to keep the two much more distinct.


问:
Is there a reason for the crossover from the Ruby community to the Clojure Community?
When we look at the the overlap between the Ruby Community - we see the following overlaps:

Think Relevance (now Cognitect) has switched from Ruby to Clojure

Jay Fields has switched from Ruby to Clojure

David Chelimsky - author of RSpec - has left the Ruby RSpec project to join Cognitect

Is there some linguistic similarity that has lead to this crossover?

答:
In a way, Ruby is a "stealth lisp." It allows (and encourages) more metaprogramming than most other languages of its class, even the directly comparable Python. I am thinking here of the famous post, Ruby is an Acceptable Lisp. There are limitations, however; functions are not really first-class objects (calling a lambda or a Proc is horrific, for example), you can't truly redefine the language as you can with macros, and so on.

It makes sense that people who are attracted to Ruby, which has until this point been the most practical and popular language that encouraged a lot of metaprogramming, would be attracted to a language which has better libraries (via the JVM), runs faster than Ruby, is truly functional, is dynamically typed, and encourages metaprogramming to an even greater degree than Ruby. I would hypothesize that you'll also see a greater crossover from the Python and Haskell communities to Scala.

ContentLicense: CC BY-SA 3.0


问:
Why do programming languages encompass so much?
Programming languages are not just language. Each one tends to have:

Its own IDEs,

Its own package managers,

Its own set of libraries,

Its own build tools,

Its own data formats.

If you are writing Java syntax, you will be using Maven packages; if you are writing Haskell syntax, you will be using Cabal packages. What's the connection? Why does each programming language create its own world?

答:
Eclipse, IntelliJ, Visual Studio, and Emacs can all be used for at least C++, Java, and JavaScript. Maven and Ivy can be used with any language.

The .NET framework is a set of libraries that can be used with multiple languages, and there are many languages besides Java that can run on a JVM and thus use the Java core libraries.

GYP, Ant, and Make can be used with pretty much any language. GCC is structured such that you can compile any language to any platform if you install the right bits. JSON, XML, INI are all data formats widely used by many languages.

Basically, the premise of your question is flawed. A programming language is just a language, and all the things you list are separate, though some are more often used together than others.


答:
Ruby projects in general appear to scale toward the JVM. Both Twitter and Tumblr began as Ruby projects but now make extensive use of Scala. The JVM gives you access to powerful new tools like Hadoop and the various distributed databases and search utilities.

Ruby tends to find the most use on Macs and Linux-based systems. Thus you want an option that scales to those systems' strengths. You say Mono? Mono could work but is still fundamentally an immature ecosystem compared to the JVM. Particularly regarding language support outside C#

So why then Clojure? Clojure helps smooth some of the problems that large distributed projects face. Functional languages tend to scale better with large sets of concurrent data than Object Oriented languages do. It's also easier to move from Ruby to a Lisp than it is to move to Scala which is more like an ML (SML, OCaml, Haskell, etc). You could use JRuby but again, it's still going to suffer some of the limitations of a pure OO language.

Lastly, Ruby is mostly popular as a web language because of Rails. Yes, there are other options but Rails is the overwhelming majority in terms of deployment. Using Clojure gives you access to all manner of mature web solutions, being designed to function in that environment from the get go rather than adopted into that role 10 years after initial release.

Title: Is there a reason for the crossover from the Ruby community to the Clojure Community?

Body:
When we look at the the overlap between the Ruby Community - we see the following overlaps:

Think Relevance (now Cognitect) has switched from Ruby to Clojure

Jay Fields has switched from Ruby to Clojure

David Chelimsky - author of RSpec - has left the Ruby RSpec project to join Cognitect

Is there some linguistic similarity that has lead to this crossover?


问:
Mozilla Public License (MPL 2.0) vs Lesser GNU General Public License (LGPL 3.0)
I would like to release a software library written in a class-based, object-oriented programming language (Java) on a web-based source code hosting service, that allows forks of the project to be merged into the main project (GitHub via pull requests).  I have researched on the web and given a lot of thought on how to license the software.
Am I correct in the following assumptions (from an IANAL perspective)?

Both LGPL and MPL promote sharing of modifications to the LGPL/MPL licensed software being used inside other software projects. Instead of requiring the users of the modified library to host a seperate fork of the library, I can promote contributing to the original library (e.g. via pull requests).

The major difference is how MPL / LGPL licensed code must be linked into the project. MPL source code files can be directly copied into a (possibly) proprietary software project (static linking), while LGPL licensed code must be dynamically linked (loosely linked to the possibly proprietary software project, so that end-users can switch out the licensed software library for another version of the licensed software library).

Dynamic linking and thus LGPL imposes extra obstacles for packaging the proprietary software product, without promoting more contributions to the open source software library than by having static linkage (and thus MPL). There is a modified LGPL which allows static linking.

There are no other relevant differences (from an IANAL perspective).

The older license versions don't suit my needs as good as the newest ones.

As you can see my main requirement is that modifications of the software library which could prove useful to the general public stay open-source, without imposing restrictions on using the software library in a proprietary product.

There is no license that also requires extensions of the software library that are relevant to the original work to be released as open-source, as the scope of the term relevant can be arbitrarily small / huge, thus ending up as GPL that can not be used in a proprietary product (without releasing the whole source).

I am tempted to use the modified LPGL, but on the other hand discouraged by the unpopularity. Based on the above points I prefer MPL.

Question: Are my above statements correct? Which license should I pick considering my requirements?

Solution: With the help of the discussion in the accepted answer, I choose to stick to the MPL because of the popularity, freedom in linking and because it is an official, unmodified license.

答:
I believe you've stated the differences between the Mozilla Public License and the GNU Lesser General Public License accurately, and either may suit your needs just fine, but you are skipping over the most important difference between the two licenses:

Who can make new versions?

Both the MPL (section 10) and the LGPL (section 14) include in their license grants the right to substitute the current version with a latter version, and there are no actual limitations as to what can go into those licenses.  While it's highly unlikely that either the Mozilla Foundation or the Free Software Foundation will do something as crazy as, say, institute a clause that says "all contributions to this software become our property", it's not beyond the realm of possibility that one of the organizations will release a new license version that you don't like.

Which brings up another point about using a "Modified LGPL".

A modified license is not the same license!

While you have fairly amazing ability to specify your own licensing terms, and could in essence say "you can distribute this as per the GPL, but you need to put my name in your credits and pay me 1% of any revenue you generate", any time you do so you are creating a new license based on someone else's work.  This means that you're NOT using the MPL or the LGPL, you're using a new "mucaho license".

What that means is that you probably won't get any help from your original license's author if you need to defend your interpretation of the license inside of a courtroom, and it's entirely possible that they might file suit to say that THEIR version should apply and not yours.

Of course, both of these are minor points.  Even "license popularity" doesn't matter unless you expect your code to be directly incorporated into larger projects.

Personally, I think the MPL is a better choice if you like proprietary compatibility, or if the choice is between the actual MPL and a different license you have to manually edit based on the LGPL.  Unless you have a reason not to use the MPL, go with something backed by a foundation instead of one that might leave you in a courtroom without any aid whatsoever.


问:
Faster reads, on an infinite grid plane, than using a hash table?
In the past, I've had alot of success just using a .NET Dictionary, with a TKey consisting of the X,Y coordinates merged together. However its read performance, despite being amortized constant time, is a bottleneck in a design of mine.

My application needs to perform alot of reads, and would benefit greatly if the performance of the read was similar to that of an array. My data has a very high degree of spatial locality; attached is an image showing two graphs of the distribution of some sample data on a 2D plane (sorry for the lack of labels); on the left is data with low spatial locality, and on the right is how my data looks (it's always a single connected mass, and blocky in form).

I could use an array (by computing a bounding rectangle (bRect) around the data and then doing data=array[(y-bRect.Top)*bRect.Height+x-bRect.Left]) but then I'd have to rebuild the entire array each time bRect.Height changed, or bRect.Width increased.

And so my question is, given the high degree of spatial locality, is Dictionary really the best choice here? Is there another approach I could take where I could get near array like read performance, yet not have to rebuild the array when data is added? (I don't need to ever remove data)

答:
If the blocks are relatively big and there is a relatively small number of them, then I can see two approaches that could help you:

Decompose each block into rectangles and then store them in an R-tree.

Split the plane evenly into quadrants. For each quadrant that is not homogeneous (either completely empty or completely filled), continue splitting recursively. This structure is called quadtree.


问:
Guidance on Excel VBA resource scheduling algorithm?
This was posted originally at StackOverflow though suggested to post here instead.

I am looking to create an Excel VBA solution that will create a rota/schedule allocating staff to service users using an algorithm. I believe there are already existing names for this kind of problem/algorithms but not entirely sure what to refer to it is.

Here is my scenario:

A colleague approached me with a problem of scheduling staff against visits required. Currently this is a manual process done every week and is labour intensive. The datasets are small, on average there would be 20 service users each requiring 2 visits a day with 5 members of staff available each day.

I have a worksheet that contains the list of staff who are available for the following week. Each row of data contains their name, gender, skill level, home postcode, day working, start time and end time. A member of staff may be listed more than once on the same day as they may be available for hours in the morning and also in the evening.

Another worksheet contains the list of service users and visits required for the following week. Each row of data contains their name, postcode, day of visit, time of visit, visit duration, gender required (i.e. must be seen by a male/female), skill level required (i.e. any, certified) and the number of staff required for that visit (i.e. 1 or 2). Again a service user may appear more than once on the same day as they may require multiple visits at different times of the day (i.e. morning and evening)

I have already created some VBA functions to deal with handling of postcodes and getting latitude/longitude co-ordinates along with a function to calculate the distance between two points as the crow flies. At present the distinct values of postcodes with there co-ordinates are being stored on a helper sheet for the VBA to reference.

What I am really looking for is guidance on how to even being creating a procedure/algorithm which will produce a suggested rota/schedule, this could be a simple table with pairings between staff and visits. The process must always make suitable pairings based on:

Skill Level Required

Gender Required

Staff Availability

Least important are that matches take into consideration the distance required to travel between visits. I believe this is referred to as a Genetic Algorithm?

There may be instances where there are too many service users for the available staff and vice versa. Making use of all staff isn't necessary provided all visits are dealt with, if all visits cannot be paired due to a lack of staff availability then this needs to be listed as being unmet.

I can utilize SQL Server if need be but ultimately the solution needs to be presented in Excel to the end user, as this is what they are most familiar with.

I'm thinking the procedure/process would need to go something like this:

For each day, sort the visits by start time

For each visit, determine which staff members meet the gender and
skill level requirement and is available on that day

For each of the staff member determined above, are they available at
the time requested?

For each staff member that is available calculate the distance from
their current location to the where they need to be

Rank them in order of preference by distance required to travel

Once this has been done for each day, come up with a suggested
allocation of staff to visits using some kind of scoring method

I'm no VBA expert and deal with SQL Server as my day job but I am willing to try and come up with a suitable solution, just need some guidance on how best to start.

答:
I have some experience with the sort of scheduling problem you present, and the technical stack you're using, and so I can speak from authority and say this is a database problem and belongs in SQL Server, not Excel!.

Assuming that these are regular visits that are already scheduled and you only need to allocate your staff to the various tasks, (and staff have to return to their home office between visits), I recommend the following process:

Migrate your staff list to a normalized table structure, with separate Employee and Availability tables.

Do the same to your service users, with Customer and Visit tables.  (How you populate the visits is a different question.)

Create a distinct Assignment table, that reflects the assignments you give your staff.  This table will include both actual shifts, and necessary non-visit assignments (such as "drive across town").  Your program will generate suggestions, but you need to allow a human to revise the list.

Generate a "complexity" score for each visit, by adding all the necessary requirements together.  ("Must be seen by two certified women for 3 hours" may be seven points, for example.)

For the highest complexity value, make all assignments for your time period for all visits on that assignment.  Do this one row at a time, with tie-breakers based on the visit length and start-time.  Select staff who meet the needs based on availability and then some sensible sort value (seniority or "times done this shift.")

Mark a travel time entry for the assigned staff between the customer's location and the employee's central location.

Repeat from #5, above, until all visits are satisfied.

Return to Excel two lists, one of Customer Visits that indicates the assigned employees(s), and one of Employee assignments that notes the times each employee will be assigned.  Include any highlight in both any unassigned items.

There are professional Workforce Management systems that will much of this for you, but such require several tens of thousands of dollars to purchase and assume you'll have an employee doing much of the work manually.  If they were doing this in Excel by hand, any automation will be an aid, and you can improve as you go on.

(And take a look at .NET or Access to replace Excel in some instances; round-tripping data from Excel back to SQL Server is significantly harder than just making a form for a SQL server table in Access.)


问:
Repository query conditions, dependencies and DRY
To keep it simple, let's suppose an application which has Accounts and Users. Each account may have any number of users. There's also 3 consumers of UserRepository:

An admin interface which may list all users

Public front-end which may list all users

An account authenticated API which should only list it's own users

Assuming UserRepository is something like this:

class UsersRepository extends DatabaseAbstraction {
    private function query() {
        return $this->database()->select('users.*');
    }
    public function getAll() {
        return $this->query()->exec();
    }
    // IMPORTANT:
    // Tons of other methods for searching, filtering,
    // joining of other tables, ordering and such...
}
```

<p>Keeping in mind the comment above, and the necessity to abstract user querying conditions, How should I handle querying of users filtering by <code>account_id</code>? I can picture three possible roads:</p>

<h3>1. Should I create an <code>AccountUsersRepository</code>?</h3>

<pre class="lang-php prettyprint-override"><code>class AccountUsersRepository extends UserRepository {
    public function __construct(Account $account) {
        $this->account = $account;
    }
    private function query() {
        return parent::query()
            ->where('account_id', '=', $this->account->id);
    }
}
</code>```

This has the advantage of reducing the duplication of UsersRepository methods, but doesn't quite fit into anything I've read about DDD so far (I'm rookie by the way)

2. Should I put it as a method on AccountsRepository?

class AccountsRepository extends DatabaseAbstraction {
    public function getAccountUsers(Account $account) {
        return $this->database()
            ->select('users.*')
            ->where('account_id', '=', $account->id)
            ->exec();
    }
}
```

<p><em>This requires the duplication of all <code>UserRepository</code> methods and may need another <code>UserQuery</code> layer, that implements those querying logic on chainable way.</em></p>

<h3>3. Should I query <code>UserRepository</code> from within my account entity?</h3>

<pre class="lang-php prettyprint-override"><code>class Account extends Entity {
    public function getUsers() {
        return UserRepository::findByAccountId($this->id);
    }
}
</code>```

This feels more like an aggregate root for me, but introduces dependency of UserRepository on Account entity, which may violate a few principles.

4. Or am I missing the point completely?

Maybe there's an even better solution?

Footnotes: Besides permissions being a Service concern, in my understanding, they shouldn't implement SQL query but leave that to repositories since those may not even be SQL driven.

答:
If I got it correctly, I would suggest you to model both Account and User as aggregate roots (with own their repositories). So, if you need all account's users you could do it this way:

```<code>interface UserRepository
{
    public function findAll();
    public function findByAccount(Account $account);
}
</code>```

You are free to "recycle" your code inside infrastructure layer (implementation side), you could do it this way:

```<code>class UserRepositoryImpl extends BaseRepository implements UserRepository
{
    public function findAll()
    {
        return $this->query('user');
    }

    public function findByAccount(Account $account)
    {
        // ...
    }
}

class AccountRepositoryImpl extends BaseRepository implements AccountRepository
{
    public function findAll()
    {
        return $this->query('account');
    }
}

abstract class BaseRepository
{
    protected function query($type = 'user')
    {
        // common part 1
        if ($type == 'account')
            $q .= 'AND account_id = ...';
        // common part 2
    }
}
</code>```

Just remember one thing, model (including repository interface) shouldn't deal with concerns like this. It's always a bad idea to change your model according to DB access needs.

Body:
If I got it correctly, I would suggest you to model both Account and User as aggregate roots (with own their repositories). So, if you need all account's users you could do it this way:

interface UserRepository
{
    public function findAll();
    public function findByAccount(Account $account);
}

You are free to "recycle" your code inside infrastructure layer (implementation side), you could do it this way:

class UserRepositoryImpl extends BaseRepository implements UserRepository
{
    public function findAll()
    {
        return $this->query('user');
    }

    public function findByAccount(Account $account)
    {
        // ...
    }
}

class AccountRepositoryImpl extends BaseRepository implements AccountRepository
{
    public function findAll()
    {
        return $this->query('account');
    }
}

abstract class BaseRepository
{
    protected function query($type = 'user')
    {
        // common part 1
        if ($type == 'account')
            $q .= 'AND account_id = ...';
        // common part 2
    }
}

Just remember one thing, model (including repository interface) shouldn't deal with concerns like this. It's always a bad idea to change your model according to DB access needs.


问:
Syncing objects from code with the view in WPF
I've been reading some into it, but I am time pressed, so I would require a simple solution now and I promise to read up on it later. I come from a winforms c# background, and have lately been working with WPF. As the user interface I'm implementing is not that input intensive, I've gotten by with using INotifyPropertyChanged so far. Until I ran into this:

I have a 3D interface from a third party library (MogreInWpf). Upon clicking an object in the 3D interface, I need to display some of the object's properties (position, size etc). Here's how my code-behind looks. I have a class, let's call it objectOfInterest, that saves all these properties, the 3D data and includes some methods that manipulate the object. In one of these methods, I generate a Grid containing textboxes to simulate name-value pairs of properties. Like "X position:" "134". As these properties are only user-changed, I've managed to bind the textbox on text changed event to respond to most changes, IE when the size is changed from 134 to 1345.

Once this grid is generated, it is set to display in the main window using a ContentPresenter and setting its content to the objectOfInterest.grid. Works like a charm. Now, I have to implement a property that changes how the properties grid look like depending on a combobox included in this grid.

For example, if the object is a cube, I want width/height/length to show, while I only want a radius property to show if it's a sphere. I'm kind of stuck here, as regenerating the grid upon combobox selectedValueChanged doesn't notify the view, and the generating occurs in the objectOfInterest class instead of the main window class, meaning I can't rebind the grid once it's regenerated (I cannot call contentPresenter.Content = objectOfInterest.grid again, as the main window has no idea the instances grid has changed). So, without completely understanding the MVVM methods and rewriting most of the application to fit the model, how can this be accomplished?

答:
If I understand correctly, you essentially have a ContentPresenter and you want the contents to change depending on the type of object being presented.

It sounds like you have created an ObjectOfInterest class that contains the object of interest, say a Cube or a Sphere, and it generates a Grid based on the type of object it contains.  If I understand you correctly, then...

I'd drop the ObjectOfInterest and bind the Cube or Sphere directly to the Content property of the ContentPresenter from the combobox selection.  In the ContentPresenter resources (Eg. <ContentPresenter.Resources>), define a DataTemplate for each object type.  Do not define a Key for each template, only set that DataType property to the object types that will be displayed.  In the DataTemplate, just define the Grid you want to display, complete with the databound controls.  When you set the Content property of the ContentPresenter, it will automatically search its Resources and apply the appropriate template for each object.

If you need the ObjectOfInterest and that must be set as the content, then make sure there's a property you can access that identifies the object type.  Create DataTemplates for the different object types, and define a custom DataTemplateSelector class that contains those templates and will check the object type property and return the appropriate DataTemplate.  Then bind the DataTemplateSelector to the ContentPresenter.ContentTemplateSelector property.


答:
There are a few principles in play here that may affect your design:

Aggregates - if Account is your top level item (aggregate root) for this aggregate, that should be your repository. You don't necessarily need one repository per table, as that breaks any domain encapsulation that you're trying to achieve.  Based on this, I'd consider a single AccountRepository, which has options to pull Users by Account (ex: findUsersInAccount(Account $account) ) Your concern about joins here is what makes me suspect this is the case.

Bounded Contexts - Be careful not to stuff everything into a single bounded context. Often, admin and public interfaces are performing entirely different business goals, and they can be separated as such. Mind you, if both are trutly just findAll() calls, ignore this, but I doubt this is the case. I don't know your application, but perhaps the admin side acts on multiple Accounts, whereas the public side only acts on a single one (the user's account). Having two different subdomains (or bounded contexts) is often better than one perfect one that is skewed trying to fit each.

Reality - Now, assuming what you have still satisfies the above and you are running into problems, wrapping both in a service is probably the way to go. That service can hide all of the repository access (from multiple repositories).

However, in the effort of good OO design, and especially DDD, I'd advise against the following:

Extending repositories from each other UNLESS it's abstract. Interfaces are often more appropriate here if you want to re-use patterns.

Building your repositories around your SQL schema. Don't assume a SQL back-end, as that mapping will be evident in your domain model; exactly where it's not allowed to be.

Anyway, without understanding your domain fully, it seems something like this should satisfy your needs:

```<code>interface AccountRepository
{
    function findUsersInAccount(Account $account);
}

interface UserRepository
{
    function findAll()
}
</code>```

Your domain model can expose multiple interfaces for its needs, while your actual database implementations of those repositories can be mashed together if needed. Just focus on what your domain needs, and worry about how it's implemented later.

Finally, DDD is meant for applications with complex domains. Applying it where it's not needed can lead to a lot of confusion because many of the benefits don't necessarily apply.

Title: Repository query conditions, dependencies and DRY

Body:
To keep it simple, let's suppose an application which has Accounts and Users. Each account may have any number of users. There's also 3 consumers of UserRepository:

An admin interface which may list all users

Public front-end which may list all users

An account authenticated API which should only list it's own users

Assuming UserRepository is something like this:

class UsersRepository extends DatabaseAbstraction {
    private function query() {
        return $this->database()->select('users.*');
    }
    public function getAll() {
        return $this->query()->exec();
    }
    // IMPORTANT:
    // Tons of other methods for searching, filtering,
    // joining of other tables, ordering and such...
}
```

<p>Keeping in mind the comment above, and the necessity to abstract user querying conditions, How should I handle querying of users filtering by <code>account_id</code>? I can picture three possible roads:</p>

<h3>1. Should I create an <code>AccountUsersRepository</code>?</h3>

<pre class="lang-php prettyprint-override"><code>class AccountUsersRepository extends UserRepository {
    public function __construct(Account $account) {
        $this->account = $account;
    }
    private function query() {
        return parent::query()
            ->where('account_id', '=', $this->account->id);
    }
}
</code>```

This has the advantage of reducing the duplication of UsersRepository methods, but doesn't quite fit into anything I've read about DDD so far (I'm rookie by the way)

2. Should I put it as a method on AccountsRepository?

class AccountsRepository extends DatabaseAbstraction {
    public function getAccountUsers(Account $account) {
        return $this->database()
            ->select('users.*')
            ->where('account_id', '=', $account->id)
            ->exec();
    }
}
```

<p><em>This requires the duplication of all <code>UserRepository</code> methods and may need another <code>UserQuery</code> layer, that implements those querying logic on chainable way.</em></p>

<h3>3. Should I query <code>UserRepository</code> from within my account entity?</h3>

<pre class="lang-php prettyprint-override"><code>class Account extends Entity {
    public function getUsers() {
        return UserRepository::findByAccountId($this->id);
    }
}
</code>```

This feels more like an aggregate root for me, but introduces dependency of UserRepository on Account entity, which may violate a few principles.

4. Or am I missing the point completely?

Maybe there's an even better solution?

Footnotes: Besides permissions being a Service concern, in my understanding, they shouldn't implement SQL query but leave that to repositories since those may not even be SQL driven.

Body:
There are a few principles in play here that may affect your design:

Aggregates - if Account is your top level item (aggregate root) for this aggregate, that should be your repository. You don't necessarily need one repository per table, as that breaks any domain encapsulation that you're trying to achieve.  Based on this, I'd consider a single AccountRepository, which has options to pull Users by Account (ex: findUsersInAccount(Account $account) ) Your concern about joins here is what makes me suspect this is the case.

Bounded Contexts - Be careful not to stuff everything into a single bounded context. Often, admin and public interfaces are performing entirely different business goals, and they can be separated as such. Mind you, if both are trutly just findAll() calls, ignore this, but I doubt this is the case. I don't know your application, but perhaps the admin side acts on multiple Accounts, whereas the public side only acts on a single one (the user's account). Having two different subdomains (or bounded contexts) is often better than one perfect one that is skewed trying to fit each.

Reality - Now, assuming what you have still satisfies the above and you are running into problems, wrapping both in a service is probably the way to go. That service can hide all of the repository access (from multiple repositories).

However, in the effort of good OO design, and especially DDD, I'd advise against the following:

Extending repositories from each other UNLESS it's abstract. Interfaces are often more appropriate here if you want to re-use patterns.

Building your repositories around your SQL schema. Don't assume a SQL back-end, as that mapping will be evident in your domain model; exactly where it's not allowed to be.

Anyway, without understanding your domain fully, it seems something like this should satisfy your needs:

interface AccountRepository
{
    function findUsersInAccount(Account $account);
}

interface UserRepository
{
    function findAll()
}

Your domain model can expose multiple interfaces for its needs, while your actual database implementations of those repositories can be mashed together if needed. Just focus on what your domain needs, and worry about how it's implemented later.

Finally, DDD is meant for applications with complex domains. Applying it where it's not needed can lead to a lot of confusion because many of the benefits don't necessarily apply.


问:
Javascript Naming Convention
I've been using Javascript for quite a while, but I've always ignored the common naming conventions that I see online (camelCase). I know it all depends on the developer's preference, but why camel case for Javascript?

I'm originally a PHP programmer and I kind of have my own naming convention and I use it everywhere I can, including Javascript. Well, I have to sacrifice my naming convention when it comes to Java though as the program flow depends on those names sometimes.

Anyway, my convention goes like:

```<code>var variable_name = 'I always use underscores to separate words';
var another_variable = 'I also tend to use single quotes all the time';

function epic_name_here (some_paramaters ...)
{
    // Curly brackets on separate lines
    do_something();
}

if (x == y)
{
    // Same goes here
}
</code>```

I have taken this kind of code-writing style from working a lot with phpBB, their docs encourage people to use this style.

Why do I see a lot of people writing Javascript in camelCase? And will it be a problem if I don't use it?

答:
Let's see what tell two most popular style conventions:

JavaScript naming rules in Google JavaScript style guide suggest camel case.

Douglas Crockford suggests to start the names with a lower case letter too in JavaScript: The Good Parts. In the same book, Douglas explains that by convention, objects which require new start with a capital letter (see page 123 Constructors and new).

why camel case for Javascript?

No reason. This is a common practice, that's all. Don't look for a proof that this style is undoubtedly better than any other.

Why do I see a lot of people writing Javascript in camelCase?

Because developers tend to be consistent with other developers who write in the same language. Given that camel case is a common practice, new developers would tend to follow it.

And will it be a problem if I don't use it?

Your code will be inconsistent with code written by other developers,

When working in a team, your colleagues may tell you that your style sucks and ask you to change it,

If you contribute to an open source project which uses camel case, and you chose a different convention, other contributors will definitely ask you to change your style,

Other people using your code may mistakenly use new when they shouldn't,

You'll do an additional effort when reading someone else's code. Other people will do an additional effort when reading yours. Neither you, nor others need to waste time for that,

If you use a linter (style checker), you'll have to rewrite the ruleset to fit your particular style. You could have spent this time to do something useful instead.

Title: Javascript Naming Convention


问:
Why aren't Entities allowed to reference other entities inside an aggregate except the root?
I have read in several places this following rule concerning Aggregates:

Entities in one aggregate can hold references to any other Aggregate Root, but never to an
  Entity or Value Object inside the other Aggregate.

What can go wrong if an Entity was holding a direct reference to an entity in another Aggregate root?

Can someone please explain why such rule is important? and preferably illustrate with an example, please?

答: The point of aggregate root is to encapsulate behavior of the whole through it's root. This simplifies the model, because you know any entity in aggregate will always be changed through only one entity, the root. By allowing entities to reference another entity, that is not a root in an aggregate, breaks this encapsulation.</p>


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
Maybe I'm misunderstanding, but would the following fit?

java.lang.Thread

must call thread.start() before thread.stop()

InputStream and OutputStream

should not call other methods after calling close()

ContentLicense: CC BY-SA 2.5


问:
Product backlog acceptance criteria
I read on a similar forum https://stackoverflow.com/questions/8117530/examples-for-acceptance-criteria-for-a-user-story about putting in the acceptance criteria for product backlog item.

I am working on a Scrum based project and I need more info as my backlog item is as follows -

UserProfiles ( I am using this in the title field in tfs 2013) and the description contains all the "As a user I want to be able to create new users and assign permissions'

The acceptance criteria talks about how the user interacts with the UI (as discussed in one of the answers in the above link - which is very logical)

For example

As the user clicks on the home button, system will bring up 3 options

And then the user can enter their user name

Is this the right approach I am using to use title for PBI and put the actual user story in description field in tfs

Thanks in advance

答:
It is one possible way, but strictly speaking there is not need for acceptance criteria as a story should be negotiable.

In other words, what constitutes a correct implementation of a story should be decided while it's being developed and not before.

That said, there could be some basic criteria that you might expect to see in a correct story, keeping in mind that stories are about "aims" and not "specs".

"A user can create another user" is a good candidate. "A user can set permissions for a user he created" is another good one. "As the user clicks on the home button, system will bring up 3 options" is not a good example of an acceptance test. It prescribes an interaction in advance.

Title: Product backlog acceptance criteria


问:
What's the most readable way of echoing from PHP?
Should I use

```<code><?php
    if(!$user->is_logged_in()){
        echo '<p id="login">Click here to log in</p>';
    }
?>
</code>```

or

```<code><?php
    if(!$user->is_logged_in()){
?>
    <p id="login">Click here to login.</p>
<?php
    }
?>
</code>```

? Why?

The first one will not have the HTML tags coloured so is less readable in code editors, but with the second one, it seems like it would be bad to take up three lines just to add a curly brace.

Which should I be using?

答:
Don't use inverted logic to execute statements. It raises the change that you'll miss the single ! operator and think it does the opposite of what it's doing.

```<code><?php
    if($user->is_session_empty()) {
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }
?>
</code>```

Use a function for more clarity, and keep statements on the first indent.

```<code><?php
    function foo($user) {
        if($user->is_logged_in()) {
            return;
        }
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }

    foo($user);
?>
</code>```

For logic in templates use endif instead of { }.

```<code><?php if($user->is_session_empty()): ?>
    <p id="login">Click <a href="login">here</a> to login.</p>
<?php endif; ?>
</code>```

Readability of source code is an ambiguous guideline. What is readable for one person is not so readable for another. It's better to focus on maintainable code. That is code where you can navigate quickly, is kept clean and short. Objects, functions and files all have a single purpose.

There is no correct answer to your question.

Body:
Should I use

```<code><?php
    if(!$user->is_logged_in()){
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }
?>
</code>```

or

```<code><?php
    if(!$user->is_logged_in()){
?>
    <p id="login">Click <a href="login">here</a> to login.</p>
<?php
    }
?>
</code>```

? Why?

The first one will not have the HTML tags coloured so is less readable in code editors, but with the second one, it seems like it would be bad to take up three lines just to add a curly brace.

Which should I be using?

Body:
Don't use inverted logic to execute statements. It raises the change that you'll miss the single ! operator and think it does the opposite of what it's doing.

<?php
    if($user->is_session_empty()) {
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }
?>

Use a function for more clarity, and keep statements on the first indent.

<?php
    function foo($user) {
        if($user->is_logged_in()) {
            return;
        }
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }

    foo($user);
?>

For logic in templates use endif instead of { }.

<?php if($user->is_session_empty()): ?>
    <p id="login">Click <a href="login">here</a> to login.</p>
<?php endif; ?>

Readability of source code is an ambiguous guideline. What is readable for one person is not so readable for another. It's better to focus on maintainable code. That is code where you can navigate quickly, is kept clean and short. Objects, functions and files all have a single purpose.

There is no correct answer to your question.


答:
According to this study:

results indicate a significant improvement in time and lower visual
  effort with the underscore style. The interaction of Experience with
  Style indicates that novices benefit twice as much with respect to
  time, with the underscore style.

so if that matters to you go ahead with underscore style.

Title: Javascript Naming Convention

Body:
I've been using Javascript for quite a while, but I've always ignored the common naming conventions that I see online (camelCase). I know it all depends on the developer's preference, but why camel case for Javascript?

I'm originally a PHP programmer and I kind of have my own naming convention and I use it everywhere I can, including Javascript. Well, I have to sacrifice my naming convention when it comes to Java though as the program flow depends on those names sometimes.

Anyway, my convention goes like:

```<code>var variable_name = 'I always use underscores to separate words';
var another_variable = 'I also tend to use single quotes all the time';

function epic_name_here (some_paramaters ...)
{
    // Curly brackets on separate lines
    do_something();
}

if (x == y)
{
    // Same goes here
}
</code>```

I have taken this kind of code-writing style from working a lot with phpBB, their docs encourage people to use this style.

Why do I see a lot of people writing Javascript in camelCase? And will it be a problem if I don't use it?


答:
I have 6 years experience in PHP and I have actually had big issues with the readability and the maintenance of HTML code in strings.
There is not any rule anywhere, but I think it is better to have the HTML separate from PHP.

It is easily readable in any editor (notepad++, sublime... e.t.c.). The HTML is colored and the PHP is colored. Even at the question you can see the difference :)

It is easier for a designer to change only the HTML code and not do any mistake in the PHP code accidentally.

It is easier if you want to move to a template library. For example, let's say that you want to use twig (http://twig.sensiolabs.org/). You can then more easily transform

this:

```<code>    <?php foreach ($users as $user) { ?>
        <div class="username">
            <div class="name"><?=$user->name?></div>
            <div class="lastname"><?=$user->lastname?></div>
        </div>
    <?php }?>
</code>```

to this:

```<code>{% for user in users %}
    <div class="username">
        <div class="name">{{ user.name }}</div>
        <div class="lastname">{{ user.lastname }}</div>
    </div>
{% endfor %}
</code>```

Title: What's the most readable way of echoing from PHP?

Body:
I have 6 years experience in PHP and I have actually had big issues with the readability and the maintenance of HTML code in strings.
There is not any rule anywhere, but I think it is better to have the HTML separate from PHP.

It is easily readable in any editor (notepad++, sublime... e.t.c.). The HTML is colored and the PHP is colored. Even at the question you can see the difference :)

It is easier for a designer to change only the HTML code and not do any mistake in the PHP code accidentally.

It is easier if you want to move to a template library. For example, let's say that you want to use twig (http://twig.sensiolabs.org/). You can then more easily transform

this:

    <?php foreach ($users as $user) { ?>
        <div class="username">
            <div class="name"><?=$user->name?></div>
            <div class="lastname"><?=$user->lastname?></div>
        </div>
    <?php }?>

to this:

{% for user in users %}
    <div class="username">
        <div class="name">{{ user.name }}</div>
        <div class="lastname">{{ user.lastname }}</div>
    </div>
{% endfor %}


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Icon-style expressions with built-in backtracking.

Python gets a lot of the Icon generator benefits - and does a better job of them in general, IMO. And in principle the backtracking was just a kind of exception throw, but it was the simplicity of expressions the rough equivalent of...

```<code>x = (a / b) else c;
</code>```

to handle fail-cases like division by zero.

Where Icon went nuts - no boolean-returning comparison operators. The comparisons always either succeeded or triggered backtracking, and there was some other semantic issue which I'm now desperately trying to remember that... well, let's just say it's probably more repressed than forgotten.

I always thought they should have an if expression with no else part - if (condition, success-value) kind of thing, backtracking if the condition returns false - and drop the weird comparisons.

EDIT I remember - obvious really. A comparison with two arguments either succeeds or fails - it doesn't compute a new value to return. So when it succeeds, what does it return? Answer - one of the arguments. But if you write a > b, which is the logical argument to return - a or b? And what if you write b < a instead? I think it always returned the right argument, which makes as much sense as anything, but it still usually seemed like the wrong argument to me.

Body:
Icon-style expressions with built-in backtracking.

Python gets a lot of the Icon generator benefits - and does a better job of them in general, IMO. And in principle the backtracking was just a kind of exception throw, but it was the simplicity of expressions the rough equivalent of...

x = (a / b) else c;

to handle fail-cases like division by zero.

Where Icon went nuts - no boolean-returning comparison operators. The comparisons always either succeeded or triggered backtracking, and there was some other semantic issue which I'm now desperately trying to remember that... well, let's just say it's probably more repressed than forgotten.

I always thought they should have an if expression with no else part - if (condition, success-value) kind of thing, backtracking if the condition returns false - and drop the weird comparisons.

EDIT I remember - obvious really. A comparison with two arguments either succeeds or fails - it doesn't compute a new value to return. So when it succeeds, what does it return? Answer - one of the arguments. But if you write a > b, which is the logical argument to return - a or b? And what if you write b < a instead? I think it always returned the right argument, which makes as much sense as anything, but it still usually seemed like the wrong argument to me.


问:
Several interdependent models, each with several data sources — how to avoid hell and nightmare
I'm currently working on a project that requires a complicated model structure and I'm struggling with picking the right architecture.

First of all, there are several interdependent models. Change in one model can trigger changes in several other models. For example, user inputs a query, first model checks the database for type of the query and the second model requests its data depending on that query type.

Secondly, each model can have several data sources. Data sources are used conditionally, dependent on system configuration.

The app needs to function seamlessly, — for example, if one data source doesn't return required information, model must try and use another one.

An important thing also is that the codebase will eventually be expanded with other models. So models, data sources etc. must be very modular.

Currently there are several ways I can organise the model layer:

'Dumb' models re-created by factory objects when input data (or a related model) changes. Model dependencies are resolved in an operation object, encapsulating the whole update routine. Operation object is configured and run by a domain model. I don't know where to inject a data source though.

'Smart' models with update logic encapsulated in them. Each model queries a sort of a mapper/data-source-manager, which works as a proxy for different data sources. Models report their updates to a domain model. Dependencies are resolved by a model-controller or dependency manager object.

Which architecture is more appropriate here?

I'm leaning towards the first one as it is (to my mind) better to work with immutable models, updating the whole tree on change of input. This approach gives several benefits: for example it is easier to serialize as the presence of model equals to a finite state. But I'm really unsure about data sources...

答:
"There are several interdependent models. Change in one model can trigger changes in several other models."

This is exactly what you should avoid.  Welcome to Hell.

I'm getting a sense from your question that your head is in the technology more than in the business.  I think the answer is for you to change your focus slightly...

The key to minimizing dependencies is in how you divide a business problem in order to solve it.  It sounds like the existing design is already facing some challenges.  This makes your job harder as you not only have to understand and interface with business needs, but also with legacy systems that do not currently meet those needs.

I would give the technical solution a rest and go back to the business and ask them 2 questions (again): What is the absolute minimum you need from the system on day 1?  Where do you see the system capabilities going in the future?  Any solution has limits and benefits.  Communicate the relevant limits/benefits to the business (leaving out the technical details) and find out how well they fit with the business needs.

With the business, design for the future, but then pick a subset of that design to implement for the present.  That way you keep it as simple as possible, without completely walling yourself off from the changes you are most likely to have to make to it.  Another little trick I sometimes play is to imagine that the system the business and I just designed is all implemented and then imagine how it will be used with the business.  Often this teases out critical design considerations that were overlooked.  Use cases anyone?  How the business will use the system is super-critical...

I don't know which of your proposed solutions you'll end up choosing, or if you'll come up with a new solution.  No matter how smart I was, if I were to pick one for you, it would not be as helpful as for you to pick one in tandem with the business.  The one that helps the business the most is the best way to go.

I hope that helps.  24 views, 7 hours, no answers or comments... I thought I'd give it a stab.

P.S. If you have to have fail-over from one data-source to another, that begs for a level of indirection somewhere.  Ultimately, I'd want a layer in my code that I can ask for the data I need and if it's available at all, that layer will just return it.  Then I can write relatively dumb clients that just say, "Get me the data" and not, "Get me the data using SQL-flavor A from Source #1... then if that doesn't work, try using another query language from source #2..."  Maybe a JSON/XML/YAML service can encapsulate that complexity?  Maybe it returns a little metadata footnote in addition to the data: "From source C because A took too long to respond and B gave an error."

I'm just latching onto the fail-over because it's the clearest requirement I got from your question.


答:
MainMa said it all insofar as camelCase (from my point of view, underscores remind me of Cobol coding :)

Insofar as single versus double quotes:  that convention probably migrated from C, where single quotes are used for chars & doubles for strings.  In javascript, it doesn't matter which you use except in such cases as:

var myStr =  "He said, 'She said, it's dark in here. Where's Kevin's flashlight?'"
 Because the single quote is used for inner quotes, apostrophes and contractions, it makes more sense to use double quotes for the string assignment.  Doing it the other way would require escaping, at the least, the contraction.

Title: Javascript Naming Convention


问:
Further decoupling using static libraries
I've been thinking for a while about reasons that prevent a lot of programmers — myself first of all — from writing clean, modular and expressive code while developing, for example, CocoaTouch apps.

What I discovered is that my top-three of reasons are following:

UI code. Device-specific UI/UX, general clutter, 'quick fixes and workarounds' and so on.

Poor Controller-View decoupling. Sometimes Controller ends up doing job that the View is responsible for.

Sparse test harness.

Of course, those problems stem from lack of discipline or habit to write clean code. But it is difficult to discipline yourself if the environment allows you not to do that.

It is easy to sort laundry if you have a set of dedicated drawers, but if you have one drawer, it will slowly turn into mess — unless you are very disciplined.

And then I tried to apply that idea of 'sorting drawers' to address my code problems — and I thought that it is possible to sort MVP components as follows:

Model is actually a framework of classes responsible for dealing with data. Model is reusable, as it is a set of routines to work with data.

View is actually a framework of classes responsible for presenting information graphically. It doesn't depend that much on environment and it definitely can be reused.

Controller is a framework of classes responsible for coordination of aforementioned layers and working with user interaction paths. Application itself is something like (?) a big controller. Since it glues together a defined set of models to a defined set of views, it is not reusable and depends heavily on those + platform etc.

So given the M and V are somewhat reusable, and C is not — maybe it makes sense to force separation of M and V? The best way to ensure they are separated is to put them in static libraries. After that they can be linked to the app, which contains only controller code.

This approach seems to me quite good because:

only controller depends on something here

developer can write separate test suites for those modules

user interface classes can be reused in other apps easily

model classes can be extracted to cross-platform codebase while maintaining the old facade

commits are limited to three really distinct modules — what's more distinct than a separate library?

What do you think? Does this sound like an idea to follow?

答:
MVC is an old and well used pattern that started with desktop apps.  It can sort-of sometimes apply to web-apps as well.  People have done well even when they somewhat misapplied this pattern (e.g. to a web app), so I can't discourage you there.

One thing to consider as an alternative is a service.  Google Steve Yegge's Service Rant.  I think it's titled somethings like "Why Amazon is better than Google."  If you have a good front-end coder on the team, you can basically leave the View on the client/browser.  Then you need to define a set of data view and update calls between client and server.  I'm assuming, of course, that you have a central server.  Maybe use JSON to communicate.  Then your back-end just does security/authentication (who can view or update what data) and basically translates canned queries into JSON and vice-versa.  Any finer-grained interaction can happen entirely on the client, which saves bandwidth and simplifies both client and server code at the same time by removing dependencies and providing a more sensible separation of concerns.

Now, if your app happens entirely on one device, maybe MVC is all you need.  Just providing another perspective for your consideration.


问:
Why is it so hard to recruit for compiler[-related] jobs?
Last week, a few colleauges and I were participating in career fairs at three major universities (two here in the US and one in England), where we were trying (without much success) to recruit for several compiler positions, ranging from internship, to entry-level, to more senior, for our team.

To our surprise, 80% of the students that we talked to responded somewhere a long the line of "I want to build Ansroid apps", when asked what they were interested in doing. (And the other 20%? "iPhone apps"! )
Some even expressed openly that they did not "want to build a compiler, ..., it's boring"; they said and I quoted.

So what is it about mobile apps that is so appealing to (young ?) "developers" these days? And by the same token, why is compiler such a"boring" topic to them? ( I don't necessarily think these two are mutually exclusive. One can certainly build a compiler for a mobile phone, but that's beside the point)

What can we do, if anything, to attract more talents, or even just interested candidates?

答:
Well first, I'd like to break the stereotype: I'm 17 and contribute to/have written several compilers and rather like them.

To answer the question, a teenager's primary interaction with a computer isn't examining an IL dump of some compiler, but through apps/websites/video games. So it's only a natural step that if someone decides they want to start programming, why not make something they already "know" a bit about and like.

It doesn't help that there's a strong perception that real jobs are centered around the web and games. So already, you're fighting the "Oooh shiny" response of teenagers and the fact that they think that's where the money is.

Finally, no one's teaching compilers anymore! Many compilers courses are relegated to optional graduate courses. Even when many take a compilers course, half of the course is spent on the parser, which is arguably one of the least interesting bits of a compiler. So those who make the effort to register come away going, "Ok, We write the parser, then magic, then codegen". Not exactly thrilling compared to Angry Birds.

Now recruiting is generally hard, but I think you'll find it harder than most since many undergraduates who are willing to devote their own time to figuring out how to write or contribute to a compiler already have plans. In which case Joel's advice on getting good devs is relevant.


问:
What language to use for prototyping and creating quick scripts?
Right now, I use Python for my quick scripts and prototypes (e.g. algorithms, my pseudocode is very Python-like as well). The oher languages that I am familiar with include Java, C, x86 Assembly and Scheme, and Python is pretty much the best for this among these in my opinion.

Perl gets a lot of rep for this over and over again, and I have heard that Ruby isn't bad either, and the Python community praises Python for this too. What language (could be another one than these 3) do you think is the best programming language for:

Creating quick prototypes of applications or algorithms

Creating simple scripts for small, repetitive tasks

Important features for such languages include:

Little boilerplate code, not too verbose

(Very) high-level

Interpreted

Good and comprehensive standard library

答:
My two cents for an almost 3 year old question:

Ruby is perfect for custom DSL, and prototyping is a task in need of those.

you want a new efficient mini language for a very specific task

you want contributions from someone with different skills than yours.


问:
How to refactor out static members of basic classes
Currently I am working on C++ project, which can be classified as "legacy" project. A lot of poor written code was committed because of lack of experience and under the pressure of deadlines. When I try to fix bugs I eventually make the new one.

Recently I got some more free time and I want to make this project better. To be exact I want to begin using TDD. However, it turned out not so easy. I faced the problem that I can't write test for any class. Singletons are everywhere. Even basic classes uses static members.

For instance, in project we widely use "Numeric" class (which is wrapper for decNumber C library for decimal computation). This class has static member to keep a context (precision, rounding mode, etc.). It is obvious that I need to refactor this class to avoid static fields.

Immediately I thought about dependency injection and a factory pattern. The factory will keep the single context, every user class should create Numeric instances only using that factory. But the code is going to be messy because the factory should be injected in every class which wants to construct "Numeric" instance.

Which pattern I can use for this case? Which one makes me sure that every instance of "Numeric" class uses single shared state?

P.S.: There are significant parallels with this question - Dependency injection ; good practices to reduce boilerplate code.

答:
It depends what platform you're working on - Microsoft has Moles (called something else now) that allows you to replace objects in your program with other objects, so you can replace the singletons with ones specific to your test scenarios. Its wonderful and a damn sight easier to use than mangling your code to use interfaces everywhere so lesser unit test systems can work.

But, generally TDD is frowned upon for legacy code - as I mentioned above, when writing code designed to be test driven, you have to code it in a certain way. Not easy to do with existing codebase which is never written like that (which suggests to me that the TDD way of coding is not natural).

I would forget putting things like DI in, as you'll only make the system even more complicated and messy. You can change your static methods on your class, remove the static, make the constructor set a default, and allow the class to set different properties - though, if the numeric's static is always a constant value, then what's the point of changing it so each object carries the state rather than the class? Just so you can use TDD? When you do this, you're introducing more complexity, not less.

For legacy code, there is no easy way out other than to split sections off and attempt to isolate them. Then take the time required to understand the rest of the system. There's no silver bullet here, you will just have to get your hands dirty.


答:
I really like the book Working Effectively with Legacy Code, by Michael Feathers, for this purpose.  I'll go ahead and disagree with gbjbaanb here; testing is very useful for legacy code, but you may need to approach it at a higher level than individual classes at first. Start by writing functional tests: mock out an object, send it through the system, and see if it comes out as expected on the other end. This process is painful, but necessary.

Once you have this sort of testing around the portions of the code that you want to refactor, you can begin making large-scale refactors, like taking static methods out of the classes you're testing, and then begin expanding the scope of your refactoring.

Title: How to refactor out static members of basic classes

Body:
Currently I am working on C++ project, which can be classified as "legacy" project. A lot of poor written code was committed because of lack of experience and under the pressure of deadlines. When I try to fix bugs I eventually make the new one.

Recently I got some more free time and I want to make this project better. To be exact I want to begin using TDD. However, it turned out not so easy. I faced the problem that I can't write test for any class. Singletons are everywhere. Even basic classes uses static members.

For instance, in project we widely use "Numeric" class (which is wrapper for decNumber C library for decimal computation). This class has static member to keep a context (precision, rounding mode, etc.). It is obvious that I need to refactor this class to avoid static fields.

Immediately I thought about dependency injection and a factory pattern. The factory will keep the single context, every user class should create Numeric instances only using that factory. But the code is going to be messy because the factory should be injected in every class which wants to construct "Numeric" instance.

Which pattern I can use for this case? Which one makes me sure that every instance of "Numeric" class uses single shared state?

P.S.: There are significant parallels with this question - Dependency injection ; good practices to reduce boilerplate code.


答:
Why is it so hard to recruit for compiler[-related] jobs?

Better phrased, your question is asking why it is hard to recruit for jobs that aren't currently trendy.

And the rephrasing gets at the core of the challenge - trends.  In and of themselves, there isn't a whole lot wrong with trends.  They'll always occur to some varying degree.

Any company or programming domain that's outside of what's currently trendy will have a bit harder of a time in recruiting candidates.  It's just the nature of the beast.

But trends come and go.  For example, in the late '90s and perhaps early '00s, RedHat was on a tear and "everybody who was anybody"* wanted to work there.  Then the economy changed up a bit, attention focused elsewhere and the industry picked up new darlings for the popularity contest.

 * Okay, that's a bit of hyperbole but that's the nature of trends

What can we do, if anything, to attract more talents, or even just interested candidates?

First off, make sure that you're promoting the interesting bits of those jobs.  Every job has grunt work associated with it, and we put up with those aspects for the fun parts of our jobs.  Make sure you lead with the fun parts when describing the gig.

Second, make sure you promote the fun and interesting aspects of your employer.  For example, if you're recruiting in both the US and England then advertise your international presence.  If you send developers overseas for periods of cross-training, point that out.  Many developers are interested in opportunities to travel internationally and increase the breadth of their skills.

Third, make sure you're getting your company's name out there outside of recruiting season.  Trends come and go, but you combat the trends by making sure the company's brand has at least been heard of in the off-season.  There's a really large, international software firm based in Armonk that advertises constantly in order to make sure their name is known.  You probably don't have the same advertising budget as they do, but you can target the campuses you're interested in recruiting from.

Fourth, always hire someone new every year especially in the lean years.  It doesn't have to be the same amount as a growth year, but you need to hire at least one person.  That same firm I mentioned has that type of policy in place for a host of reasons.  Word will get around campus that you guys always have a slot available even in the worst of times.  That security and economic strength will generate interest in your company.

Fifth, make sure that the benefits and salary your company offers are competitive.  Word does get around about the quality of offers made.  The students and the campus career center know who's cheap and who's competitive.  Don't be cheap if you're not getting enough candidates.

Sixth, make sure that students know what skills you're looking for.  They will have limited time actually developing compilers, perhaps only a semester or two of experience.  If their perception is that you are looking for years of experience or only those who have done deep dives into compilers, then they're not going to apply for those jobs.  Likewise, candidates may need a degree of reassurance that you'll help train them in bridging from academic compiler design to industrial compiler work.

Finally, consider donating equipment or software or both to the engineering labs.  If the students don't know who your company is, then provide them the opportunity to find out about your product.  Sun Microsystems did really well for a while with this approach.  Giving free or low-cost gear to universities is a great way to make sure students know about your kit.

Body:
Last week, a few colleauges and I were participating in career fairs at three major universities (two here in the US and one in England), where we were trying (without much success) to recruit for several compiler positions, ranging from internship, to entry-level, to more senior, for our team.

To our surprise, 80% of the students that we talked to responded somewhere a long the line of "I want to build Ansroid apps", when asked what they were interested in doing. (And the other 20%? "iPhone apps"! )
Some even expressed openly that they did not "want to build a compiler, ..., it's boring"; they said and I quoted.

So what is it about mobile apps that is so appealing to (young ?) "developers" these days? And by the same token, why is compiler such a"boring" topic to them? ( I don't necessarily think these two are mutually exclusive. One can certainly build a compiler for a mobile phone, but that's beside the point)

What can we do, if anything, to attract more talents, or even just interested candidates?


问:
Why most "well-known" imperative/OO languages allow unchecked access to types that can represent a 'nothing' value?
I have been reading about the (un)convenience of having null instead of (for example) Maybe. After reading this article, I am convinced that it would be much better to use Maybe (or something similar). However, I am surprised to see that all the "well-known" imperative or object oriented programming languages still use null (which allows unchecked access to types that can represent a 'nothing' value), and that Maybe is mostly used in functional programming languages.

As an example, look at the following C# code:

```<code>void doSomething(string username)
{
    // Check that username is not null
    // Do something
}
</code>```

Something smells bad here... Why should we be checking if the argument is null? Shouldn't we assume that every variable contains a reference to an object? As you can see, the problem is that by definition almost all variables can contain a null reference. What if we could decide which variables are "nullable" and which not? That would save us a lot of effort while debugging and looking for a "NullReferenceException". Imagine that, by default, no types could contain a null reference. Instead of that, you would state explicitly that a variable can contain a null reference, only if you really need it. That is the idea behind Maybe. If you have a function that in some cases fails (for example division by zero), you could return a Maybe<int>, stating explicitly that the result may be an int, but also nothing! This is one reason to prefer Maybe instead of null. If you are interested in more examples, then I suggest to read this article.

The facts are that, despite the disadvantages of making most types nullable by default, most of the OO programming languages actually do it. That is why I wonder about:

What kind of arguments would you have to implement null in your programming language instead of Maybe? Are there reasons at all or is it just "historical baggage"?

Please ensure you understand the difference between null and Maybe before answering this question.

答:
My understanding is that null was a necessary construct in order to abstract programming languages out of assembly.1  Programmers needed the ability to indicate that a pointer or register value was not a valid value and null became the common term for that meaning.

Reinforcing the point that null is just a convention to represent a concept, the actual value for null used to be able to / can vary based upon programming language and platform.

If you were designing a new language and wanted to avoid null but use maybe instead, then I would encourage a more descriptive term such as not a valid value or navv to indicate the intent.  But the name of that non-value is a separate concept from whether you should allow non-values to even exist in your language.

Before you can decide on either of those two points, you need to define what the meaning of maybe would mean for your system.  You may find it's just a rename of null's meaning of not a valid value or you may find it has a different semantic for your language.

Likewise, the decision on whether to check access against null access or reference is another design decision of your language.

To provide a bit of history, C had an implicit assumption that programmers understood what they were attempting to do when manipulating memory.  As it was a superior abstraction to assembly and the imperative languages that preceded it, I would venture that the thought of safe-guarding the programmer from an incorrect reference hadn't come across their mind.

I believe that some compilers or their additional tooling can provide a measure of checking against invalid pointer access.  So others have noted this potential issue and taken measures to protect against it.

Whether or not you should allow it depends upon what you want your language to accomplish and what degree of responsibility you want to push to users of your language.  It also depends upon your ability to craft a compiler to restrict that type of behavior.

So to answer your questions:

"What kind of arguments…" - Well, it depends upon what you want the language to do.  If you want to simulate bare-metal access then you may want to allow it.

"is it just historical baggage?"  Perhaps, perhaps not.  null certainly had / has meaning for a number of languages and helps drive the expression of those languages.  Historical precedent may have affected more recent languages and their allowing of null but it's a bit much to wave your hands and declare the concept useless historical baggage.

1 See this Wikipedia article although credit is given for to Hoare for null values and object-oriented languages.  I believe the imperative languages progressed along a different family tree than Algol did.


答: Maybe is a very functional way of thinking of a problem--there is a thing, and it may or may not have a value that is defined. In an object-oriented sense, however, we replace that idea of a thing (no matter if it has a value or not) with an object. Clearly, an object has a value. If it doesn't, we say the object is null, but what we really mean is that there isn't any object at all. The reference we have to the object points to nothing. Translating Maybe into an OO concept does nothing novel--in fact, it just makes for more greatly cluttered code.  You still have to have a null reference for the value of the Maybe<T>. You still have to do null checks (in fact, you have to do a lot more null checks, cluttering your code), even if they are now called "maybe checks". Sure, you'll write more robust code as the author claims, but I'd argue that it is only the case because you've made the language far more abstract and obtuse, requiring a level of work that is unnecessary in most cases. I'd willingly take a NullReferenceException once in a while than deal with spaghetti code doing a Maybe check every time I access a new variable.

Title: Why most "well-known" imperative/OO languages allow unchecked access to types that can represent a 'nothing' value?

Body:
I have been reading about the (un)convenience of having null instead of (for example) Maybe. After reading this article, I am convinced that it would be much better to use Maybe (or something similar). However, I am surprised to see that all the "well-known" imperative or object oriented programming languages still use null (which allows unchecked access to types that can represent a 'nothing' value), and that Maybe is mostly used in functional programming languages.

As an example, look at the following C# code:

```<code>void doSomething(string username)
{
    // Check that username is not null
    // Do something
}
</code>```

Something smells bad here... Why should we be checking if the argument is null? Shouldn't we assume that every variable contains a reference to an object? As you can see, the problem is that by definition almost all variables can contain a null reference. What if we could decide which variables are "nullable" and which not? That would save us a lot of effort while debugging and looking for a "NullReferenceException". Imagine that, by default, no types could contain a null reference. Instead of that, you would state explicitly that a variable can contain a null reference, only if you really need it. That is the idea behind Maybe. If you have a function that in some cases fails (for example division by zero), you could return a Maybe<int>, stating explicitly that the result may be an int, but also nothing! This is one reason to prefer Maybe instead of null. If you are interested in more examples, then I suggest to read this article.

The facts are that, despite the disadvantages of making most types nullable by default, most of the OO programming languages actually do it. That is why I wonder about:

What kind of arguments would you have to implement null in your programming language instead of Maybe? Are there reasons at all or is it just "historical baggage"?

Please ensure you understand the difference between null and Maybe before answering this question.


答:
Actually, null is a great idea. Given a pointer, we want to designate that this pointer does not reference a valid value. So we take one memory location, declare it invalid, and stick to that convention (a convention sometimes enforced with segfaults). Now whenever I have a pointer I can check if it contains Nothing (ptr == null) or Some(value) (ptr != null, value = *ptr). I want you to understand that this is equivalent to a Maybe type.

The problems with this are:

In many language the type system does not assist here to guarantee a non-null reference.

This is historical baggage, as many mainstream imperative or OOP languages have only had incremental advances in their type systems when compared to predecessors. Small changes have the advantage that new languages are easier to learn. C# is a mainstream language that has introduced language-level tools to better handle nulls.

API designers might return null on failure, but not a reference to the actual thing itself on success. Often, the thing (without a reference) is returned directly. This flattening of one pointer level makes it impossible to use null as a value.

This is just laziness on the designer's side and can't be helped without enforcing proper nesting with a proper type system. Some people might also try to justify this with performance considerations, or with the existence of optional checks (a collection might return null or the item itself, but also provide an contains method).

In Haskell there is a neat view onto the Maybe type as a monad. This makes it easier to compose transformations on the contained value.

On the other hand, low-level languages like C barely treat arrays as a separate type, so I'm not sure what we're expecting. In OOP languages with parameterized polymorphism, a runtime-checked Maybe type is rather trivial to implement.


答:
Boring Company Because they think building a mobile app is the path to the next "big" thing, so companies who build those, are more exciting and offer greater opportunities. Let's get funded, go public and become millionaires. Can't do that with a compiler. Certainly, the best thing about your company isn't getting to build compilers. Or is it?

Boring People It's hard to recruit the types of devs you need, so step up your game.  Get more creative in your recruiting by attaching yourselves to professors who teach compiler classes. Find their best students and court them. Don't wait for career day. Everybody wants to be wanted and to prove that, offer a signing bonus for doing an internship.

Being Marketable they may not see a career path in your product/technology area. It's up to you to convince them this isn't a dead end. You want to build mobile apps kid? You better learn how to work with a shortage of memory. You will learn that at our company to such a level it will put you in the top 1% of mobile devs should you choose to switch. Make sure they understand the pitfalls of some mobile dev jobs.

Writing Code for People Sometimes it can be more liberating to write code that writes code. Avoid the customers that want you to add features so useless they suck your will to live. Can you fix that line in your GUI that is a pixel off?

Steve Jobs approached the CEO of Pepsi and asked, "Do you want to sell sugar water all your life or change the world?"  I wonder what Dell would have said? "Come with us and we'll save  3 cents on every chip we buy!"

Title: Why is it so hard to recruit for compiler[-related] jobs?


答:
I believe it is primarily historical baggage.

The most prominent and oldest language with null is C and C++. But here, null does makes sense. Pointers are still quite numerical and low-level concept. And how someone else said, in the mindset of C and C++ programmers, having to explicitly tell that pointer can be null doesn't make sense.

Second in line comes Java. Considering Java developers were trying to get closest to C++, so they can make transition from C++ to Java simpler, they probably didn't want to mess with such core concept of the language. Also, implementing explicit null would require much more effort, because you have to check if non-null reference is actually set properly after initialization.

All other languages are same as Java. They usually copy the way C++ or Java does it, and considering how core concept of implicit null of reference types is, it becomes really hard to design a language that is using explicit null.


答:
I think this is because functional programming is much concerned about types, especially types that combine other types (tuples, functions as first class types, monads, etc.) than object-oriented programming does (or at least initially did).

Modern versions of the programming languages I think you're talking about (C++, C#, Java) are all based on languages that didn't have any form of generic programming (C, C# 1.0, Java 1). Without that, you still can bake some kind of difference between nullable and non-nullable objects into the language (like C++ references, which can't be null, but are also limited), but it's much less natural.


问:
Emulation of MMU accessing the contents of the registers
I'm having a play around with emulating a simple old CPU.

I've set the structure up, so far anyway, as follows:

The device is the main and creates an instance of the CPU. The CPU then creates instances of the registers, clocks and MMU.

I'm in the position where the MMU needs to access the contents of the registers, how to do this? I figure I could probably bodge something together by passing the entire register object to the MMU when it's called but that seems unwieldy.

The other thing I thought to do would be to initialise the MMU with the register object in the constructor. If I'm not mistaken that will still reference the same object? Meaning any changes I do to the registers in the MMU will affect the whole system?

答: The second part of your question reads like the classic reference versus copy issue with objects. If you initialise your MMU class with a reference to the registers then that reference points to the true register object (think of a reference as an automatically dereferenced pointer). If you copy the register object in your constructor then that's all you have - a snapshot copy of the state at the time of construction.</p>


问:
Concrete types - as described by Stroustrup - C++ Programming Language 4th ed
I'm having a hard time with this concept.  What is Stroustrup getting at here?  What is special about a class whose "representation is part of its definition"? What does a "concrete type" contrast with? (I assume it contrasts with "abstract type", but since, AFAIK, you can't even bring an instance of an abstract type into existence, it seems obvious you couldn't place that on the stack, initialize it, etc.)

Is there such a thing as a class I could instantiate that would NOT fit this description of a "concrete class"?  Normally I find BS very easy to follow, but I'm missing the point here.

The basic idea of concrete classes is that they behave “just like
built-in types.” For example, a complex number type and an
infinite-precision integer are much like built-in int, except of
course that they have their own semantics and sets of operations.
Similarly, a vector and a string are much like built-in arrays, except
that they are better behaved (§ 4.2, § 4.3.2, § 4.4.1).

The defining
characteristic of a concrete type is that its representation is part
of its definition. In many important cases, such as a vector, that
representation is only one or more pointers to more data stored
elsewhere, but it is present in each object of a concrete class.... In
particular, it allows us to

• place objects of concrete types on the
stack, in statically allocated memory, and in other objects (§ 6.4.2);

• refer to objects directly (and not just through pointers or
references);

• initialize objects immediately and completely (e.g.,
using constructors; § 2.3.2); and

• copy objects (§ 3.3).

Stroustrup, Bjarne (2013-07-10). The C++ Programming Language (4th
Edition) (Section 16.3 Concrete Classes; Kindle Locations 2373-2386). Pearson Education. Kindle
Edition.

答:
You've pretty much got it right, a concrete type is something that you can create an instance of, while an abstract type is not. For example, consider a typical pedagogical hierarchy such as:

```<code>class animal {
    virtual void noise() = 0;
}
class dog: public animal {
    void noise() { cout << "bark\n"; }
public:
    human *master;
}
class cat: public animal {
    void noise() { cout << "meow\n"; }
public:
    std::vector<human *> slaves;
}
</code>```

You can create instances of dog or cat because they are concrete, and not abstract. On the other hand, you can't create an instance of an animal, but only hold a pointer (or refernce) to one. For example:

```<code>void hungry(animal *a) {
    a->noise();
}
</code>```

In terms that Stroustrup is using, the representation of an animal is not included in the definition of class animal. The representation for a particular kind of animal is described in a subclass, here either dog or cat.

Body:
You've pretty much got it right, a concrete type is something that you can create an instance of, while an abstract type is not. For example, consider a typical pedagogical hierarchy such as:

class animal {
    virtual void noise() = 0;
}
class dog: public animal {
    void noise() { cout << "bark\n"; }
public:
    human *master;
}
class cat: public animal {
    void noise() { cout << "meow\n"; }
public:
    std::vector<human *> slaves;
}

You can create instances of dog or cat because they are concrete, and not abstract. On the other hand, you can't create an instance of an animal, but only hold a pointer (or refernce) to one. For example:

void hungry(animal *a) {
    a->noise();
}

In terms that Stroustrup is using, the representation of an animal is not included in the definition of class animal. The representation for a particular kind of animal is described in a subclass, here either dog or cat.


答:
It seems a term used by BS with a meaning which only him is using AFAIK.  I'm not sure I understand fully what he intend.

First a citation from the same section:

Such types are called concrete types or concrete classes to distinguish them from abstract classes and classes in class hierarchies.

So for him a a non abstract descendant of an abstract class is not a concrete class (which isn't a nuance I'm used to, the familiar usage for me is that all non abstract classes are concrete), at least if than inheritance is not an implementation detail. His concrete classes seems to be standalone utilities.

Another concrete/abstract dichotomy I'm familiar with is for data structure.  An abstract data structure is defined by its operation (say a Dictionary provide look up, insertion, ...)  A concrete data structure states how those are provided (an hash table for instance).  His insistence that representation is exposed is perhaps related to that (probably due to the influence of the representation on complexity).

Stepanov and McJones in Elements of Programming are using a concept of Regular types. Stroustrup is also using that notion (in section 24.3.1) and I'm not sure what the difference is with the concrete types.  Two guesses:

the concrete type is more a notion of intend of usage than strict properties while the concept of Regular is intended to describe properties that a type has to have to be usable in generic contexts.

the notion of regular type is a refinement of the one concrete type and he didn't saw when he introduced it that they should perhaps be unified (the description of concrete types is already present in the second description but seem to have been rewritten).

Title: Concrete types - as described by Stroustrup - C++ Programming Language 4th ed

Body:
I'm having a hard time with this concept.  What is Stroustrup getting at here?  What is special about a class whose "representation is part of its definition"? What does a "concrete type" contrast with? (I assume it contrasts with "abstract type", but since, AFAIK, you can't even bring an instance of an abstract type into existence, it seems obvious you couldn't place that on the stack, initialize it, etc.)

Is there such a thing as a class I could instantiate that would NOT fit this description of a "concrete class"?  Normally I find BS very easy to follow, but I'm missing the point here.

The basic idea of concrete classes is that they behave “just like
built-in types.” For example, a complex number type and an
infinite-precision integer are much like built-in int, except of
course that they have their own semantics and sets of operations.
Similarly, a vector and a string are much like built-in arrays, except
that they are better behaved (§ 4.2, § 4.3.2, § 4.4.1).

The defining
characteristic of a concrete type is that its representation is part
of its definition. In many important cases, such as a vector, that
representation is only one or more pointers to more data stored
elsewhere, but it is present in each object of a concrete class.... In
particular, it allows us to

• place objects of concrete types on the
stack, in statically allocated memory, and in other objects (§ 6.4.2);

• refer to objects directly (and not just through pointers or
references);

• initialize objects immediately and completely (e.g.,
using constructors; § 2.3.2); and

• copy objects (§ 3.3).

Stroustrup, Bjarne (2013-07-10). The C++ Programming Language (4th
Edition) (Section 16.3 Concrete Classes; Kindle Locations 2373-2386). Pearson Education. Kindle
Edition.


答:
If you look at the examples in the article you cited, most of the time using Maybe doesn't shorten the code.  It doesn't obviate the need to check for Nothing.  The only difference is it reminds you to do so via the type system.

Note, I say "remind," not force.  Programmers are lazy.  If a programmer is convinced a value can't possibly be Nothing, they're going to dereference the Maybe without checking it, just like they dereference a null pointer now.  The end result is you convert a null pointer exception into an "dereferenced empty maybe" exception.

The same principle of human nature applies in other areas where programming languages try to force programmers to do something.  For example, the Java designers tried to force people to handle most exceptions, which resulted in a lot of boilerplate that either silently ignores or blindly propagates exceptions.

What makes Maybe is nice is when a lot of decisions are made via pattern matching and polymorphism instead of explicit checks.  For example, you could create separate functions processData(Some<T>) and processData(Nothing<T>), which you can't do with null.  You automatically move your error handling to a separate function, which is very desirable in functional programming where functions are passed around and evaluated lazily rather than always being called in a top-down manner.  In OOP, the preferred way to decouple your error handling code is with exceptions.


答:
From the perspective of a young(ish) compiler guy, one thing not discussed here is the question of where people get their introduction to compiler technology.

If you're lucky, they have a project or a class which discusses compilers. Maybe a course on computer architecture or internals which introduces them to varying layers of abstraction and optimization.

If you're unlucky, then they hear from their friends that compilers are: A solved problem, boring, without impact, too low-level, too small an employment market etc.

My university has a professor who still works in compilers and he's the reason that there are still people coming out of that university with experience and interest in the area. Even better, he has many industrial connections, and uses them to help students get work experience in the area.

So that could be one important route: Start making friends in the faculty at universities you're interested in: Start trying to get interns and research students associated. You'll start building a talent pool.