问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答:
The short version is NO, you can't assume all users have internet access.  As others have mentioned there are a large number of people with limited or no internet access at home.

Your licensing scheme should be able to handle the case that the computer the software will run on will never have access to the internet.  It is not all that unusual for corporations to have networks that are isolated from the internet (especially when dealing with security concerns).  This is especially true if you will ever want to be able to sell you software to a government agency.  The other side is how will you handle updates?  If you will want to sell to corporations/government you will have to support Enterprise rollout of the updates.


问:
Finding a Pre-Written Software License
I've been researching licenses for a few days for a software project I've been working on that I'd like to add a license to.

I'm looking for a fairly restrictive software license that allows access to the source code, although you could only read it, really. Something like the Creative Commons BY-NC-ND v4.0 license would be perfect, but CC is not for software.

Here's what I'm looking for in a pre-written license:

End user is free to share and redistribute the source code (and/or binaries)

Under the following conditions:

End user must provide appropriate attribution, and a link to the license (in any reasonable manner, so long as it does not suggest I endorse their use).

End user must not use the software for commercial purposes.

End user must not share or redistribute the software (source or binary) if they modify the source.

Please post a comment if you need any more info.

答:
It's going to be awfully hard to enforce :)

However, what you have written would seem to me to be a perfectly good thing to put into a license conditions file and/or something prominent where your s/w can be downloaded.

In the end what it comes down to is:

Do you want to be simple and clear (which you have done) and POSSIBLY have something slip through the net?

Or do you want to come over all lawyer-ish, and spend ages trying to find something and/or polish what you have with lots of legalese and additional clauses which probably adds little value (esp. seeing as you have little chance of enforcement).

Re enforcement: The most you would ever realistically be able to do would be a name-and-shame, and even that's unlikely to be very effective.

ContentLicense: CC BY-SA 3.0

Title: Finding a Pre-Written Software License


问:
YAGNI principle put to practice
I recently came across to this principle and so far it is clear the fact that doing things that you don't need at the moment is not feasible as they might not be used or might be changed.

That being said, consider the following scenario: You're working on an application that needs to display text in labels, in several places/parts. The targeted language is English, and there is no requirement to implement multi-language. At this point, if you needed multi-language feature, you'd define every string in a resource file (let's say it's an XML file) and create/use a class to read them and assign them to the corresponding labels (according to the language). Thing is, since multi-language is not a requirement, YAGNI.

So, do you still define strings into a resource file and implement the reader, or you hard-code them and reafactor when you actually need it?

答:
Making applications multi-language does take some additional development effort. You can either invest that effort right from the start, every day a bit. Or you can invest that effort afterwards, when you have written >100K lines-of-code. Fact is, the sum of the needed efforts in both cases is not so very different as you might think.

The first approach actually disguises the needed effort which make some people believe the second approach is more costly, but IMHO that's a misconception. The second approach actually shows you the real costs and makes them much more transparent.  And that is what the YAGNI principle is about: saving that hidden costs at the time you are not ready to invest it.

That said, providing applications for multi-language support right from the start might be the right strategic decision for lot of software products, especially when there is a good chance to sell those applications to a wider audience. But one should not believe that such a decision comes totally for free.

Title: YAGNI principle put to practice


问:
What is a better design a light weight user or a heavy weight heavy user model?
This is a design question and I am confused about how to design my user  object. As in most systems, user is the central part of my application  and a lot of information scattered around my database points back to the user for example a user can have multiple orders, mulitple Addresses, and he may have won multiple prizes. If we want to talk about ONLY user and his basic information we can be done with ID, firstnmae, lastname etc. So I have two clear choices

Create a light weight  user object which looks like following:

```<code> public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
}
</code>```

and get all the infromation at the other information at the run time like orders and Prizes on need basis.

OR

Design a more contained object which carries all the required information with it but is little heavy:

```<code>public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
  public Address HomeAddress {get;set;}
  public List<Prizes> Prizes {get;set;}

}
</code>```

Which Does any design model align to a good design philosophy? Are there any best practices in the kind of situation that can help me make a decision?

答:
To answer this question you should distinguish between information analysis phase, and design phase; even though modern software engineering methods often combine them, the model (doesn't have to be a 1073 page document, it can be in your mind or in the code as well) and level of detail differs:

In the analysis phase, your model will closely match reality, meaning the is a single concept user and some ideas about what data about a user is required.

In the design phase, it depends on what information about the user your application needs in various situations and how easy it is to retrieve the information.

For example, from looking at the user side of Stack Exchange we can deduct that:

Often <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count> suffices (e.g. to display the author of a post or comment).

To display comments, only the user name is sufficient.

When someone views a user profile, much more information is required: <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count, all questions, all answers, all comments, all badges, reputation changes>.

When a user logs in, authentication information and browser session are required; but these should definitely not be shown in post author information.

So here we, conceptually, have four different User classes.  We might opt to use the <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count>-structure for the comment author as well, since its available anyway.

You could use inheritance to combine the different kinds of UserInfo, i.e.:

```<code>class BasicUserInfo
{
    public string Name { get; }
    public Image Avatar { get; }
    public int Reputation { get; }
    public int GoldBadgeCount { get; }
    public int SilverBadgeCount { get; }
    public int BronzeBadgeCount { get; }
}

class UserProfileInfo: BasicUserInfo
{
    public List<Post> Questions { get; }
    public List<Post> Answers { get; }
    public List<Comment> Comments { get; }
    public List<Badge> Badges { get; }
    public List<ReputationChange> Reputation { get; }
}

class UserAuthentication: BasicUserInfo
{
    public string PlainTextPassword { get; } // Not really, I hope everyone knows why and
                                             // how to do this correctly
}

class UserSession: BasicUserInfo
{
    public List<Cookey> Cookey { get; set; }
    public UserAuthentication Authentication { get; }
}
</code>```

And then use some kind of repository to find UserInfo objects, e.g.:

```<code>class UserRepository {
    public UserProfileInfo FindUserProfile(BasicUserInfo user)
    {
        // …
    }

    public UserSession FindLoggedInUsers(BasicUserInfo user)
    {
        // …
    }
}
</code>```

The repository deliberately uses the common base class, BasicUserInfo, to find the extended UserInfo objects, since:

it allows using any kind of UserInfo-object (i.e BasicUserInfo and all extended UserInfo variants) to lookup an extended UserInfo-object;

I'm wary of using a string or int as user id, since forgetting the type info
means we can confuse a string or int that contains something completely different with one containing a user id (e.g. if (UserRepository r, BasicUserInfo u) => r.FindUserProfile(u.BronzeBadgeCount) where supported, would give surprising results.)

TL; DR

Depending on what your application requires use lightweight class User, heavyweight class User, or use several kinds of UserInfo.  If using several kinds of UserInfo you can use a repository and the lightweight common base BasicUserInfo class to find the extended UserInfo.

Body:
To answer this question you should distinguish between information analysis phase, and design phase; even though modern software engineering methods often combine them, the model (doesn't have to be a 1073 page document, it can be in your mind or in the code as well) and level of detail differs:

In the analysis phase, your model will closely match reality, meaning the is a single concept user and some ideas about what data about a user is required.

In the design phase, it depends on what information about the user your application needs in various situations and how easy it is to retrieve the information.

For example, from looking at the user side of Stack Exchange we can deduct that:

Often <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count> suffices (e.g. to display the author of a post or comment).

To display comments, only the user name is sufficient.

When someone views a user profile, much more information is required: <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count, all questions, all answers, all comments, all badges, reputation changes>.

When a user logs in, authentication information and browser session are required; but these should definitely not be shown in post author information.

So here we, conceptually, have four different User classes.  We might opt to use the <user name, avatar, reputation, gold medal count, silver medal count, bronze medal count>-structure for the comment author as well, since its available anyway.

You could use inheritance to combine the different kinds of UserInfo, i.e.:

class BasicUserInfo
{
    public string Name { get; }
    public Image Avatar { get; }
    public int Reputation { get; }
    public int GoldBadgeCount { get; }
    public int SilverBadgeCount { get; }
    public int BronzeBadgeCount { get; }
}

class UserProfileInfo: BasicUserInfo
{
    public List<Post> Questions { get; }
    public List<Post> Answers { get; }
    public List<Comment> Comments { get; }
    public List<Badge> Badges { get; }
    public List<ReputationChange> Reputation { get; }
}

class UserAuthentication: BasicUserInfo
{
    public string PlainTextPassword { get; } // Not really, I hope everyone knows why and
                                             // how to do this correctly
}

class UserSession: BasicUserInfo
{
    public List<Cookey> Cookey { get; set; }
    public UserAuthentication Authentication { get; }
}

And then use some kind of repository to find UserInfo objects, e.g.:

class UserRepository {
    public UserProfileInfo FindUserProfile(BasicUserInfo user)
    {
        // …
    }

    public UserSession FindLoggedInUsers(BasicUserInfo user)
    {
        // …
    }
}

The repository deliberately uses the common base class, BasicUserInfo, to find the extended UserInfo objects, since:

it allows using any kind of UserInfo-object (i.e BasicUserInfo and all extended UserInfo variants) to lookup an extended UserInfo-object;

I'm wary of using a string or int as user id, since forgetting the type info
means we can confuse a string or int that contains something completely different with one containing a user id (e.g. if (UserRepository r, BasicUserInfo u) => r.FindUserProfile(u.BronzeBadgeCount) where supported, would give surprising results.)

TL; DR

Depending on what your application requires use lightweight class User, heavyweight class User, or use several kinds of UserInfo.  If using several kinds of UserInfo you can use a repository and the lightweight common base BasicUserInfo class to find the extended UserInfo.


答:
There is no such open source license. In fact, there cannot possibly be such an open source license, since your terms violate several of the fundamental principles of open source, and thus any license which includes your terms is by definition not an open source license.

In particular, your proposed terms violate clauses 3 and 6 of the Open Source Definition:

3. Derived Works

The license must allow modifications and derived works, and must allow them to be distributed under the same terms as the license of the original software.

Rationale: The mere ability to read source isn't enough to support independent peer review and rapid evolutionary selection. For rapid evolution to happen, people need to be able to experiment with and redistribute modifications.

6. No Discrimination Against Fields of Endeavor

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research.

Rationale: The major intention of this clause is to prohibit license traps that prevent open source from being used commercially. We want commercial users to join our community, not feel excluded from it.

It also violates freedoms 0 and 3 of the Free Software Definition:

The freedom to run the program as you wish, for any purpose (freedom 0).

The freedom to distribute copies of your modified versions to others (freedom 3). By doing this you can give the whole community a chance to benefit from your changes. Access to the source code is a precondition for this.

In short: what you are asking for is impossible. You can't find such an open source license, nor can you write one yourself, since your terms are fundamentally incompatible with the very foundations of open source.

Title: Finding a Pre-Written Software License

Body:
I've been researching licenses for a few days for a software project I've been working on that I'd like to add a license to.

I'm looking for a fairly restrictive software license that allows access to the source code, although you could only read it, really. Something like the Creative Commons BY-NC-ND v4.0 license would be perfect, but CC is not for software.

Here's what I'm looking for in a pre-written license:

End user is free to share and redistribute the source code (and/or binaries)

Under the following conditions:

End user must provide appropriate attribution, and a link to the license (in any reasonable manner, so long as it does not suggest I endorse their use).

End user must not use the software for commercial purposes.

End user must not share or redistribute the software (source or binary) if they modify the source.

Please post a comment if you need any more info.


问:
How to organize remote Git branches when team does single change releases?
I am a member of a project team with somewhat unusual (or at least from my perspective) release methodology and team dynamic.  The way we have been doing releases is rolling out a single functional bundle at a time, all of which, as a rule of thumb, was done by a single developer.  Developers do work on their virtually independent functional areas, that are all nonetheless part of the same deployment bundle (WAR file and its corresponding Git repo), concurrently but it is not certain or clear whose change will go in in what order.  It often depends on whoever finishes and gets their stuff tested first.  So Dev1 may be working on Change1 within TeamProject and Dev2 will be working on Change2 in the same application, and sometimes their changes may be interdependent (such as changing a shared API) but it is not clear when each will be rolled out to PROD.

The way we currently do Git branch management is that each change gets its own remote branch, which defacto means there is one remote branch per developer.  The biggest problem I see with that is that, in order to be refreshed of your teammate's changes, you have to manually sync your branch to their branch, which is a manual and often a PIA process, excuse the term.  It may be okay for the developer whose release is the very next one in line, for his branch is what the next version of the release will look like once it is rolled out (in the existing single change release setup).  But it surely does not work for the developer whose release comes right after as (s)he has to build their changes on top of the first developer's changes.  However, they don't want the second developer to push into the first developer's branch as to keep the change pristine and exclude everything else from that specific release.  So the 2nd developer has to do the merging of the 1st developer's branch into his branch and then push his stuff into that branch on top of the 1st dev's changes.  That would not be half as bad if it were clear who the 1st and who the 2nd developer is, IOW, whose changes will first be rolled out but that is a contingency, as explained above.

Now, by the nature of this post thus far, it is clear that I am not the father of this process and that I am aware of many of its inherent flaws.  One notable flaw happened recently when we were promoting our changes to the TEST environment.  I had been working in my dedicated branch but the version that was deployed to TEST was built out of my peer's branch (it had his changes only).  I was about to push my stuff but didn't want to lose his, as I value our QAs time and wanted his and my tester to be able to work concurrently.  So I synced my branch to his (cherry picked his changes into mine, after the common ancestor) so that both his and my changes were in.  It worked fine.  However, he wanted to push a bug fix a day later and did it out of his own branch without syncing with mine.  Guess what happened:  my changes were gone from the build and only his were present.  Needless to say, these multiple remote branches make continuous integration (which I would like to start doing and is not presently done), difficult or virtually impossible.

Frustrated with all this, I have been working on a proposal to my team how to change this configuration.  My idea is to have an INTEGRATION SHARED REMOTE BRANCH that everyone pushes their stuff into and that is something like a work-in-progress branch that anything can go in as long as it compiles and passes tests (basically passes the build).  CI daily builds could be done out of this branch. Then there is a release branch to which stuff is not pushed in directly but is cherry-picked out of the WIP branch to correspond to what we want in the release.  So if we think that Dev1's changes will go in the immediate next release, we cherry pick his changes in it.  But the important thing is there is one UNIFIED branch for all the developers on the team that work on the same project as opposed to them working in each one's isolated silo.  This way, we could actually rebase our local branches with the shared remote continuously and get our peer's changes timely as opposed to when they become part of the master (or production) when the volume of changes to be synced can make the merging process a living hell.

I would like to inquire about the pros and cons of my proposed methodology vs what the team is doing presently and is explained above.  And generally, with the idea of the current release culture in mind, which perhaps is not within my powers of changing as it is affected by many members of the organization above me, what would be the most efficient and painless teamwork setup.

答:
I'd keep those feature branches (very much like what you describe now), but make sure they are feature branches, not individual developer branches... Developers work on these feature branches, develop and test their feature.

Then on top of that, like you say, have an integration branch where all changes get merged, compiled and perhaps get some day-to-day testing. Merges don't happen until the feature's developers are confident and have tested that what they developed doesn't break stuff. Beware, this doesn't mean their feature is completely done, rather that what they 'publish' is good, sound and no longer in code-flux.

Benefits:

merge conflicts get found and fixed early on

everyone can see where the code is going by looking at the integration branch
Whatever is in there is considered to-be-released and not subject to large changes, exceptions notwithstanding.

this branch can be tested for merge-damage (i.e. 2 features don't work well together).
You no longer need to wait for the feature to be merged into the release branch (on top of previous features) to find and fix these issues

In time, you might find that testers spend more time testing the integration branch and less time testing the release branch because more issues have been found during integration.

But, opposed to cherry-picking individual changes into a release branch, I'd opt for merging in each feature branch into the release branch and stabilizing that until actual release. Merging gives you the extra benefit of being able to do "git log integration..release" or "git log release..feature" and get overviews of pending changes.
If you cherry-pick, git has no knowledge of what did or did not make it into the release.

Connaisseurs will find that this resembles Linux kernel development flow a bit, where linux-next serves as integration repository(/branch) where all features must have lived a while before being merged into mainline and developers work on their own local repositories (/branches).


问:
What does stubbing mean in programming?
I often hear the term "stub", "stub something out", "stubs", and so forth.

What does stubbing mean in programming, and where does the word come from? In what contexts can it be used?

答:
A stub method is a method that just returns a simple but valid (though not necessarily correct) result.

They are typically made when building the infrastructure and you don't want to spend time on every method needed right now. Instead you create stubs so everything compiles and your IDE's auto-complete knows about the methods you are planning to use.

Another place where stubs are used is in mocking when testing, You supply stub methods instead of the normal dependency through dependency injection which return fixed results and then ensure that the code does the right thing with them. This isolates testing to the code you are trying to test and means you don't need to spin up a database just to run those tests.

ContentLicense: CC BY-SA 4.0

Title: What does stubbing mean in programming?


问:
Transpose a matrix without a buffering one
How is it possible to transpose a MxN matrix without using a "buffering" matrix?
In the latter case it's easy and quite the "classic" approach...

Given a matrix[M][N], I would like to put it into a void transpose_matrix(int matrix[][]) function which operates directly on the matrix passed as reference which, as previosly said, would edit the matrix memory space to transpose its elements.

e.g:

A =

```<code>1 2 3 4
5 6 7 8
9 1 2 3
</code>```

A after transposing itself (without pretty printing)[1]:

```<code>1 5 9 2
6 1 3 7
2 4 8 3
</code>```

How would A looked like in a NxM matrix:

```<code>1 5 9
2 6 1
3 7 2
4 8 3
</code>```

Thanks!

[1]: Printing the matrix as if it was actually a "new" NxM matrix.

答:
Doing that efficiently is complex.

Wikipedia has a nice article on the subject: In-place matrix transposition with many interesting references.

A simple "follow-the-cycles" C implementation with O(1) auxiliary storage requirement (and heavily non-consecutive memory accesses) is:

```<code>/// \param[in] m input matrix
/// \param[in] h number of rows of \a m
/// \param[in] w number of columns of \a m
///
/// Performs in-place transposition of matrix \a m.
void transpose(double m[], const unsigned h, const unsigned w)
{
  for (unsigned start = 0; start <= w * h - 1; ++start)
  {
    unsigned next = start;
    unsigned i = 0;
    do
    {
      ++i;
      next = (next % h) * w + next / h;
    } while (next > start);

    if (next >= start && i != 1)
    {
      const double tmp = m[start];
      next = start;
      do
      {
        i = (next % h) * w + next / h;
        m[next] = (i == start) ? tmp : m[i];
        next = i;
      } while (next > start);
    }
  }
}
</code>```

You can find a faster (C++) implementation requiring O(MN) auxiliary storage, one bit per element, here (the In-place transposition of a matrix question on Stackoverflow). Also take a look at Transpose a 1 dimensional array, that does not represent a square, in place.

PS in a number of circumstances it isn't necessary or desirable to physically reorder a matrix to its transposed ordering: it could be enough to provide options to specify that certain matrices are to be interpreted in transposed order.

Some details about the above algorithm (assuming the input matrix A(3;4) of your question):

The first chunk: (do … while) is a sort of sequence generator:

```<code>next-sequence  start     next    i
-----------------------------------
[0]                0        0    1
[1,4,5,9,3]        1        1    5       <-
[2,8,10,7,6]       2        2    5       <-
[3,1]              3        1    1
[4,5,9,3]          4        3    3
[5,9,3]            5        3    2
[6,2]              6        2    1
[7,6]              7        6    1
[8,10,7]           8        7    2
[9,3]              9        3    1
[10,7]            10        7    1
[11]              11       11    1
</code>```

Not every sequence is useful:

sequences of length 1 (i == 1 e.g. [0] and [11]) mean no data motion and can be skipped;

sequences where the final value of next is smaller than start can be skipped since they are sub-sequences of an already seen sequence.

Second chunk (if) will perform the data motion described by a sequence.

E.g. [1,4,5,9,3] means the value in position 4 goes to position 1, value in position 5 goes to position 4 … while position 1 goes to position 3 (written using the standard notation for cycles/permutations it's (1 3 9 5 4)).

About the expression:

```<code>(position % h) * w + position / h;
</code>```

this is a way to convert the position between the original and the transposed matrix.

Body:
Doing that efficiently is complex.

Wikipedia has a nice article on the subject: In-place matrix transposition with many interesting references.

A simple "follow-the-cycles" C implementation with O(1) auxiliary storage requirement (and heavily non-consecutive memory accesses) is:

/// \param[in] m input matrix
/// \param[in] h number of rows of \a m
/// \param[in] w number of columns of \a m
///
/// Performs in-place transposition of matrix \a m.
void transpose(double m[], const unsigned h, const unsigned w)
{
  for (unsigned start = 0; start <= w * h - 1; ++start)
  {
    unsigned next = start;
    unsigned i = 0;
    do
    {
      ++i;
      next = (next % h) * w + next / h;
    } while (next > start);

    if (next >= start && i != 1)
    {
      const double tmp = m[start];
      next = start;
      do
      {
        i = (next % h) * w + next / h;
        m[next] = (i == start) ? tmp : m[i];
        next = i;
      } while (next > start);
    }
  }
}

You can find a faster (C++) implementation requiring O(MN) auxiliary storage, one bit per element, here (the In-place transposition of a matrix question on Stackoverflow). Also take a look at Transpose a 1 dimensional array, that does not represent a square, in place.

PS in a number of circumstances it isn't necessary or desirable to physically reorder a matrix to its transposed ordering: it could be enough to provide options to specify that certain matrices are to be interpreted in transposed order.

Some details about the above algorithm (assuming the input matrix A(3;4) of your question):

The first chunk: (do … while) is a sort of sequence generator:

next-sequence  start     next    i
-----------------------------------
[0]                0        0    1
[1,4,5,9,3]        1        1    5       <-
[2,8,10,7,6]       2        2    5       <-
[3,1]              3        1    1
[4,5,9,3]          4        3    3
[5,9,3]            5        3    2
[6,2]              6        2    1
[7,6]              7        6    1
[8,10,7]           8        7    2
[9,3]              9        3    1
[10,7]            10        7    1
[11]              11       11    1

Not every sequence is useful:

sequences of length 1 (i == 1 e.g. [0] and [11]) mean no data motion and can be skipped;

sequences where the final value of next is smaller than start can be skipped since they are sub-sequences of an already seen sequence.

Second chunk (if) will perform the data motion described by a sequence.

E.g. [1,4,5,9,3] means the value in position 4 goes to position 1, value in position 5 goes to position 4 … while position 1 goes to position 3 (written using the standard notation for cycles/permutations it's (1 3 9 5 4)).

About the expression:

(position % h) * w + position / h;

this is a way to convert the position between the original and the transposed matrix.


问:
Statistics about the usage of programming paradigms
I hear very often that the object-oriented programming paradigm is the most widespread. But are there any scientific statistics about how often other programming paradigms like procedural programming are used today?

I searched at gartner, but didn't found anything.

答:
I don't think such statistics exists, and if they are, they may not be particularly relevant.

Take C# code base:

C# is an object-oriented language, but it is not unusual to see code bases full of procedural code written by programmers who has no understanding of object-oriented programming (or understand it as "OOP is when you put the code in methods within classes").

How would you measure the proceduraliness of the code base? How can you tell that the code base is 64.2% procedural and 35.8% object-oriented?

Assuming you just want to tell whether the code base is either object-oriented or procedural. Agreed, you will be able to do that for some code bases (the ones which are obviously missing any OOP or the ones which use object-orientation very well), but in many cases, the answer won't be that straightforward.

C# also has many functional paradigms, making it sometimes particularly elegant when working with collections.

This being said, C# is not a functional language, and writing purely functional code for a large application won't be possible, not counting the fact that many functional paradigms don't exist in C#.

This makes it even harder to measure. You can't just say: "This code base is functional." or "This code base is object-oriented." for code bases which use functional paradigms only when working with collections. So we are back to 64.2/35.8% problem described above.

If you're interested in the popularity of paradigms, what you may search instead is the penetration of some paradigms in languages and communities which weren't using them before. For example, ten years ago, C# didn't have any functional paradigms, and programmers who were using exclusively C# were most unaware of what a functional language is. Today, things are radically different.

This is also statistically measurable. You may measure that in 2004, 21.7% of programmers of a given community knew what functional language is, while in 2014, 41.2% know that, or that in 2004, 6% of programming languages had a specific paradigm, while ten years later, 9% had it.


问:
What is really a resource?
I'm starting to study about web api's and REST and I'm having a hard time to understand what is really a resource. Basically the book I'm reading says that a resource is a conceptual mapping to one or more entities. Searching on the internet I found this from a dissertation:

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

Which again says a resource is a conceptual mappings to one or more entities, but that says that any information that can be named can be a resource. The book also stresses that entity in this case doesn't refer to business objects but can be really anything.

Now, this idea of resource seems pretty important, but I can't grasp what really a resource is and why it should be a mapping.

So what is really a resource, why it should be a mapping to one or more entities and what are some examples?

答:
A resource is simply something you can get through an uniform resource identifier (URI), i.e. a piece of information which has an URI associated with it.

Imagine an image funny-cat.jpg on your PC; only you can access it. This is not a resource. If, on the other hand, you install an HTTP server which points to the directory containing the image, you can now access the image through an URI similar to http://example.com/funny-cat.jpg; it's now a resource.

Note that a resource may be static (an image in the previous example) or dynamic (http://example.com/latest-news). This means that a resource isn't necessarily something which exists permanently on a server.

Also note that a resource has an URI, but doesn't necessarily have only one URI. For instance, http://example.com/product/912/dell-poweredge-r420 and http://example.com/publicstore/dc2/product.aspx?id=912 may point to the same resource (here using URL rewriting technique).

In the quote in your answer, the key sentence is:

Any information that can be named can be a resource.

An image can be named (http://example.com/funny-cat.jpg). The list of latest news can be named (http://example.com/latest-news). The image stored on your PC with no HTTP server on it cannot be named (there is no URI you can give to CURL to get this image), therefore it is not a resource.

Title: What is really a resource?


答:
YAGNI is often in opposition to other established principles and/or best practices. Other examples include several of the SOLID principles, which are largely about structuring your code to make certain kinds of change easier in future. But what if you don't ever need to make those changes? Then the extra work involved in, say inverting the dependencies between two different parts of your application, and the extra complexity introduced by the unnecessary abstractions that such an inversion requires, is wasted.

YAGNI doesn't mean we should never do such things. It does mean we should stop to think before doing it and make a serious assessment of how much effort we're about to put in, how likely it is to pay off, and how much easier it is now than later.

In your example of externalizing strings, the amount of effort is small, but it is also not much harder to do it later, as Doc Brown has suggested. And you're the only one who knows how likely it is that you will need i18n support in the future.

Personally, I'm inclined to leave this particular task until it is necessary, but my experience is largely in building internal apps for SMEs that rarely need the facility, and I work with tools that have support for automatically refactoring to an external string resource. Your market and tools may be different, which might result in a different decision.

Title: YAGNI principle put to practice

Body:
I recently came across to this principle and so far it is clear the fact that doing things that you don't need at the moment is not feasible as they might not be used or might be changed.

That being said, consider the following scenario: You're working on an application that needs to display text in labels, in several places/parts. The targeted language is English, and there is no requirement to implement multi-language. At this point, if you needed multi-language feature, you'd define every string in a resource file (let's say it's an XML file) and create/use a class to read them and assign them to the corresponding labels (according to the language). Thing is, since multi-language is not a requirement, YAGNI.

So, do you still define strings into a resource file and implement the reader, or you hard-code them and reafactor when you actually need it?


问:
Is there some structured format for drawing source control branching diagrams?
Everyone on my team draws branch diagrams differently, including how branches exit or reintegrate to the parent, how cherry-pick merges are shown, and a host of other aesthetic choices.

Is there some structured format for drawing source control branches (like UML but for source control)?

答: If you want standardization I sugest a graphviz with .dot format. It's well known lib for drawing networks and flowcharts. Hope it helps. :)</p>


问:
Small code, big test
I have this code in a controller of an MVC implementation:

```<code>public void execute() {
        try {
            String path = userSelectsFile();
            if ( path == null ) return; //Just returns if the user press "Cancel"

            //Load the data
            Collection<Info> infos = Infos.fromJSON(getInputReader(path));
            //Show the data in the interface
            new ShowTransformationsInTree(win(), infos, win().getTree()).execute();
        } catch (Exception e) {
            new ComplainAction(win(), "Unable to...blah, blah", e).execute();
        }
    }
</code>```

To test this, I have to mock the user interface to show file dialog and make getInputReader method an abstract factory method.

Test code:

```<code>    /**
     * Mocks the LoadTransformationsAction so the factory method getReader returns a ByteInputStream
     */
    public class MockLoadTransformationsAction extends LoadTransformationsAction {
        //CONSTRUCTOR REMOVED FOR CLARITY.....

        @Override
        protected InputStreamReader getInputReader(String path) {
            assertEquals(FAKE_ABSOLUTE_PATH, path);
            return new InputStreamReader(
                    new ByteArrayInputStream(TestHelpers.createDataBytes());
        }
    }

    /**
     * Test the proper loading of the data.
     */
    @Test
    public void testLoadData(@Mocked final FileChooser anyChooser) {
        new Expectations() {{
            //Mocks the IntelliJ idea API
            FileChooser.chooseFile(null, null, null); result = new MyFakeVirtualFile(); //Returns a fixed path
        }};

        //Loads the data from the JSON file
        MainToolWin m = new FakeMainToolWin();
        LoadTransformationsAction action = new MockLoadTransformationsAction(
                m, new FakeProject(), new MockInputProgram());
        action.execute();

        //Test that the transformations are in the UI Tree
        DefaultTreeModel model = (DefaultTreeModel)m.getTree().getModel();
        assertEquals(2, model.getChildCount(model.getRoot()));
        assertEquals(3, model.getChildCount(model.getChild(model.getRoot(), 0)));
    }
</code>```

Questions:

Am I doing too much to test too little?

As you can see there are mock and fake objects all the way. Can so much mocking can make my test unreliable?

Is there a better design?

答:
Try writing tests first and then write implementation. By doing this way you'll see that your tests will be short and simple and the implementation as well.

Use as many simple interfaces as you can.

In your method 'execute' I don't see any story. If I would do such kind of thing I would have such implementations:

An object that returns selected path

An object that validates path

An object that parses file specified in the path

String path = pathProvider.provideSelectedPath()
pathValidator.validate(path)
UseData data = infoReader.readFromPath(path)
return data

If user pressed cancel -- it's GUI logic
Show user data -- it's GUI logic

Title: Small code, big test


问:
How to identify http requests made from a closed-source java app?
I am an avid Go player and play on the Kiseido Go Server.

I would like to write an open source client for this, but the KGS protocol is a well-kept secret.  Is there any way to catch the http requests made by the *.jar file to the Go server?

I know this is possible because at least one other client app (CGoban) exists.

答:
You've got two basic approaches, one is to watch the network traffic, the other is to look at the source.

For looking at the source, you would do something like use a java decompiler and see what it gives you.  Note, however that this means you are looking at the source (or something close to it) and any works based on it may be considered a derived work (in which case you may not be allowed to release it with your desired license - or at all).

The other option would be to sniff the traffic somehow.  Depending on one's familiarity with network administration, there is the option of setting up a transparent web caching proxy that would allow you to watch what goes through it. Or a specific application like fiddler to sniff the traffic.

There is nothing saying that this is running over port 80.  It could be running on port 1502 with something other than http. For that you would need to look at sniffing all the packets to get a better idea of what is going on.  For that you start looking at tools such as wireshark or tcpdump.  Then you look at all the packets and figure out what it is doing.

Reverse engineering a protocol that may be obscufated is not necessarily trivial. Especially if you don't have a server of your own that you can test against (you will be testing to see if it does the right thing on the other end). A tweak to the protocol (I note that they use java webstart - it would be very easy) and all your work has to start over again.  If you don't "behave" it could be fairly trivial to start blocking the IP of misbehaving clients.

This leads us to another option which the site provides.  There is a GTP client also listed on the client page.  This is a translation layer between the Go Text Protocal and KGS.  You could write a program that writes GTP through standard in and out and is piped through the client.

This way you are using their library at arms length (you could switch it to another server that provides their own GTP client trivially) and create your own open source application that serves an even wider community.  This is exactly what GNU Go does:

Although ASCII-based, GNU Go supports two protocols — the Go Modem Protocol and the Go Text Protocol — by which GUIs can interface with it to give a graphical display. Several such GUIs exist. GTP also allows it to play online on Go servers (through the use of bridge programs), and copies can be found running on NNGS, KGS, and probably others.


问:
How to prevent others from using non-thread safe variables in a multithreading environment?
I have an application written in C++ that was originally single threaded, but, due to the increasing complexity of this project, I'll need to expand it to at least two or three threads.

There are only a total of four variables that will be used between more than one thread threads, making it useless to make everything thread-safe. The obvious solution is to just create a mutex for each variable and move on with my life.

However, looking back, this seems like a horrible idea! I'm afraid that another programmer may forget that the majority of the methods and variables are not thread-safe and use a variable in another thread.

Since I'm the main programmer for this project, it doesn't seem like this would be an issue, but I honestly feel like this is bad programming and it feels really messy.

What are some ways to keep the variables separate to make it easier to tell which variable is for which thread? I've been thinking about isolating the code for the thread so it cannot access the other global variables (giving a compile error instead of silently creating a bug). I could also create a namespace or class for each thread. Is there a best practice for this?

答:
After some work, I actually figured out a simple solution for this issue (as simple as they get)... namespaces.

I have each logical thread organized into a specific namespace. For example, this is what my namespace organization looks like (split into different files, obviously). If I had a ton more stuff shared, I would've done a class approach like SumGuy's answer for shared variables, but it'd be overkill to do this for all of the code since, besides the four variables, the threads are independent.

```<code>namespace MainThread {

}

namespace ThreadOne {

}
</code>```

It isn't a pretty solution, but at least another person will have to explicitly type the word "thread" to use a variable/function in another thread, so it's their fault if they ignore such an obvious thing.

Also, if editing code in one namespace, it takes no extra effort to type the name of the current thread since that's automatically assumed!

Body:
After some work, I actually figured out a simple solution for this issue (as simple as they get)... namespaces.

I have each logical thread organized into a specific namespace. For example, this is what my namespace organization looks like (split into different files, obviously). If I had a ton more stuff shared, I would've done a class approach like SumGuy's answer for shared variables, but it'd be overkill to do this for all of the code since, besides the four variables, the threads are independent.

namespace MainThread {

}

namespace ThreadOne {

}

It isn't a pretty solution, but at least another person will have to explicitly type the word "thread" to use a variable/function in another thread, so it's their fault if they ignore such an obvious thing.

Also, if editing code in one namespace, it takes no extra effort to type the name of the current thread since that's automatically assumed!


问:
Program Architecture: How to manage objects that are interdependent
Consider the following case, image I making a simple chat program; I want it to be extensible such that it would be fair easy to add add different scripting and user interfaces.

I want the core controller and model to be separate from the interface so I could something like the following, I am using python syntax for simplicities sake.

```<code> class chat_controller:
     def send_message():
     def add_new_interface(iface)

class console_ui:
    def __init__(chat_interface): #new need access to the chat ctrl
    def receive_new_message(msg):

class python_scripting:
    def __init__(chat_interface): #new need access to the chat ctrl
    def receive_new_message(msg):

c=chat_controller(...)
c.add_new_interface(console_ui)
c.add_new_interface(python_scripting)
</code>```

This works, UNTIL I also want to the python interface to be able to interact with the UI (say alter colours, whatever) or until I want to be able to execute script macros from the UI.

On idea I had would be to have something like this:

```<code> class chat_controller:
     def send_message():
     #register new interface with name
     def add_new_interface(name, iface)
     def try_get_interface(name) #none or iface
</code>```

but then I'll have to do some cast relying on the string value to be correct, which is kind of gross.

Another way, would be to make each of the sharing objects to have an 'add_new_inteface' functions, but now it just seems cumbersome.

Bare in mind, it maybe the case that the chat program could be run with out python scripting, or with a different script engine, or say a web or GUI rather than console, it's supposed to be generic.

Any input is greatly welcome.

答:
I believe you should have as few interdependent objects as possible. In your case, as I understand, chat_controller is not actually an initiator of events. It is more like a central manager of the system.

I guess what you need to do is to declare CharController as a class, that have methods, registering (pushing) various events, happening in the system to it, and then use Observer pattern to let various classes to subscribe to it's events.

But I am sure you will eventually find out, that there are many event types and ChatController will be split into several class, each responsible for a particular system function to avoid complexity.

But it's difficult to give some good advice until we know more of the nature of the system. What is it like? What does it do?


问:
Service layer - fat service classes?
Let's say that I have a service for Job Offer entity in CRM app. Job offer is related to many many things, so there will be lot of methods on service layer to interact with above.

What should be considered better approach - one big, fat service class for whole Job Offer family (like, 50 methods in service), or breaking it into few smaller services targeted for specific parts of interactions (one for saving/updating basic data, one for handling job offer details, one for job applications etc).

Pros of one fat class that I see is that it could be more DRY than multiple smaller services. Of course one can always can call another service from other service, but this will cause less modularity. Cons - I'm afraid that large service class will be harder to maintain and to test.

答:
Well, I'm typically against anything fat in the application unless there is no way to avoid it. So, I say: break it apart.

Reading through your comment I can suggest some ideas:

I'm talking about methods like

"saveOffer", "deleteOffer", "activateOffer" - OfferService definitely.

"markAllApplicationsAs" - not so sure about this one. Probably just belongs to OfferApplicationService with just offerId passed as a filter

"getOfferApplications" - OfferApplicationService with offerId passed as a filter I say.

and so on. I thought that those methods should belong to service
  layer.

Sure, they should.

Title: Service layer - fat service classes?


问:
Best approach for managing users that are defined inside the active directory, inside my custom application
I want to start a new asp.net mvc5 Personal Appraisals web project. Now I will have a module inside the system for managing users, and adding info such as primary role, secondary role, main skills, rating for each skill.

As the users are already inside the active directory so I do not want to store duplicate info such as their first name, last name, email address, I want to retrieve them directly from the AD. So I am thinking of this scenario:

Click on "Add user".

Start typing first name, where the system will auto-complete the related users from AD.

Select specific user. The system will populate its first and last names + email address.

Enter info such as primary role, main skills, etc.

Save

After that I will ONLY save the GUID for the user or any id that uniquely identify the user inside the AD.

Later on when I want to view the users info, I will dynamically retrieve his first name, last name, and email address from the AD based on the GUID id which i store inside my DB, and display them inside my system + the info which is stored inside my DB (such as primary role, skills, etc).

So can anyone advise on this approach, or is it better to store the users' info inside my system, and define a sync job which will synchronize the users as defined inside the AD?  I'm not sure how I should be handling this scenario.
Thanks.

答: I think you should store all the data you will need to properly draw UI inside your database and synchronize it with AD. Otherwise very soon you will stumble over performance issues. Sync with AD sounds good for me. And as to when to sync, check this Microsoft article. There are techniques for this inside AD.</p>


问:
Data serialization architecture, injection on construction vs. on function call
I am creating a data serialization/deserialization mechanism for essentially a persistent storage object. Due to the variety of systems this mechanism could run on, there needs to be a a variable number of "drivers" that could be used to serialize or deserialize the data.

I am having trouble figuring out the appropriate level of abstraction for this system. Primarily, when I construct a "driver", should it have a reference to the object I am storing, or should that object be passed in to the various write functions?

So, let's say I have an some DataAccessLayer which wraps my DataAccessDriver. My DataAccessLayer necessarily contains a reference to some DataObject which it also wraps, and it uses the DataAccessDriver to actually keep some serialized representation of the DataObject.

The question is, should the DataAccessDriver be constructed with a reference to the DataObject, or should I pass in the DataObject for every function call the DataAccessDriver makes?

答:
o, let's say I have an some DataAccessLayer which wraps my
  DataAccessDriver.

I doubt very much there should be such a strong dependency. I vote for serialization subsystem to be completely independent from other things in your application. Note: I vote for serialization to be independent from persistence layer. Serializing an object is one responsibility, saving it anywhere is another one.

My DataAccessLayer necessarily contains a reference to some DataObject
  which it also wraps, and it uses the DataAccessDriver to actually keep
  some serialized representation of the DataObject.

What do you mean "wraps"? It created some instance of DataObject, I take it. And then uses serialization to serialize it.

The question is, should the DataAccessDriver be constructed with a
  reference to the DataObject, or should I pass in the DataObject for
  every function call the DataAccessDriver makes?

I think this depends on how much configuration serialization needs. If for serialization you need to do some complex setup of the serializer apart from just passing object reference, then it would, probably, be better to pass object to the serializer's constructor, have constructor setup various defaults and then just call serialize(). If serialization logic is as simple as passing an object reference, I vote for one method in the serializer which takes object instance as argument. This case is also slightly better performance-wise because you don't need to create new serializer instance each time you are serializing another object.


问:
Multitier architecture using API
I have been reading a number of posts and I am leaning towards building an SOA.

My main dependencies are:

Need to support multiple clients

Need individual client environments to not effect other client environments

For example, if I want to add a text field to Client A's application, but I don't want Client B to be effected in any way.

The solution I have is to send an API address along with the client auth token.  For example, the client will send something like this:

```<code>api: http://myWebsite/api/clients/ClientA/someServiceCall
</code>```

Similarly, from a token, the (MVC) controller will know which view to render for a given user.

My question is, is this a good solution to my problem?

I understand that I am having to call an HTTP REST service for my data access; but, I feel this solves a lot of problems.  For instance, I could see which services sending 404 errors and fix them (presumably) before they even get reported.

I have read a number of articles that seem to enforce my idea.  Have I misunderstood this concept?  Is there a better architectural approach?

Here's what I've been reading:

Dogfooding: how to build a great API

Should a website use its own public API?

Stevey's Google Platforms Rant

Again, the goal is to keep individual client environments as separate as possible; such that if we push a change to the service layer, there is no downtime and no one gets logged out because of an app pool refresh.

My over all plan is to incorporate these API calls wherever they are needed; i.e. in an MVC controller or a javascript AJAX call.  For example:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        WebClient client = new WebClient();
        string api = /* api from auth token */
        User result = JsonConvert.DeserializeObject<User>(client.DownloadString(api));
        return View(result);
    }
}
</code>```

答:
The solution I have is to send an API address along with the client
  auth token. For example, the client will send something like this:

api: http://myWebsite/api/clients/ClientA/someServiceCall

I don't think it's a good idea. What you are actually trying to do here is to make separate APIs for separate client types. It will quickly become an overcomplicated task. I say: make one good API, offer it to clients as a whole and control what each client can do with it via access tokens and per-token permissions.

Similarly, from a token, the (MVC) controller will know which view to
  render for a given user.

I don't know how you want this to be implemented, but in my opinion web service should operate with data only. It should be separated from GUI by all means.

Again, the goal is to keep individual client environments as separate
  as possible; such that if we push a change to the service layer, there
  is no downtime and no one gets logged out because of an app pool
  refresh.

What is a client environment in your design? Surely not an API?

Again, the goal is to keep individual client environments as separate
  as possible; such that if we push a change to the service layer, there
  is no downtime and no one gets logged out because of an app pool
  refresh.

In REST model clients don't maintain constant connection to the server. So no need to care about service restarts. If you need some data to persist across calls, implement it using some data objects or tokens.

Should a website use its own public API?

I agree with Steve in that question completely. If you don't use your own API it means that API will not be... useful (pardon my word game here). But using API doesn't necessarily mean you have to actually do some HTTP calls to your service API. It means the code, working on your platform should be the same, that is utilized by your REST API. You may expose only part of the functionality via API - that's ok.

Title: Multitier architecture using API


问:
Best approach for a server configuration data collection and reporting solution from a legacy script?
I have a project which involves collecting config data from windows servers in our (very large) server estate. My manager wants me to collect over 150 data items across all configuration areas including network config data, disks, registry values, BIOS version, dll versions, you name it. The server support team currently use a nasty vbScript script which is massive, messy and has been passed around and grown organically over time. The script is currently used to collect the data and produce a very basic flat HTML report with a column for each of the 150+ items it collects data for.  My job is to tranform it into a proper software solution with new bells and whistles, a website, reports etc.

The idea is a sys admin will go to an intranet website, puts the server name in and presses the go button, the solution collects the data and pushes it into the DB for reporting later.

My manager wants the solution to collect the data, some of it referencing known desired values (e.g. RAID card drivers for ABC model servers is at v1.2.5.1) to see if they are correct or up to date, store it in a SQL database, and then use the front end web site for producing reports. In the reports, he wants it to be able to compare two datasets; for example, one for server ABC123 and one for server DEF987 in one report, highlighting any differences between the two.

It gets messy pretty quick as some data will be collected for on some servers but not others (domain controllers wont have data collected about exchange services running status). There are many miscellanous items which don't fit into a data model area and don't really have a home ... it's a mess.

I'm ok with collecting the data (using .Net), but I'm at a loss as to where the best place is to do such things as store and lookup/compare items to good known values (XML, DB?). Should I do it as part of the data collection phase and then push it into the DB. Or should I marry it all up as part of the reporting data?

I'm going with a data warehouse (de-normalised) schema for the DB. There will probably be about 20 tables which the data will need to be pulled from, so I have no real idea what the best way to compare the dataset from one server data collection, with another, with such a massive set of fields to compare.

What do you guys think my best options are for approaching this project and the architecure of the solution?

答:
I'm ok with collecting the data (using .Net), but I'm at a loss as to
  where the best place is to do such things as store and lookup/compare
  items to good known values (XML, DB?). Should I do it as part of the
  data collection phase and then push it into the DB. Or should I marry
  it all up as part of the reporting data?

I would recommend it to do this way.

Make a CollectorService, which will run on client computers and collect data. It should store collected data locally in XML, YAML, JSON or whatever (personally I tend to use JSON these days).

CollectorService will query hardware, software or whatever, store data locally on client machine and then connect to central data directory and send data there. After receipt has been confirmed, local data can be deleted. Data should be transfered in the same format it was collected in (e.g. JSON).

Make ProcessorService, which will receive data from clients and store it in the central database. I would recommend Postgres for storage (more on that in a moment). ProcessorService will split data received from clients into two groups using the following rule: data, that is probably be queried often goes to separate schema/table/column. Data, which is going to be queried rarely, goes into JSONB column fields / subfields.

Now why Postgres. 9.4 version of this wonderful DB server can now handle JSON types in columns and what is more - it can define arbitrary indexes on JSON fields of any depth. So, you doesn't loose much storing data in JSONB column comparing to storing it in a separate one. So now Postgres speaks NoSQL too ;)

Now make AnalysisService. This one will incorporate all about data querying. This is what enduser will work with.


答:
Well, this is a question, answer to which heavily depends on what requirements should the model satisfy. But in a general case I would vote for solution 1 (lightweight objects) because of the following reasons:

Of all application design rules there are in a world I consider the following of the uttermost importance: Lower the complexity of your code.

By complexity here I understand generic human-perceptible complexity. If you are building some puzzle for a six year old, it can contain quizzes like 2+2=?. You can, of course, make it 2+2+3-1+14/2+16 and it will still be ok. But when it becomes something like sqrt(4)+2*16^2 it tends to unnecessarily overcomplicate matters ;)

When you design a small application, putting everything into one model doesn't matter much since the code is still easy to understand. But when application grows, putting everything into one bowl will strike you with unmaintainable code soon.

Performance-wise it's faster to query/update small chunk of data

Usually you don't need every single piece of model data for each and every operation so small chunks are ok. Of course, your persistence layer should be able to work with related data, but then again, every more or less mature ORM now can do that well.

Title: What is a better design a light weight user or a heavy weight heavy user model?

Body:
This is a design question and I am confused about how to design my user  object. As in most systems, user is the central part of my application  and a lot of information scattered around my database points back to the user for example a user can have multiple orders, mulitple Addresses, and he may have won multiple prizes. If we want to talk about ONLY user and his basic information we can be done with ID, firstnmae, lastname etc. So I have two clear choices

Create a light weight  user object which looks like following:

```<code> public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
}
</code>```

and get all the infromation at the other information at the run time like orders and Prizes on need basis.

OR

Design a more contained object which carries all the required information with it but is little heavy:

```<code>public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
  public Address HomeAddress {get;set;}
  public List<Prizes> Prizes {get;set;}

}
</code>```

Which Does any design model align to a good design philosophy? Are there any best practices in the kind of situation that can help me make a decision?


问:
Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

答:
When I learned SQL, the INNER JOIN, LEFT JOIN, etc. forms didn't exist.  As other answers have already stated, different dialects of SQL had each implemented outer joins using idiosyncratic syntax.  This damaged portability of SQL code.  Bringing the language back together required some change, and LEFT JOIN, etc. was what they settled on.

It's true that for every INNER JOIN, an equivalent comma join with the join condition in the WHERE clause can be written.  It took me a while to migrate from liking the old form to preferring the new form.  Apparently, the author of Learning SQL the Hard Way still thinks the old way is easier.

Are there any differences?  Well, yes, there are.  The first is that an INNER JOIN with an ON clause reveals the author's intent more clearly than the old style join.  The fact that the ON clause is in fact a join condition and not some other kind of restriction is more obvious.  This makes code that uses INNER JOIN easier to learn when reading than the old style.  This is important when maintaining someone else's code.

The second difference is that the new style makes it marginally easier for the query optimizer to discover the winning strategy.  This is a very small effect, but it's real.

The third difference is that when you learn using INNER JOIN (or just plain JOIN) it makes it easier to learn LEFT JOIN, etc.

Apart from that there is no material difference at all.


答:
Perhaps this is best answered with a concrete example. Let's consider the case where you're creating a desktop application. You've decided to have a function named createMenubar, createToolbar and createMain so that your application constructor is neat and tidy.

Your main code will look something like this (this example is in python):

```<code>class ExampleApp():
    def __init__(self):
        self.createMenubar()
        self.createToolbar()
        self.createMain()
</code>```

Until you have everything working, your main function will fail, so how can you test your app during development? For example, if you start out working on createMenubar, the initialization will fail after it creates the menubar since you haven't implemented the toolbar or main area of the GUI.

This is where stubs come in. You can create a function named createToolbar and createMain that satisfy the requirement of the app constructor (namely, that these functions exist), without having to actually implement them. These functions are stubs:

```<code>def createToolbar():
    pass

def createMain():
    pass
</code>```

With those stubs in place you can begin to implement the main program and the menubar, without having to worry about the details of the toolbar or main part of the program. Eventually you'll move on to the toolbar, and replace the stub with the actual function. And finally, you'll remove the stub for createMain and give that a real implementation.

Note that stubs don't necessarily have to do nothing. These stub could, for example, create an empty container widget that the app constructor can lay out. The point is, you create dummy functions or objects that do just enough to let your other code run while you are developing it. Over time you replace the stubs one-by-one until your application is complete.

Title: What does stubbing mean in programming?

Body:
I often hear the term "stub", "stub something out", "stubs", and so forth.

What does stubbing mean in programming, and where does the word come from? In what contexts can it be used?

Body:
Perhaps this is best answered with a concrete example. Let's consider the case where you're creating a desktop application. You've decided to have a function named createMenubar, createToolbar and createMain so that your application constructor is neat and tidy.

Your main code will look something like this (this example is in python):

class ExampleApp():
    def __init__(self):
        self.createMenubar()
        self.createToolbar()
        self.createMain()

Until you have everything working, your main function will fail, so how can you test your app during development? For example, if you start out working on createMenubar, the initialization will fail after it creates the menubar since you haven't implemented the toolbar or main area of the GUI.

This is where stubs come in. You can create a function named createToolbar and createMain that satisfy the requirement of the app constructor (namely, that these functions exist), without having to actually implement them. These functions are stubs:

def createToolbar():
    pass

def createMain():
    pass

With those stubs in place you can begin to implement the main program and the menubar, without having to worry about the details of the toolbar or main part of the program. Eventually you'll move on to the toolbar, and replace the stub with the actual function. And finally, you'll remove the stub for createMain and give that a real implementation.

Note that stubs don't necessarily have to do nothing. These stub could, for example, create an empty container widget that the app constructor can lay out. The point is, you create dummy functions or objects that do just enough to let your other code run while you are developing it. Over time you replace the stubs one-by-one until your application is complete.


答: A "stub" is used in "top down" programming. That's when you are building your application from the general to the specific. In so doing, you will use "stubs" as "placeholders" for the specific applications that you haven't had time to build. They often return things like dummy or random values to the more general part of the program. That's all right, the stub feeds enough of a value to make the more "senior" part of the program work. Until it is time for the stub to be replaced or fitted with its true computation or value.</p>

Title: What does stubbing mean in programming?


问:
How to handle a memory consuming member variable
Suppose multiple objects of the same class should do something which takes a memory consuming resource. Which of the following approaches is recommended to define and use the resource by the objects?

Each object create the resource in its own

Declare one resource instance and pass it to each object

Using a static object for the resource

Let me give an example

```<code>class Section
{
     public Bitmap Page {/* set and get the page...*/}
     Bitmap page = new Bitmap(600,800);
     Draw(SomeThing s)
     {
        // Draw something on the page
     }
}

// in somewhere else
foreach (Section sect in Sections)
{
     sect.Draw(something);
     Video.AddFrame(sect.Page);
}
</code>```

Versus.

```<code>class Section
{
     public Bitmap Page {/* set and get the page ...*/}
     Bitmap page; // it isn't instantiated in the class
     Draw(SomeThing s)
     {
        // Clear the page
        // Draw something on it
     }
}

// in somewhere else
Bitmap screen = new Bitmap(600,800); // the common resource
foreach (Section sect in Sections)
{
     sect.Page = screen;
     sect.Draw(something); // it clears it before drawing something on it
     Video.AddFrame(screen);
}
</code>```

Versus.

```<code>class Section
{
     public Bitmap Page {/* set and get the page ...*/}
     static Bitmap page = new Bitmap(600,800);
     Draw(SomeThing s)
     {
        // First Clear the page
        // Draw something on the page
     }
}

// and in somewhere else
foreach (Section sect in Sections)
{
     sect.Draw(something);
     Video.AddFrame(sect.Page);
}
</code>```

First I used the first approach but it consumed a lot of memory as each object in my Sections array had a bitmap. Then I was forced to try the second approach. Is this new approach better than the former on all aspects? What is the guideline for such situations?

答:
That really depends on threading model your application uses.

In a single-threaded sequential scenario I would either pass bitmap around (if it's construction is a costly operation)  or have it created / destroyed each time. But you have to create such memory-intensive objects immediately before they are going to be used and destroy them as soon as you no longer need them if possible. Don't create them in the constructor and leave hanging around.

If we are about to enter multithreading you can either create a thread-safe pool of them (if construction of a bitmap is costly in your scenario) or just create /destroy each time you need it. But again, don't create objects just for fun. Create them when you need them.


问:
API - How to handle scope based functionality?

TLDR;

Where and possibly how should I implement scope based logic in the
  example code?

I have got a ASP.NET Web Api.

The Api uses OData (on top off REST) for data endpoints and OAuth 2.0 authentication.
Now I want to add functionality to handle an Access Token in several different scopes.

Some of the scopes are:

User

Organization

Customer

The result set the API returns should be based on this scope.
The same applies if someone wants to add, update or delete an entity.

Now take for example the following endpoint:

http://myapi/Employees

Someone with a Token in the Organization scope does a GET and should only get the employees that are in the Organization that is defined within the Token. An user in the Customer scope should get the employees for all organizations within the customer defined in the Token. This functionality however is not available for someone with a Token in the User scope.

The same applies to a POST. Someone within the organization scope should only be allowed to add a new employee to his own organization.

The functionality for the different scopes will usually only differ a little bit.
In the case of getting the employees the difference is only a where on organization or otherwise on customer. In the case of a post their should be a check to see if for example the organization is part of the customer that is bound to the customer Token.

Current implementation:

Currently we have a base ApiController which is generic typed.
The base controller calls an Query or CommandHandler with the entity type and all the implementation details are inside this handlers.

ApiController

```<code>public abstract class ApiController<TEntity> : EntitySetController<TEntity, Guid>
    where TEntity : class, IApiEntity
{
    protected readonly IQueryProcessor QueryProcessor;
    protected readonly ICommandProcessor CommandProcessor;

    protected ApiController(IQueryProcessor queryProcessor, ICommandProcessor commandProcessor)
    {
        this.QueryProcessor = queryProcessor;
        this.CommandProcessor = commandProcessor;
    }

    [HttpGet]
    public override IQueryable<TEntity> Get()
    {
        var command = new GetEntityCommand<TEntity>();
        return this.QueryProcessor.Process(command);
    }
}
</code>```

EmployeeController

```<code>public class EmployeeController : ApiController<Employee>
{ }
</code>```

GetEmployeeHandler

```<code>public class GetEmployeeCommandHandler : IQueryHandler<GetEntityCommand<Employee>, IQueryable<Employee>>
{
    public IQueryable<Employee> Handle(GetEntityCommand<Employee> command)
    {
         // Code that knows how to get a collection of employees.
         // This collection contains all employees
    }
}
</code>```

PostEmployeeHandler

```<code>public class PostEmployeeCommandHandler : ICommandHandler<PostEntityCommand<Employee>, Employee>
{
   public Employee Handle(PostEntityCommand<Employee> command)
    {
         // Code that knows how to add an employee to the database.
    }
}
</code>```

The question

Where and possibly how should I implement the scope based logic?
I know there has to be a smart way to do this and a good place to implement this scope based logic, I just don't see it (yet).

答:
I would recommend not to return different information on the same URI based on user's scope.

It's better to validate a set of parameters a client passes to the service against scopes he authorized. REST identifies a resource or resources via its URI. and it looks to me to be against REST principles to return different sets of information via the same URI.

So, in your code just make sure the client requesting http://myapi/Employees/?organization=xyz has scope organization_xyz before returning anything to him.


问:
From a DDD perspective is a report generating service a domain service or an infrastructure service?
Let assume we have the following service whose responsibility is to generate Excel reports:

```<code>class ExcelReportService{

   public String generateReport(String fileFormatFilePath, ResultSet data){
      ReportFormat reportFormat = new ReportFormat(fileFormatFilePath);
      ExcelDataFormatterService excelDataFormatterService = new ExcelDataFormatterService();
      FormattedData formattedData = excelDataFormatterService.format(data);
      ExcelFileService excelFileService = new ExcelFileService();
      String reportPath= excelFileService.generateReport(reportFormat,formattedData);
      return reportPath;
   }
}
</code>```

This is pseudo code for the service I want to design where:

fileFormatFilePath: path to a configuration file where I'll keep
the format of my excel file (headers, column widths, number of
columns,..etc)

data: the actual records returned from the database. This data

can't be used directly coz I might need to make further calculations
to the data before inserting them to the excel file.

ReportFormat: Value object to hold the report format, has methods

like getHeaders(), getColumnWidth(),...etc.

ExcelDataFormatterService: a service to hold any logic that need to
be applied to the data returned from the database before inserting it
to the file.

FormattedData: Value object the represents the formatted data to be
inserted.    ExcelFileService: a wrapper top the 3rd party library
that generates the excel file.

Now how do you determine whether a service is an infrastructure or domain service?

I have the following 3 services here:

ExcelReportService, ExcelDataFormatterService and ExcelFileService?

答: I think you may put it this way: in your specific case if the main purpose of the application / webservice / whatever you are developing is to make reports, then reporting tends to be considered a domain service. Otherwise it is an infrastructure service.</p>


问:
JSON or protocol buffer to replace the custom TCP message
Originally, We have two applications communication with TCP/IP, and both of them are implemented by C++. The messages between them are custom message type.

Now the client program will be changed to web application based on nodejs and the communication between them will be changed to message bus such as rabbitmq

So the message type between them should be changed.

JSON comes to my mind first, however the custom messages are too complicated, which are defined by template and inheritance. It seems that convert the custom message to JSON is not a good option. Am I right?

```<code>class Address {
    int network;
    int addressType;
    //...
};

class MsgType{
    unsigned char   msgSeq;
    unsigned int    msgLen;
    //...
};

class Message{
    Address destination;
    Address source;
    MsgType msgType;

    //...
};

template <typename T, int RESPONSE_TYPE>
class ResponseMessage : public Message{
    //...
}

typedef struct{
    int number;
    int type;
}ConfigResp;

class CfgResp : public ResponseMessage<ConfigResp, CONFIG_REQUEST>
{
    //...
}
</code>```

Protocol Buffers is another option for me to do that. What should I do?
redefine the custom message into protocol buffer? no no

Here is my solution: Just wrap the whole original custom message (binary type) into protocol buffer as one message in the server side, then decode the custom message(binary type) in client side. Is that possible?

答:
Well, applications tend to become more complicated with time. If you will ever need to handle separate versions of API which will in turn require you to maintain several versions of data structure, I think you'd better go with protocol buffers since they are designed with some versioning in mind. With JSON you will be on your own.

If at a given moment in time you are required to support only one version of a protocol, you may consider writing a serializer for your bussiness objects to stream them into JSON back and forth.

Another thing to consider is speed. I think protocol buffers could be faster when it comes to serialization/deserialization speed than pure json. But that needs to be carefully tested since this depends on implementation.


问:
Version control for independent developers?
Do you think it's worth it to use version control if you are an independent developer, and if so, why? Do you keep the repository on your own computer, or elsewhere, where it can serve as a backup?</p>

答: Worth?? Must! If you don't use Source Control then you don't control you sources, and that's bad. You can't diff you can't revert, you can't track changes - you'll spend hours trying to find out the dummy bug you just entered. It is better to have it on some backed up server, but you can also you your computer and use any backup method you find appropriate.

ContentLicense: CC BY-SA 2.5


问:
Why is the Document Object Model the view?
I was told by a Javascript programmer not to do DOM manipulation in model code.

I also remember hearing a snazzy tune for a JS framework (I forget which one): "Get your models out of the DOM".

This is confusing to me. The DOM is the Document Object Model. To me it sounds like "get your model out of the model".

Should my JS model really not touch the DOM? Can someone set me straight on model v. model?

答: "Model" in "Document Object Model" is not referring to "Model" in "Model-View-Controller". It's just a Module which we use to manipulate the DOM. We do data handling in Model(MVC) and do some logic in the Controller and what you're referring DOM is to be used in View(MVC) as we are representing the view for the user.</p>


问:
Should Latin-1 be used over UTF-8 when it comes to database configuration?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.

When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.

My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).

The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?

Are there other reasons one should use Latin-1 over UTF-8? It's my understanding that it is superior and becoming more ubiquitous.

答:
Some situations where restricting the character set only to ASCII may make sense is for limited choice fields, e.g. status fields, because you strictly control the values that can be there, and foreign key/references to external system, because there are rarely any reasons for them to have anything but alphanumeric characters and a few symbols.

For any other texts, just use UTF-8.


问:
Is Emailing waste of time in Dev Teams
I know its not strictly related to what people ask here but I have to ask this anyway.

Isn't having long conversations/discussions over emails reduce one's productivity. I have joined this new company where people prefer emails alot. It's not a big company so every one is accessible to everyone and also senior techies tend to get together for a 30 mins session every day to discuss and plan things with managers and stake holders.

I think emails are great and should be used as long as they are to the point and don't waste anyone's time. In my professional experience getting or agreeing things over emails quickly becomes an endless game of ping-pong. Reaching to a conclusion often takes days just because.. oh well..not everyone has enough time to go through lengthy emails. Email subjects often become less subjective and more "re:re:re:re:fw:". After few "re:re's" and "fw:fw's" it becomes a nightmare to find what you're looking for since not every single thing in emails is a key-point so coming back to conversation after 8-9 months is like going through someone's source code writen in C.

It's also not the best approach for discussing ideas or agreeing over things as most people tend to be more reserved in email conversations than they are in real life because it's very easy to misinterpret one's tone.

Most of the times I find it much easier and quicker to send an email saying "Lets discuss thing X at xx:xx" followed by a quick call at agreed time rather than dragging the issue for days (or in some cases weeks). When needed I follow up with an email saying "well here's what we agreed on the phone".

Also people are generally more respectful to each other and open to discussions when talking face to face or over the phone.

Don't get me wrong, emails are important and should be used whenever they are absolutely necessary. But in small/medium sized teams why is this culture (of writing long stories i.e. emails) so so important ? why don't people use tools like Basecamp, redmine, wiki's instead.

How would you improve your team or company's communications so people become more productive and create a friendly environment.

Thank you for reading.

答:
Email is great for temporary communication, scheduling, organization, and so forth - especially with calendar or to-do list integration and other nifty features.  It can be good for meta-discussions that involve a lot of opinions and shouldn't be documented as fact provided it is somehow easy to filter (e.g., email aliases for topic discussion), and can be good for quick information that doesn't need to be documented (although I prefer IM or face-to-face for this).

Anything that is likely to be needed over and over again should be properly documented in an easy-to-locate spot.  Our company likes to use a wiki.  Some companies use SharePoint.  If it isn't leveraging an email feature like the calendar and will be needed again a few weeks later, generally it is better (IMO) to document it somewhere else.

To get your company to avoid using email when things should be documented, I think the thing to do is:

Make sure your company has a
repository for information like this;
if not, set up a wiki or something
yourself

Use the repository religiously; be a good example

When others fail to use the repository of information and instead email it out, either reply-all with "Should this go on the Sharepoint / wiki?" if the person is normally good about this kind of thing, or put it up yourself and then send a reply-all with "I put this up on the Sharepoint / wiki at [URL]" if they are often forgetful.  Reply-all lets your message affect a broader spectrum of people.

A similar approach can be taken for moving meta-discussions and "fun" emails to aliases.

Most workplaces I've been in have rules about marking "fun" emails low-pri or using a particular "off-topic" alias - this can also clean up a lot of clutter.

I find long emails with lots of discussion often indicate that a meeting would be a really, really good idea.  So you could also ask if people could schedule a meeting when you see that, or (depending on company culture) just go ahead and schedule it yourself. Then make sure the notes from the meeting get posted on your information repository, and just email the link instead of the notes themselves.

Title: Is Emailing waste of time in Dev Teams


问:
How handle a chain of Whens or Thens in a Scenario?
I am trying to figure out how to write BDD scenario where it seems like I need a chain of "Then" conditions.  How do I write it?  As one scenario?  As two scenarios?

Here is how I've written as one scenario:

```<code>Scenario: Take user directly to their message on swipe after login
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in
And she is taken directly to the specific message shown in the preview
</code>```

It's the last two lines I'm unsure of.  What I'm trying to say she is taken directly to the specific message shown in the preview should not occur until after she must log in.  They should not co-occur, which is what I suspect an Then containing an And probably means.

Should I separate it into two scenarios like this:

```<code>Scenario: Make user login after swipe
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
When she swipes the preview
Then she must log in

Scenario: Take user to message after logging in
Given Dee has received a push notification
And she is logged out of Uluvit
And the message preview appears on her locked phone screen
And she has swiped the preview
When she logs in
Then she is taken directly to the specific message shown in the preview
</code>```

Thanks in advance for your help.

答:
Generally, you rarely see more than 1 "when" in a scenario. The "when" is exercising the behaviour that you're interested in.

As others have posted, you have two aspects of behaviour here:

Users must log in before they can access content on the phone

Users who use a preview will be taken to that preview when they log in.

So you could always have two scenarios.

However, there are a couple of times when it is OK to have two whens (notwithstanding whether your framework deliberately limits you to one or not; some do).

It's OK to have two whens when you have an interaction between two different stakeholders, or time passes.

In this instance, the behaviours aren't separated. They're actually strongly related. One of them is to do with a user who wants to access her phone content, and the other is to do with people who want content to be secure (either the user in another role, or potentially an employer). You can see that from the way the second requirement contains the first.

When you talk to a domain expert about this, they probably won't separate it when they run through the scenario, either. They might elide the fact that you log in. Either way, it's perfectly OK to do this as one scenario. You can explicitly have both whens:

When she swipes the preview

  And logs in

  Then she should be taken directly to the specific message shown in the preview.

If you do decide to go with two scenarios, I would make one of them miss out the fact that she's logging in, and just do it as part of the step where she accesses the message, both logging in and swiping:

When Dee accesses the message

And then have a separate one which explicitly calls out the security aspect:

When Dee swipes the preview

  Then she should be forced to log in before she can view it.

These will actually do the same thing, which makes them redundant, so I'd tend to go with one scenario for pragmatism, and either miss out the fact that she's logging in (which is fine if it's obvious) or have two "whens".

Note that because logging in is an aspect of behaviour that you're actively interested in, it should definitely be a when and not a then. Lots of people reckon you should only ever have one when, but it's not how people talk when requirements interact, and BDD was designed to capture conversation, not torture it.


问:
Does ORM at any point become a "requirement" for RESTful API?
I've started building a RESTful API in PHP's Slim framework. The framework appealed to me because of its light-weight design and routing features. I am using PostgreSQL for the database.

However, the dataset is somewhat large - there would be about 20 types of resources, with many associations and nested sets. So far, I have implemented my own custom ORM methods on resource classes, such as "select from database by primary key". Slim does not provide any ORM features. I am wondering if the scale of the API is large enough to recommend the use of a framework with built-in ORM support or integration with an ORM such as Doctrine or Propel.

Am I at the point where I should use an ORM to help mitigate the complexity of changes to  database tables, attribute names, etc?

I am also open to using other technologies - it seems Python's Django is highly regarded as a framework for building RESTful APIs.

答:
An ORM is not a requirement for any project of any scale. More often, small projects start with an ORM, then abandon it when scaling up.

If database changes become too complex:

Ask yourself why is the database changing too often.

I had to work on projects where database was changed at least once per day, just because the project was badly thought, requirements not gathered correctly, and database originally created by a person who knew nothing about databases in general. An unnecessary nightmare.

If you've found that changes are due to the complex, volatile structure of the data which is constantly extending, consider using non-relational databases. A document model (such as what is used in MongoDB) may better correspond to your needs.

If there are no that much changes, but you're simply overwhelmed by the size of the schema, consider splitting your service into multiple ones, each owning a part of a database.

By constraining each service to use only a part of a database (and call other services to access other data), you may make it really simple to deal with changes: the scope of each change would be limited to a concerned service instead of being spread over the code base.