问:
MVVM and service pattern
I'm building a WPF application using the MVVM pattern. Right now, my viewmodels calls the service layer to retrieve models (how is not relevant to the viewmodel) and convert them to viewmodels. I'm using constructor injection to pass the service required to the viewmodel.

It's easily testable and works well for viewmodels with few dependencies, but as soon as I try to create viewModels for complex models, I have a constructor with a LOT of services injected in it (one to retrieve each dependencies and a list of all available values to bind to an itemsSource for example). I'm wondering how to handle multiple services like that and still have a viewmodel that I can unit test easily.

I'm thinking of a few solutions:

Creating a services singleton (IServices) containing all the available services as interfaces. Example: Services.Current.XXXService.Retrieve(), Services.Current.YYYService.Retrieve(). That way, I don't have a huge constructor with a ton of services parameters in them.

Creating a facade for the services used by the viewModel and passing this object in the ctor of my viewmodel. But then, I'll have to create a facade for each of my complexe viewmodels, and it might be a bit much...

What do you think is the "right" way to implement this kind of architecture ?

答:
Why not combine both?

Create a facade and put all services your viewmodels use. Then you can have single facade for all yourviewmodels without the bad S word.

Or you can use property injection instead of constructor injection. But then, you need to ensure that those are getting injected properly.

Title: MVVM and service pattern


问:
How to create single integer index value based on two integers where first is unlimited?
I have table data containing an integer value X ranging from 1.... unknown, and an integer value Y ranging from 1..9

The data need to be presented in order 'X then Y'.

For one visual component I can set multiple index names: X;Y

But for another component I need a one-dimensional integer value as index (sort order).

If X were limited to an upper bound of say 100, the one-dimensional value could simply be X*100 + Y.

If the one-dimensional value could have been a real, it could be X + Y/10.

But if I want to keep X unlimited, is there a way to calculate a single integer 'indexing' value from X and Y?

[Added] Background information:

I have a Gantt/TreeList component where the tasks are ordered on a TaskIndex integer. This does not need to be a real database field, I can make it a calculated field in the underlying client dataset.

My table data is e.g. as follows:

```<code>ID    Baseline   ParentID
 1       0          0     (task)
 5       2          1     (baseline)
 8       1          1     (baseline)
 9       0          0     (task)
12       0          0     (task)
16       1         12     (baseline)
</code>```

Task 1 has two baselines numbered 1 and 2 (IDs 8 and 5)

Task 9 has no baselines

Task 12 has one baseline numbered 1 (ID 16)

Baselines number 1-9 (the Y variable from my question); 0 or null identify the tasks

ID's are unlimited (the X variable)

The user plays with visibility of baselines, e.g. he wants to see all tasks and all baselines labeled 1. This is done by updating a filter on the table.

Right now I constantly have to recalculate TaskIndex after changing the filter (looping through records with a counter). It would be nice if TaskIndex could be calculated on the fly for each record knowing only the ID and Baseline data in the current record (I work in Delphi where a client dataset has an OnCalcFields event handler, that is triggered for each record when necessary).

I have no control over the inner workings of the visual component.

答:
since Y is bounded you can just use that as prefix because numbers grow to the right, so you can't use it as a suffix.

So if Y is 8 and X is a 4000 digit number, it would be 8XXXXXXXXXXXXXXXXXXXXXX[...].

Though I read that you are trying to do sorting, so this form of sorting would be Y first, X second which may not be what you want.

If you want to sort using the composition of X and Y with X as the primary, You may just want to have something sorted by X, where each element is another collection sorted by Y, then you can use a simplistic iteration over the set to get a flat list that is sorted as you wish.

ContentLicense: CC BY-SA 3.0


问:
How to practice object oriented programming?
I've always programmed in procedural languages and currently I'm moving towards object orientation. The main problem I've faced is that I can't see a way to practice object orientation in an effective way. I'll explain my point. When I've learned PHP and C it was pretty easy to practice: it was just matter of choosing something and thinking about an algorithm for that thing.

In PHP for example, it was matter os sitting down and thinking: "well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. Combining these with PHP features, it was a good way to practice.

Now, in object orientation we have lots of additional things. It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things.

The main point is that in the way I've been learning object orientation it seems that a good design is crucial, while in procedural languages one vague idea was enough. I'm not saying that in procedural languages we can write good software without design, just that for sake of practicing it is feasible, while in object orientation it seems not feasible to go without a good design, even for practicing.

This seems to be a problem, because if each time I'm going to practice I need to figure out tons of requirements, use cases and so on, it seems to become not a good way to become better at object orientation, because this requires me to have one whole idea for an app everytime I'm going to practice.

Because of that, what's a good way to practice object orientation?

答:
"well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products.

Why not do the same thing only this time with user objects and product objects?  Also if you are using a language that supports both procedural and OO then you could try to implement objects based on the procedural standard library, like a file object.


问:
What is meant by, "A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should."
The example used in the question pass bare minimum data to a function touches on the best way to determine whether the user is an administrator or not.  One common answer was:

```<code>user.isAdmin()
</code>```

This prompted a comment which was repeated several times and up-voted many times:

A user shouldn't decide whether it is an Admin or not. The Privileges
  or Security system should. Something being tightly coupled to a class
  doesn't mean it is a good idea to make it part of that class.

I replied,

The user isn't deciding anything. The User object/table stores data
  about each user. Actual users don't get to change everything about
  themselves.

But this was not productive.  Clearly there is an underlying difference of perspective which is making communication difficult.  Can someone explain to me why user.isAdmin() is bad, and paint a brief sketch of what it looks like done "right"?

Really, I fail to see the advantage of separating security from the system that it protects.  Any security text will say that security needs to be designed into a system from the beginning and considered at every stage of development, deployment, maintenance, and even end-of-life.  It is not something that can be bolted on the side.  But 17 up-votes so far on this comment says that I'm missing something important.

答: The poster merely had a different and more complicated design in mind.  In my opinion, User.isAdmin() is fine.  Even if you later introduce some complicated permissions model, I see little reason to move User.isAdmin().  Later, you may want to split the User class into an object representing a logged-in user and a static object representing the data about the user.  Or you may not.  Save tomorrow for tomorrow.


问:
Accuracy in calculating distance from Android Device using double integral?
Using TYPE_LINEAR_ACCELERATION suppose I found out that the device is moving at 4 m/s².

```<code>a(t)=s"(t)=+4
v(t)=∫4tdt
s(t)=2/3t³
s(3)=18m
</code>```

How much accurate it would be?

答:
Accuracy of the measurement will be specific to the device you are using and the chips used to create the sensor.

Accuracy (precision) of the calculation will be dependent upon the variable types (int, float, double, etc...) that you use.

Accuracy of the integration you are suggesting to calculate distance will depend upon how many samples you are able to gather, the frequency of those samples, and the accuracy of the samples themselves.

Your question is a minor example of the compounding error problem.  You are most likely limited by the sensor reading.  All of the subsequent operations upon that reading / those readings will compound that error.

Your best bet is to take a lot of readings and see how close they match your expectations for what you need it to do.


答:
I've run into a similar problem before, and I've solved it by taking advantage of the fact that padded binary will always sort correctly, whether parsed as a string or a number.

Here's pseudocode (padding to make a 32-digit number, you can trim it down):

```<code>define X,Y as int
define Xbin, Ybin as string
Xbin = ConvertToBinary(X).PadLeft(28, "0")
Ybin = ConvertToBinary(Y).PadLeft(4, "0")
return Xbin + Ybin
</code>```

For 5 randomly chosen sets of data:

```<code>6737, 7 -> 00000000000000011010010100010111
51, 6   -> 00000000000000000000001100110110
2, 0    -> 00000000000000000000000000100000
864, 5  -> 00000000000000000011011000000101
165, 3  -> 00000000000000000000101001010011
</code>```

Sorted (whether by string value or numeric value),

```<code>00000000000000000000000000100000 <- 2, 0
00000000000000000000001100110110 <- 51, 6
00000000000000000000101001010011 <- 165, 3
00000000000000000011011000000101 <- 864, 5
00000000000000011010010100010111 <- 6737, 7
</code>```

*Edit: * I used 228 worth of storage here, but since these can be stored as strings, there's no effective upper limit.  If you're storing the X in the database as an int, then you'd need to use 32 as the X-padding number.  If long, 64.  If you're using something which supports larger-than-64bit numbers, just keep expanding as appropriate.

If you're storing it as a string/varchar in the database, you have a problem.  If your language/database has a maximum length for a string, then you can't guarantee you won't overflow by adding extra information into it.  If you don't have a limit, you can't calculate the maximum padding you'd need.

Title: How to create single integer index value based on two integers where first is unlimited?

Body:
I have table data containing an integer value X ranging from 1.... unknown, and an integer value Y ranging from 1..9

The data need to be presented in order 'X then Y'.

For one visual component I can set multiple index names: X;Y

But for another component I need a one-dimensional integer value as index (sort order).

If X were limited to an upper bound of say 100, the one-dimensional value could simply be X*100 + Y.

If the one-dimensional value could have been a real, it could be X + Y/10.

But if I want to keep X unlimited, is there a way to calculate a single integer 'indexing' value from X and Y?

[Added] Background information:

I have a Gantt/TreeList component where the tasks are ordered on a TaskIndex integer. This does not need to be a real database field, I can make it a calculated field in the underlying client dataset.

My table data is e.g. as follows:

```<code>ID    Baseline   ParentID
 1       0          0     (task)
 5       2          1     (baseline)
 8       1          1     (baseline)
 9       0          0     (task)
12       0          0     (task)
16       1         12     (baseline)
</code>```

Task 1 has two baselines numbered 1 and 2 (IDs 8 and 5)

Task 9 has no baselines

Task 12 has one baseline numbered 1 (ID 16)

Baselines number 1-9 (the Y variable from my question); 0 or null identify the tasks

ID's are unlimited (the X variable)

The user plays with visibility of baselines, e.g. he wants to see all tasks and all baselines labeled 1. This is done by updating a filter on the table.

Right now I constantly have to recalculate TaskIndex after changing the filter (looping through records with a counter). It would be nice if TaskIndex could be calculated on the fly for each record knowing only the ID and Baseline data in the current record (I work in Delphi where a client dataset has an OnCalcFields event handler, that is triggered for each record when necessary).

I have no control over the inner workings of the visual component.

Body:
I've run into a similar problem before, and I've solved it by taking advantage of the fact that padded binary will always sort correctly, whether parsed as a string or a number.

Here's pseudocode (padding to make a 32-digit number, you can trim it down):

define X,Y as int
define Xbin, Ybin as string
Xbin = ConvertToBinary(X).PadLeft(28, "0")
Ybin = ConvertToBinary(Y).PadLeft(4, "0")
return Xbin + Ybin

For 5 randomly chosen sets of data:

6737, 7 -> 00000000000000011010010100010111
51, 6   -> 00000000000000000000001100110110
2, 0    -> 00000000000000000000000000100000
864, 5  -> 00000000000000000011011000000101
165, 3  -> 00000000000000000000101001010011

Sorted (whether by string value or numeric value),

00000000000000000000000000100000 <- 2, 0
00000000000000000000001100110110 <- 51, 6
00000000000000000000101001010011 <- 165, 3
00000000000000000011011000000101 <- 864, 5
00000000000000011010010100010111 <- 6737, 7

*Edit: * I used 228 worth of storage here, but since these can be stored as strings, there's no effective upper limit.  If you're storing the X in the database as an int, then you'd need to use 32 as the X-padding number.  If long, 64.  If you're using something which supports larger-than-64bit numbers, just keep expanding as appropriate.

If you're storing it as a string/varchar in the database, you have a problem.  If your language/database has a maximum length for a string, then you can't guarantee you won't overflow by adding extra information into it.  If you don't have a limit, you can't calculate the maximum padding you'd need.


问:
Dependency inversion always includes dependency injection?
This is a question on a home work. I've been up and down my notes and I can't even see how the two are related. Googling this gives me questions/answers on one or the other, but never both.</p>

答:
The wiki page on Dependency inversion principle tells :

Various patterns such as Plugin, Service Locator, or Dependency
  Injection are then employed to facilitate the run-time provisioning of
  the chosen low-level component implementation to the high-level
  component.

Therefore, the answer is : dependency injection is a technique to apply the dependency inversion principle, but it is not the only one.

There are other techniques when you want to use this principle (the linked wiki page lists plugins and service locator as additional techniques).

The dependency injection is a specific kind of inversion of control in a way that you somehow inject a lower level object into higher level object. That way, the higher level object depends on an abstraction - and not on the concrete implementation of a lower level object. In other words, it access an object through it's (usually abstract) interface.


问:
SOA, Java EE and data organization
At the company I work for, we're currently splitting up our monolith solution into a number of small services (SOA).

The purpose of this is to make the developers working on each chunk of code (service) more independent, and on the whole to make the code base more manageable. When a change in code is introduced, only one part (i.e. a whole service) needs to be deployed, instead of having to deploy everything. This also helps with testing, there's less of a need to test everything when something is deployed.

Many of the services are small, so we'd like to deploy a number of these services on the same application server, JBoss 7.1 in this case.

As per the SOA philosophy, the independence of each service and the teams working on them is very important. What would be the best way to organize the data?

Use one schema per service

Would you use one datasource per schema in the application server?

Or use one datasource, prefixing all DB object names with the schema name in some transparent manner?

Use a shared schema, but evading any naming collisions by requiring each service to use a distinct prefix for all DB objects

Other options?

Am I maybe thinking this completely wrong here? :)

Edit: Explained why the code base is being split up from a monolith to smaller services.

答:
I'm no SOA expert but I think you are looking for a more lightweight solution. In any case, see http://soaprinciples.com

If you are splitting up just one application I suggest studying the OSGI platform.

In the 'classic' SOA a Canonical Data Model is used http://soapatterns.org/design_patterns/canonical_schema, or at least it is a widely used pattern.

I don't get your DB object prefixing issue. In the Canonical Data Model you use xsd schemas for your data types and you can put them in different xml namespaces.

Title: SOA, Java EE and data organization


答:
Dependency Injection is a technique for implementing Dependency Inversion.

The Inversion of Control page on Wikipedia actually says it a little better, even though Dependency Inversion and Inversion of Control may not be exactly the same thing.

Here is what it says:

Implementation Techniques

In object-oriented programming, there are several basic techniques to
  implement inversion of control. These are:

using a factory pattern

using a service locator pattern

using a dependency injection, for example:

Constructor injection

Parameter injection

Setter injection

Interface injection

using a contextualized lookup

using Template method design pattern

using Strategy design pattern

So no, Dependency Injection is not the only way to accomplish Dependency Inversion.

Title: Dependency inversion always includes dependency injection?

Body: This is a question on a home work. I've been up and down my notes and I can't even see how the two are related. Googling this gives me questions/answers on one or the other, but never both.</p>


答:
Answer: No. Here's the difference:

Dependency Inversion is a principle.

High-level modules should not depend on low-level modules. Both should
  depend on abstractions. Abstractions should not depend on details.
  Details should depend on abstractions.

Dependency Injection is a technique, whereupon the dependencies -- rather, their abstractions -- are explicitly injected into an object, typically into the constructor, but sometimes exposed as properties. This can be done with Poor Man's DI or with an IoC Container.

Example of Poor Man's DI:

```<code>public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass(ISomeService someService)
    {
        SomeService = someService ?? new SomeServiceConcrete().
    }

    /* use SomeService elsewhere in the class */
}
</code>```

Example of DI with IoC:

```<code>public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass(ISomeService someService)
    {
        SomeService = someService.
    }

    /* use SomeService elsewhere in the class */
}
</code>```

The Service Locator Pattern, in contrast to Dependency Injection, requires the object to ask a service for its dependencies. This is considered an anti-pattern. The details of why is beyond the scope of the question and is left as an exercise for the reader.

Example of Service Locator:

```<code>public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass()
    {
        SomeService = SomeServiceLocator.GetInstance<ISomeService>();
    }

    /* use SomeService elsewhere in the class */
}
</code>```

Body:
Answer: No. Here's the difference:

Dependency Inversion is a principle.

High-level modules should not depend on low-level modules. Both should
  depend on abstractions. Abstractions should not depend on details.
  Details should depend on abstractions.

Dependency Injection is a technique, whereupon the dependencies -- rather, their abstractions -- are explicitly injected into an object, typically into the constructor, but sometimes exposed as properties. This can be done with Poor Man's DI or with an IoC Container.

Example of Poor Man's DI:

public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass(ISomeService someService)
    {
        SomeService = someService ?? new SomeServiceConcrete().
    }

    /* use SomeService elsewhere in the class */
}

Example of DI with IoC:

public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass(ISomeService someService)
    {
        SomeService = someService.
    }

    /* use SomeService elsewhere in the class */
}

The Service Locator Pattern, in contrast to Dependency Injection, requires the object to ask a service for its dependencies. This is considered an anti-pattern. The details of why is beyond the scope of the question and is left as an exercise for the reader.

Example of Service Locator:

public class ConsumingClass
{
    private readonly ISomeService SomeService;

    public ConsumingClass()
    {
        SomeService = SomeServiceLocator.GetInstance<ISomeService>();
    }

    /* use SomeService elsewhere in the class */
}


答:
The simple answer to your question is "No, Dependency Injection is not always present when Dependency Inversion is used."

Simply put, "Dependency Inversion" is the principle and "Dependency Injection" is just one method of implementation. As noted in another answer, there are other implementations of the principle including Service Locators and Plug-In Frameworks.


答:
There are two sources of errors here: (a) numerical inaccuracies stemming from floating-point representations, and (b) general measurement errors, which in turn are either (b.1) calibration errors (your accelerometer has a skewed or drifting scale) or (b.2) statistical uncertainty.

Errors from (a) are difficult, but possible to quantify exactly. However, they are likely small when compared with (b).

Errors from (b.1) can be compensated by calibrating the accelerometer with other devices. In the general case, this involves transforming the data along a calibration curve. Note that this can amplify errors from (b.2).

Errors from (b.2) cannot be corrected, but we can use them to say how exact our end result is. First, the uncertainty has to be quantified by measuring the acceleration in an experiment (e.g. dropping the device, and wirelessly collecting acceleration data) which is repeated as often as possible. From the data set, we can calculate the mean μa, and the standard deviation σa for the acceleration. Because your average Android device has varying air resistance depending on the orientation, the measurements will be probably spread over a large interval.

We now wish to estimate the standard deviation of the displacement s in dependency of the acceleration a. First, they are related via:

s(t) = ½ a · t²

because a = d²/dt² s ⇔ s = ∫∫ a dt² ⇔ ∫ a·t dt.

Now, σs can be calculated as:

σs = ( ∂/∂a s(t) )² · σa²

which is terribly convenient, because then

σs = (½ · t²)² · σa² = ¼ · t4 · σa²

Note that the uncertainty depends on the time t.

Example

Let the acceleration be a = 4 m·s-2 with σa = 0.3 m·s-2, and the duration be t = 3 s. We then get:

s(t) = 18 m

  σa = 1.8225 m

so that the relative error σ/s is 10.1%.

If we change t = 0.7 s, then we would get

s(t) = 0.98 m

  σa = 5.402E-3 m

so that σ/s = 0.6%.

What does this mean? For short durations/distances, even large errors make for fairly accurate results. You might just as well ignore them. However, the error grows in O(t4), which is quite fast. So over a longer distance/duration, you tend to get very uncertain results (which may still be useful, depending on the problem domain).

We can calculate the distances or times where the σ/a -ratio stays within a certain value p:

p ≥ (¼ · t4 · σa²) / (½ a · t²) = ½ · σa²/a · t²

  t ≤ √( 2 · p · a/σa² )

So with the previous values for acceleration and deviation, and a limit for p at 5%, we now know that any extrapolations longer than  t = √4.44 s = 2.11 s (equivalent to a distance of 8.89 m) are too uncertain.

For further reading, you should look at Propagation of Uncertaincy at Wikipedia.

Title: Accuracy in calculating distance from Android Device using double integral?

Body:
Using TYPE_LINEAR_ACCELERATION suppose I found out that the device is moving at 4 m/s².

```<code>a(t)=s"(t)=+4
v(t)=∫4tdt
s(t)=2/3t³
s(3)=18m
</code>```

How much accurate it would be?


问:
How does copyrights apply to source code header files?
It seems I heard that header files are not considered copyrightable since they can only be written one way (like a list of ingredients or facts). So a header file for a specific DLL will always look the same when written in a given programming language. Unfortunately I can't find any resources to back this up.

So if a vendor provides an SDK with headers in one programming language, and then those headers are translated into another programming language by a third party. Does the 3rd party need permission from the vendor to provide the header translation? Who owns the copyright on the translation? Isn't it a derivative work still owned by the vendor, or is there no copyright, like a list of ingredients?

Does this vary from jurisdiction to jurisdiction?

答:
I am not a lawyer.  I do not play one on TV.  Questions of legality should be answered by someone who is capable of giving expert answers (a lawyer) rather than just some programmer who has a passing familiarity with intellectual property.

The key part of a copyright is that it requires some creative considerations. This is a very low threshold, but some amount of creative action is necessary (another resource - software freedom - originality requirements.  Things that cannot be copyrighted include recipes and phone books.  Fundamental facts can't be copyrighted (from EE.SE - Avoiding copyright violations when writing header files)

There have been multiple lawsuits over minimal bits of code (SCO and errno.h, Google and Oracle over some Java code, Google and android header files (there are some bits in there linking to some legal opinions on it that are a good read)).  However, I haven't seen anything that has set precedent on if header files can be copyrighted or not, or the degree to which their material is original.

If it isn't clear that all of this is in legal murky water, let me state that again.  This isn't a settled area of law.  Ask a lawyer.


答:
According to Free Software Foundation's lawyers copyright does not apply to header files:

I'm not sure what your project is designed to do, so I don't have an
  opinion about how it stands regarding the GPL. However, I've talked
  with our lawyer about one specific issue that you raised: that of
  using simple material from header files.

Someone recently made the
  claim that including a header file always  makes a derivative work.

That's not the FSF's view. Our view is that just using structure
  definitions, typedefs, enumeration constants, macros with simple
  bodies, etc., is NOT enough to make a derivative work. It would take
  a substantial amount of code (coming from inline functions or macros
  with substantial bodies) to do that.  (source: email by RMS on LKML)

There is legal precedence supporting that. Oracle's lawyers attempted to claim that APIs (and header files defining the APIs) are copyrightable, yet the court has disagreed with them (emphasis mine).

However, on the primary copyright issue of the APIs, the court ruled
  that "So long as the specific code used to implement a method is
  different, anyone is free under the Copyright Act to write his or her
  own code to carry out exactly the same function or specification of
  any methods used in the Java API. It does not matter that the
  declaration or method header lines are identical." The ruling found
  that the structure Oracle was claiming was not copyrightable under
  section 102(b) of the Copyright Act because it was a "system or method
  of operation." (source: Oracle vs Google)

Title: How does copyrights apply to source code header files?

Body:
It seems I heard that header files are not considered copyrightable since they can only be written one way (like a list of ingredients or facts). So a header file for a specific DLL will always look the same when written in a given programming language. Unfortunately I can't find any resources to back this up.

So if a vendor provides an SDK with headers in one programming language, and then those headers are translated into another programming language by a third party. Does the 3rd party need permission from the vendor to provide the header translation? Who owns the copyright on the translation? Isn't it a derivative work still owned by the vendor, or is there no copyright, like a list of ingredients?

Does this vary from jurisdiction to jurisdiction?


答:
I wouldn't have chosen to word the original comment the way it was worded, but it does identify a potentially legitimate issue.

Specifically, the concerns that warrant separation are authentication vs. authorization.

Authentication refers to the process of logging in and getting an identity. It is how the systems knows who you are, and used for things like personalization, object ownership, etc.

Authorization refers to what you are allowed to do, and this (generally) is not determined by who you are. Instead, it is determined by some security policy like roles or permissions, which don't care about things like your name or email address.

These two can change orthogonally to each other. For example, you might change the authentication model by adding OpenID/OpenAuth providers. And you might change the security policy by adding a new role, or changing from RBAC to ABAC.

If all of this goes into one class or abstraction, then your security code, which is one of your most important tools for risk mitigation, becomes, ironically, high-risk.

I have worked with systems where authentication and authorization were too tightly coupled. In one system, there were two parallel user databases, each for one type of "role". The person or team who designed it apparently never considered that a single physical user might be in both roles, or that there might be certain actions which were common to multiple roles, or that there could be problems with User ID collisions. This is an admittedly extreme example, but it was/is incredibly painful to work with.

Microsoft and Sun/Oracle (Java) refer to the aggregate of authentication and authorization information as the Security Principal. It's not perfect, but it works reasonably well. In .NET, for example, you have IPrincipal, which encapsulates the IIdentity - the former being a policy (authorization) object while the latter is an identity (authentication). You could reasonably question the decision to put one inside of the other, but the important thing is that most code you write will be for just one of the abstractions which means it is easy to test and refactor.

There's nothing wrong with a User.IsAdmin field... unless there is also a User.Name field. This would indicate that the "User" concept isn't properly defined and this is, sadly, a very common mistake among developers who are a bit wet behind the ears when it comes to security. Typically, the only thing that should be shared by identity and policy is the User ID, which, not coincidentally, is exactly how it is implemented in both the Windows and *nix security models.

It's completely acceptable to create wrapper objects that encapsulate both identity and policy. For example, it would facilitate the creation of a dashboard screen where you need to display a "hello" message in addition to various widgets or links that the current user is permitted to access. As long as this wrapper just wraps the identity and policy information, and doesn't claim to own it. In other words, as long as it's not being presented as an aggregate root.

A simplistic security model always seems like a good idea when you're first designing a new application, because of YAGNI and all that, but it almost always ends up coming back to bite you later, because, surprise surprise, new features get added!

So, if you know what's best for you, you'll keep authentication and authorization information separate. Even if the "authorization" right now is as simple as an "IsAdmin" flag, you'll still be better off if it's not part of the same class or table as the authentication information, so that if and when your security policy needs to change, you don't need to do reconstructive surgery on your authentication systems which already works fine.

Title: What is meant by, "A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should."

Body:
The example used in the question pass bare minimum data to a function touches on the best way to determine whether the user is an administrator or not.  One common answer was:

```<code>user.isAdmin()
</code>```

This prompted a comment which was repeated several times and up-voted many times:

A user shouldn't decide whether it is an Admin or not. The Privileges
  or Security system should. Something being tightly coupled to a class
  doesn't mean it is a good idea to make it part of that class.

I replied,

The user isn't deciding anything. The User object/table stores data
  about each user. Actual users don't get to change everything about
  themselves.

But this was not productive.  Clearly there is an underlying difference of perspective which is making communication difficult.  Can someone explain to me why user.isAdmin() is bad, and paint a brief sketch of what it looks like done "right"?

Really, I fail to see the advantage of separating security from the system that it protects.  Any security text will say that security needs to be designed into a system from the beginning and considered at every stage of development, deployment, maintenance, and even end-of-life.  It is not something that can be bolted on the side.  But 17 up-votes so far on this comment says that I'm missing something important.


问:
Are post conditions of a routine a subset of precondtions?
Like the title says. The post conditions of a routine must be a subset of the preconditions for the routine?

The way I understand post-conditions is that they are entirely independent of preconditions, so my understanding leads me to think that they are not a subset of preconditions.

Any input would be appreciated.

答:
How about a concrete example:

```<code>int x;
// Preconditions: none (empty set)
// Postconditions: x = y
void assign_to_x(int y) { x = y; }
</code>```

If you allow any form of mutable state in your program, you can have postconditions that are not subsets of your preconditions.

Body:
How about a concrete example:

int x;
// Preconditions: none (empty set)
// Postconditions: x = y
void assign_to_x(int y) { x = y; }

If you allow any form of mutable state in your program, you can have postconditions that are not subsets of your preconditions.


问:
How do I set up pairing email addresses?
Our team uses the Ruby gem hitch to manage pairing. You set it up with a group email address (e.g. dev@mycompany.com) and then tell it who is pairing:

```<code>$ hitch james tiffany
</code>```

Hitch then sets your Git author configuration so that our commits look like

```<code>commit 629dbd4739eaa91a720dd432c7a8e6e1a511cb2d
Author: James and Tiffany <dev+james+tiffany@mycompany.com>
Date:   Thu Oct 31 13:59:05 2013 -0700
</code>```

Unfortunately, we've only been able to come up with two options:

dev@mycompany.com doesn't exist. The downside is that if Travis CI tries to notify us that we broke the build, we don't see it.

Dev@mycompany.com does exist and forwards to all the developers. Now the downside is that everyone gets spammed with every broken build by every pair.

We have too many possible pair to do any of the following:

set up actual pair-james-tiffany@mycompany.com email addresses or groups (n^2 email addresses)

set up forwarding rules for dev+james+tiffany@mycompany.com (n^2 forwarding rules)

set up forwarding rules for james+tiffany@mycompany.com (n forwarding rules for each of n developers)

Does anyone have a system that works for them?

EDIT

I obviously missed a very important piece: we use GMail Business for all our company mail. We can add and remove users and groups, and users can create filters, but we don't have control over the MTA itself.

答:
The plus symbol has a special meaning in most email servers. While it is part of the address, it generally doesn't affect who receives the message. So dev+persona+personb@domain.com goes to dev@domain.com. This is true for Gmail for Business as well.

Gmail's filters aren't as sophisticated as those in, say, procmail, or even, as far as I can tell, Outlook. But if you get dev@domain.com set up, all the messages for those pairs will go through there. But you can write a filter that searches, for example, for to:yourname and tag it with a special label.

Because of that, and because Google limits how many rules you can have that forward email, I'd probably just start by setting dev up as an alias or a mailing list, and make sure everyone gets those emails. Advise each team member to set up a filter that looks like "to:dev to:theirname" and capture it in a way that will get their attention (Apply a label, star it or whatever works for them).

If you need something more sophisticated than what Gmail offers, such as only forwarding the relevant messages to the right developer, you'll need dev@whatever.com to be a real account. You can then use a tool like Sift, perhaps on a lightweight Amazon instance or on an underutilized machine sitting in a closet somewhere, to process the messages and forward them as needed.

Another alternative is to recognize that there are two fields of relevant information stored on each commit: the author and the committer. Author and Committer are automatically the same under typical circumstances where multiple people have commit rights. However, in workflows where one person pulls a change from someone else and commits it to the core repo, the author and committer may be different. You can force this to happen using either of two mechanisms, explained on A tour of Git:

If you specify a --author option to the “git commit” command on the
  command line, followed by a "Real Name " string,
  then this name and addresss will be used for the author fields. The
  committer fields will still be determined as below. This option is
  very helpful for when applying a commit originally authored by someone
  other than yourself.

If any of the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_COMMITTER_NAME,
  or GIT_COMMITER_EMAIL environment variables are set, then those values
  will be used for the corresponding fields

If you have a file in your home directory called .gitconfig, with name
  or email settings in the [user] section, then these values will be
  used to set any remaining author and committer fields. For more
  details on the contents of this file, refer to section 2.7.1 below.

If you have a file in the local repository called .git/config, again with
  name or email settings in the [user] section, then these values will
  be used to set any remaining author and committer fields.

If you have
  set the EMAIL environment variable, this will be used to set author
  and committer email addresses if still unset. git will query your
  system to find out your real name from available GECOS field and your
  username, hostname, and domain to construct an email address, (or at
  least an identifier resembling an email address).

In a pairing context, which one is the author and which is the committer is an arbitrary decision, but the fact is that the distinction opens the door to documenting both people involved in any particular commit.

A reasonably savvy continuous integration or build system could leverage both fields to send notifications to two separate people, which I think would work nicely for pairing situations. I don't know whether yours would, having no direct experience with it, but it is probably worth an experiment or perhaps a dive into documentation to find out.


答:
In fact, both of these solutions are bad.

Creating a services singleton (IServices) containing all the available services as interfaces. Example: Services.Current.XXXService.Retrieve(), Services.Current.YYYService.Retrieve(). That way, I don't have a huge constructor with a ton of services parameters in them.

This is essentially the Service Locator Pattern, which is an anti-pattern. If you do this, you will no longer be able to understand what the view model actually depends on without looking at its private implementation, which will make it very difficult to test or refactor.

Creating a facade for the services used by the viewModel and passing this object in the ctor of my viewmodel. But then, I'll have to create a facade for each of my complexe viewmodels, and it might be a bit much...

This isn't so much an anti-pattern but it is a code smell. Essentially you're creating a parameter object, but the point of the PO refactoring pattern is to deal with parameter sets that are used frequently and in a lot of different places, whereas this parameter would only ever be used once. As you mention, it would create a lot of code bloat for no real benefit, and wouldn't play nice with a lot of IoC containers.

In fact, both of the above strategies are overlooking the overall issue, which is that coupling is too high between view models and services. Simply hiding these dependencies in a service locator or parameter object does not actually change how many other objects the view model depends on.

Think of how you would unit-test one of these view models. How big is your setup code going to be? How many things need to be initialized in order for it to work?

A lot of people starting out with MVVM try to create view models for an entire screen, which is fundamentally the wrong approach. MVVM is all about composition, and a screen with many functions should be composed of several different view models, each of which depends on only one or a few internal models/services. If they need to communicate with each other, you do so via pub/sub (message broker, event bus, etc.)

What you actually need to do is refactor your view models so that they have fewer dependencies. Then, if you need to have an aggregate "screen", you create another view model to aggregate the smaller view models. This aggregate view model doesn't have to do very much by itself, so it in turn is also fairly easy to understand and test.

If you've done this properly, it should be obvious just from looking at the code, because you'll have short, succinct, specific, and testable view models.

Title: MVVM and service pattern

Body:
I'm building a WPF application using the MVVM pattern. Right now, my viewmodels calls the service layer to retrieve models (how is not relevant to the viewmodel) and convert them to viewmodels. I'm using constructor injection to pass the service required to the viewmodel.

It's easily testable and works well for viewmodels with few dependencies, but as soon as I try to create viewModels for complex models, I have a constructor with a LOT of services injected in it (one to retrieve each dependencies and a list of all available values to bind to an itemsSource for example). I'm wondering how to handle multiple services like that and still have a viewmodel that I can unit test easily.

I'm thinking of a few solutions:

Creating a services singleton (IServices) containing all the available services as interfaces. Example: Services.Current.XXXService.Retrieve(), Services.Current.YYYService.Retrieve(). That way, I don't have a huge constructor with a ton of services parameters in them.

Creating a facade for the services used by the viewModel and passing this object in the ctor of my viewmodel. But then, I'll have to create a facade for each of my complexe viewmodels, and it might be a bit much...

What do you think is the "right" way to implement this kind of architecture ?


答:
What I remember from my C times (far far back in the past), we used to separate functions and procedures to different files based on their responsibility. I am not claiming that is perfect or anything, but it was a good starting point for when I actually started to program in object oriented languages.
So maybe, you could start with converting files to objects.

As far as OOP goes, it is really all about practice and striving for improvement. Rarely anyone gets it right from the ground up. Thus, iterations happen throughout project's life-cycle.

Title: How to practice object oriented programming?

Body:
I've always programmed in procedural languages and currently I'm moving towards object orientation. The main problem I've faced is that I can't see a way to practice object orientation in an effective way. I'll explain my point. When I've learned PHP and C it was pretty easy to practice: it was just matter of choosing something and thinking about an algorithm for that thing.

In PHP for example, it was matter os sitting down and thinking: "well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. Combining these with PHP features, it was a good way to practice.

Now, in object orientation we have lots of additional things. It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things.

The main point is that in the way I've been learning object orientation it seems that a good design is crucial, while in procedural languages one vague idea was enough. I'm not saying that in procedural languages we can write good software without design, just that for sake of practicing it is feasible, while in object orientation it seems not feasible to go without a good design, even for practicing.

This seems to be a problem, because if each time I'm going to practice I need to figure out tons of requirements, use cases and so on, it seems to become not a good way to become better at object orientation, because this requires me to have one whole idea for an app everytime I'm going to practice.

Because of that, what's a good way to practice object orientation?


问:
Is it better to have constructors with or without parameters?
Is it better to have constructors with or without parameters and why?

```<code>public NewClass( String a,  String b, int c) throws IOException
{
    //something
}
</code>```

OR

```<code>public NewClass()
{
    //something
}
</code>```

答:
I prefer constructors with parameters and there are two main reasons:

Passing values into a constructor means that the fields can be final and therefore validated and set one time only.  Note that final fields make multi-threaded coding much simpler (see http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601).

Makes testing much easier if the values (especially objects) passed via a constructor can be mocked to behave in a desired way. Helps testing in isolation.

I don't think there is anything wrong with getter setters, but I typically only use them in a 'builder' or 'bean' class.


答:
I could write a book about this...in fact I am ;)

First off, there is no universally "right" way to do things. You have to take other factors into consideration.

It's possible that your services are too fine grained. Wrapping the Services with Facades that provide the interface that a specific Viewmodel or even a cluster of related ViewModels would use might be a better solution.

Simpler still would be to wrap the services into a single Facade that all viewmodels use. Of course that can potentially be a very big interface with a lot of unnecessary functions for the average scenario. But I would say it's no different than a message router that handles every message in your system.

In fact, what I've seen a lot of architectures eventually evolve into is a message bus built around something like the Event Aggregator pattern. Testing is easy there because your test class just registers a listener with the EA and fires the appropriate event in response. But that's an advance scenario that takes time to grow to. I say start with the unifying facade and go from there.

Title: MVVM and service pattern


答:
If you're just starting in OOP, you can amuse yourself and "practice" offline by looking at just about any real-world system and considering what the objects are and what the relation between them is and what methods/interfaces they might support and how you'd represent them in a class hierarchy and as a collection of instantiated objects and what the object ownership relations would be and so on (note: I don't mention the word "algorithms" in the above at all).  Draw lots of diagrams (learn a bit of UML or similar) before you think about coding anything.

This will help you develop a much better sense of IS-A and HAS-A relations, which is probably the single most important classification in any OOP design (and despite that, it still seems to be something which many seasoned OOP language programmers struggle with).  If you master IS-A/HAS-A there's also IS-IMPLEMENTED-IN-TERMS-OF (which I've also seen described as IS-KIND-OF-A :^)

Seriously, next trip to the supermarket, just imagine someone has given you the job of writing a OOP simulation of the place...


问:
Tell a user whether they have already viewed an item in a list. How?
It is pretty common for a web application to display a list of items and for each item in the list to indicate to the current user whether they have already viewed the associated item.

An approach that I have taken in the past is to store HasViewed objects that contain the Id of a viewed item/object and the Id of the User who has viewed that item/object.

When it comes time to display a list of items this requires querying the database for the items, and separately querying the database for the HasViewed objects, and then combining the results of these queries into a set of objects constructed solely for the purpose of displaying them in the view.

Each e.g li then uses the e.g. has_viewed property of the objects constructed above.

I think it is time to find a better approach and would like to know what approaches you would recommend.

答:
When it comes time to display a list of items this requires querying the database for the items, and separately querying the database for the HasViewed objects, and then combining the results of these queries into a set of objects constructed solely for the purpose of displaying them in the view.

What type of items are those ? Aren't those already stored in db ?

If those are not already in DB, then of course you can use @NickC solution.

If they are already coming from database, then I guess you have to fire another query to figure out which one has been read or not. It's about database-design, to cache the repeated queries.

The improvement here is to improve the database structure, because that another query can't be ignored. All that can be done, is proper indexing & caching.


问:
What is an effective git process for managing our central code library?
Quick background: we're a small web agency (3-6 developers at any one time) developing small to medium sized Symfony 1.4 sites. We've used git for a year now, but have previously used Subversion.

For the past 6 months we've put a lot of development time into a central Symfony plugin that powers our custom CMS.  This plugin includes a number of features, helpers, base classes etc. that we use to build custom functionality. This plugin is stored in git, but branches wildly as the plugin is used in various products and is pulled from/pushed to constantly.  The repository is usually used as a submodule within a major project.

The problems we're starting to see now are a large number of Merge conflicts and backwards incompatible changes brought into the repository by developers adding custom functionality in the context of their own project.

I've read Vincent Driessen's excellent git branching model and successfully used it for projects in the past, but it doesn't seem to quite apply well to our particular situation; we have a number of projects concurrently using the same core plugin while developing new features for it.

What we need is a strategy that provides the following:

A methodology for developing major features within the code repository.

A way of migrating those features into other projects.

A way of versioning the core repository, and of tracking which version each major project uses.

A plan for migrating bug fixes back to older versions.

A cleaner history that's easier to see where changes have come from.

Any suggestions or discussion would be greatly appreciated.

答:
The main mistake in this flow is creating customer branches!!! The only possible branches are new library features, not customer ones.

It's common library, so it should deliver API that COULD BE overridden by customer classes (from features requests). But this customized classes should be in client main project repository!

Your developers writes too highly coupled code. Read articles about code modularity, injections, interfaces, etc. That will reduce you pain a lot!

Second thing is proper flow for libraries. You should develop versioned libraries (e.g. 0.5, 0.7, 1.0, 1.2). Problem with library is different versions usage for different projects. Git flow doesn't support this in proper way (only last release and current development). I'm just in search for proper supporting tool for this type of flow.

Summarizing - you main pain lays in bad library code. You developers have to write code with default behaviour, free of clients behaviour and with API allowing overriding default one.


答:
Not really a problem...

I don't see a problem with User.isAdmin(). I certainly prefer it to something like PermissionManager.userHasPermission(user, permissions.ADMIN), which in the holy name of SRP makes the code less clear and does't add anything of value.

I think SRP is being interpreted a little to literally by some. I think it's fine, even preferable for a class to have a rich interface. SRP just means that an object must delegate to collaborators anything that doesn't fall within it's single responsibility. If the admin role of a user is something more involved than a boolean field, it might very well make good sense for the user object to delegate to a PermissionsManager. But that doesn't mean that it isn't also a good idea for a user to keep it's isAdmin method. In fact it means that when your application graduates from simple to complex, you want have to change the code that uses the User object. IOW, your client doesn't need to know what it really takes to answer the question of whether or not a user is an admin.

... but why do you really want to know?

That said, It seems to me like you rarely need to know if a User is an admin except to be able to answer some other question, like whether or not a user is allowed to perform some specific action, say like updating a Widget. If that is the case, I would prefer to have a method on Widget, like isUpdatableBy(User user):

```<code>boolean isUpdatableBy(User user) {
    return user.isAdmin();
}
</code>```

That way a Widget is responsible for knowing what criteria must be satisfied for it to be updated by a user, and a user is responsible for knowing if it is an admin. This design communicates clearly about its intentions and makes it easier to graduate to more complex business logic if and when that time comes.

[Edit]

The problem with not having User.isAdmin() and using PermissionManager.userHasPermission(...)

I thought I would add to my answer to explain why I greatly prefer calling a method on the User object to calling a method on a PermissionManager object if I want to know if a user is an admin (or has an admin role).

I think it's fair to assume that you are always going to depend on the User class wherever you need to ask the question is this user an admin? That's a dependency you cannot get rid of. But if you need to pass the user to a different object to ask a question about it, that creates a new dependency on that object on top of the one you already have on the User. If the question gets asked a lot, that's a lot places where you create an extra dependency, and it's a lot of places you may have to change if either of dependency demand it.

Compare this with moving the dependency into the User class. Now, suddenly you have a system where client code (code that needs to ask the question is this user an admin) is not coupled to the implementation of how this question get answered. You are free to change the permission system completely, and you only have to update one method in one class to do it. All the client code remains the same.

Insisting on not having an isAdmin method on the User for fear of creating a dependency in the User class on the permissions subsystem, is to my mind akin to spending a dollar to earn a dime. Sure, you avoid one dependency in the User class, but at the cost of creating one in every place where you need to ask the question. Not a good bargain.

Body:
Not really a problem...

I don't see a problem with User.isAdmin(). I certainly prefer it to something like PermissionManager.userHasPermission(user, permissions.ADMIN), which in the holy name of SRP makes the code less clear and does't add anything of value.

I think SRP is being interpreted a little to literally by some. I think it's fine, even preferable for a class to have a rich interface. SRP just means that an object must delegate to collaborators anything that doesn't fall within it's single responsibility. If the admin role of a user is something more involved than a boolean field, it might very well make good sense for the user object to delegate to a PermissionsManager. But that doesn't mean that it isn't also a good idea for a user to keep it's isAdmin method. In fact it means that when your application graduates from simple to complex, you want have to change the code that uses the User object. IOW, your client doesn't need to know what it really takes to answer the question of whether or not a user is an admin.

... but why do you really want to know?

That said, It seems to me like you rarely need to know if a User is an admin except to be able to answer some other question, like whether or not a user is allowed to perform some specific action, say like updating a Widget. If that is the case, I would prefer to have a method on Widget, like isUpdatableBy(User user):

boolean isUpdatableBy(User user) {
    return user.isAdmin();
}

That way a Widget is responsible for knowing what criteria must be satisfied for it to be updated by a user, and a user is responsible for knowing if it is an admin. This design communicates clearly about its intentions and makes it easier to graduate to more complex business logic if and when that time comes.

[Edit]

The problem with not having User.isAdmin() and using PermissionManager.userHasPermission(...)

I thought I would add to my answer to explain why I greatly prefer calling a method on the User object to calling a method on a PermissionManager object if I want to know if a user is an admin (or has an admin role).

I think it's fair to assume that you are always going to depend on the User class wherever you need to ask the question is this user an admin? That's a dependency you cannot get rid of. But if you need to pass the user to a different object to ask a question about it, that creates a new dependency on that object on top of the one you already have on the User. If the question gets asked a lot, that's a lot places where you create an extra dependency, and it's a lot of places you may have to change if either of dependency demand it.

Compare this with moving the dependency into the User class. Now, suddenly you have a system where client code (code that needs to ask the question is this user an admin) is not coupled to the implementation of how this question get answered. You are free to change the permission system completely, and you only have to update one method in one class to do it. All the client code remains the same.

Insisting on not having an isAdmin method on the User for fear of creating a dependency in the User class on the permissions subsystem, is to my mind akin to spending a dollar to earn a dime. Sure, you avoid one dependency in the User class, but at the cost of creating one in every place where you need to ask the question. Not a good bargain.


答:
Object.isX() is used to represent a clear relationship between the object and X, that can be expressed as a boolean result,  for example:

Water.isBoiling()

Circuit.isOpen()

User.isAdmin() assumes a single meaning of 'Administrator' within every context of the system, that a user is, in every part of the system, an administrator.

While it sounds simple enough, a real world program will almost never fit this model, there will most certainly be a requirement for a user to administer [X] resource but not [Y], or for more distinct types of administrators (a [project] administrator vs a [system] administrator).

This situation usually requires an investigation of the requirements.  Rarely, if ever, will a client want the relationship that User.isAdmin() actually represents, so I would hesitate to implement any such solution without clarification.


问:
Should my colleagues review each others code from source control system?
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.

答: Your colleague sounds like a diligent developer, you should follow his example.</p>

ContentLicense: CC BY-SA 2.5


答:
This discussion reminded me of a Blog Post by Eric Lippert, which was brought to my attention in a similar discussion about class design, security and correctness.

Why Are So Many Of The Framework Classes Sealed?

In particular, Eric raises the point:

Secure. the whole point of polymorphism is that you can pass around objects that look like Animals but are in fact Giraffes.  There are potential security issues here.

Every time you implement a method which takes an instance of an unsealed type, you MUST write that method to be robust in the face of potentially hostile instances of that type.  You cannot rely upon any invariants which you know to be true of YOUR implementations, because some hostile web page might subclass your implementation, override the virtual methods to do stuff that messes up your logic, and passes it in.  Every time I seal a class, I can write methods that use that class with the confidence that I know what that class does.

This may seem like a tangent, but I think it dovetails with the point other posters have raised about the SOLID single-responsibility principle. Consider the following malicious class as a reason not to implement a User.IsAdmin method or property.

```<code>public class MyUser : User
{

    public new boolean IsAdmin()
    {
        // You know it!
        return true;
    }

    // Anything else we can break today?

}
</code>```

Granted, it's a bit of a stretch: no one yet suggested making IsAmdmin a virtual method, but it could happen if your user/role architecture ended up being bizarrely complex. (Or perhaps not. Consider public class Admin : User { ... }: such a class might have exactly that code above in it.) Getting a malicious binary into place is not a common attack vector and has a lot more potential for chaos than an obscure user library - then again, this could be the Privilege Escalation bug that opens the door to the real shenanigans. Finally, if a malicious binary or object instance did find its way into the run time, it's not much more of a stretch to imagine the "Privilege or Security System" being replaced in a similar manner.

But taking Eric's point to heart, if you put your user code in a particular type of vulnerable system, maybe you did just lose the game.

Oh, and just to be precise for the record, I agree with the postulate in the question: “A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should.” A User.IsAdmin method is a bad idea if you are running the code on system you do not remain in 100% control of the code - you should instead do Permissions.IsAdmin(User user).

Body:
This discussion reminded me of a Blog Post by Eric Lippert, which was brought to my attention in a similar discussion about class design, security and correctness.

Why Are So Many Of The Framework Classes Sealed?

In particular, Eric raises the point:

Secure. the whole point of polymorphism is that you can pass around objects that look like Animals but are in fact Giraffes.  There are potential security issues here.

Every time you implement a method which takes an instance of an unsealed type, you MUST write that method to be robust in the face of potentially hostile instances of that type.  You cannot rely upon any invariants which you know to be true of YOUR implementations, because some hostile web page might subclass your implementation, override the virtual methods to do stuff that messes up your logic, and passes it in.  Every time I seal a class, I can write methods that use that class with the confidence that I know what that class does.

This may seem like a tangent, but I think it dovetails with the point other posters have raised about the SOLID single-responsibility principle. Consider the following malicious class as a reason not to implement a User.IsAdmin method or property.

public class MyUser : User
{

    public new boolean IsAdmin()
    {
        // You know it!
        return true;
    }

    // Anything else we can break today?

}

Granted, it's a bit of a stretch: no one yet suggested making IsAmdmin a virtual method, but it could happen if your user/role architecture ended up being bizarrely complex. (Or perhaps not. Consider public class Admin : User { ... }: such a class might have exactly that code above in it.) Getting a malicious binary into place is not a common attack vector and has a lot more potential for chaos than an obscure user library - then again, this could be the Privilege Escalation bug that opens the door to the real shenanigans. Finally, if a malicious binary or object instance did find its way into the run time, it's not much more of a stretch to imagine the "Privilege or Security System" being replaced in a similar manner.

But taking Eric's point to heart, if you put your user code in a particular type of vulnerable system, maybe you did just lose the game.

Oh, and just to be precise for the record, I agree with the postulate in the question: “A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should.” A User.IsAdmin method is a bad idea if you are running the code on system you do not remain in 100% control of the code - you should instead do Permissions.IsAdmin(User user).

ContentLicense: CC BY-SA 4.0


问:
Is 500 million lines of code even remotely possible?
The New York Times is reporting that the Healthcare.gov website contains "about 500 million lines of software code." This number, attributed to "one specialist", and widely repeated across the interwebs, seems incredibly far-fetched (even assuming a large fraction of that number includes standard libraries). If this is an accurate estimate, it would truly be staggering (as this fascinating infographic vividly reveals). I realize StackExchange:Programmers isn't Snopes.com, but I'd like to find out if anyone here believes this is even remotely possible. I'd like to know if there is a plausible system of accounting (using examples from publicly available data, if possible) that could lead someone to conclude that such an estimate is within the realm of reason. How could a codebase (by any measure) sum up to such an exhorbitant number of code lines?</p>

答:
I'm inclined to believe it.  For a very generous definition of "the Healthcare.gov website."

The software I work on has almost 1.1 million lines checked in in trunk (according to subversion's stats), and that's with just 4 in-house developers.  The largest single chunk of that (about a quarter of a million lines) is simply auto-generated code from including a reference to Ebay's web service.  Add another 150k for the various other autogenerated webservices together.

Our database is relatively small, and despite my best efforts, the large majority of it is still using DBF tables.  The portion of it that's using EntityFramework is another 11k lines.  The web database's Linq2Sql project weighs in at 28k.  The sum total of all the javascript is somewhere around 46k (including both minified and unminified versions in that total).

Again, this is 4 developers over something like 10 years (although it only really started exploding a few years ago).  It doesn't include much in the way of unit tests, database scripting (we prefer code), redundancy, or really fancy HTML5 graphical effects.

Add 3-5 subcontractors, each with their own external references, included 3rd party libraries, and 10-50 times the developers we have, and include all the database scripting we avoid, and and so on, and I can easily see it getting that big.  Especially if you start including documentation and/or heavily commenting the code.  I interviewed for an FAA contractor once where they told me that their comment-to-code ratio was ideally 1:1.


问:
What is the best approach for deploying apps to companies
What is the best approach for the following scenario:

1) A publicly available app (available in app stores) which is used by end users to make use of services offered by multiple companies.

2) These companies maintain their services also using a mobile app.

I'm not sure on how to solve the second part. Having one app for both enduser and admin functionality, secured by username/password doesn't sound like a good idea. This would leave the only option of developing a separate admin application for the companies.

What is the best approach to deploy "admin" like mobile apps to companies only, for Android, iOS and Windows Phone?

Some additional information:

Public App ----> Servers -----> Multiple Company Apps

The public app shows all companies offering their services. An end user uses the public app to order something from a specific company. The order is sent to our servers. Our servers send the order to the associated company. This order is displayed on the company's admin app and given the option to accept the order.

答:
Given that there are some many thousands (maybe millions) of mobile applications for everything including store locators for every StarBucks coffee house ... the recommendation is to move away from specific mobile applications.

That is, the best-practice I have seen for efficiency and use is to have web-applications versus downloadable mobile/PC installs.

All smart phones have web-browsers.
Using the user-agent header and other information, automatically (or offer) differentiate the full-screen application from one with a different layout for tablets (CSS has "media queries" that do a good job of this without changing content) and a 'reduced functionality' mobile application (also leveraging CSS media queries for a layout that works well for small mobile screens).

Traditionally 'full' consumer/PC applications versus more specialized use-cases for mobile phones may include similar components but the latter usually less with a simpler navigation and more focused features where people will actually use a phone.

For example, most people will not fool with trying to place a complicated commercial order for a retain store chain on a phone. However, they might use it to check order status or shipping confirmation.

So in summary - avoid client/server architectures that require distribution of applications to different devices and stay with a centrally managed structure, differentiating the client (user-agent) accessing the application, serving up style and content that is appropriate for that device.

As for the admin versus buyer use-cases, these may be different components of the web-application, with more security for the admin side (two-factor authentication is strongly recommended commensurate with the risk of the admin application having access to many buyer organization's information).


答:
The problem here is:

```<code>if (user.isAdmin()) {
   doPriviledgedOp();
} else {
   // maybe we can anyway!
   doPriviledgedOp();
}
</code>```

Either you have set up your security properly in which case the privileged method should check if the caller has sufficient authority -- in which case the check is superfluous. Or you have not and are trusting an un-priviledged class to make its own decisions on security.

Body:
The problem here is:

if (user.isAdmin()) {
   doPriviledgedOp();
} else {
   // maybe we can anyway!
   doPriviledgedOp();
}

Either you have set up your security properly in which case the privileged method should check if the caller has sufficient authority -- in which case the check is superfluous. Or you have not and are trusting an un-priviledged class to make its own decisions on security.


问:
Found a better solution to a problem at work - should I deter from posting the code snippet online?
I think most of us, programmers, used Stack Overflow to solve every day problems: looked for an efficient algorithm to do something.

Now imagine a situation: you have a problem to solve. Googled a bit, found a StackOverflow question but you are not really satisfied with the answers so far. So you have to do your own research: you need to do it because you want it in the company's app.

Eventually after some hours you have found the better solution. You're happy, you added it to the company's code base, then you want to submit your answer with a code snippet (just several lines) to the question you've found before to help others too.

But wait: the company's software is closed source, and you worked on it on the clock.

So does this mean I shouldn't post the answer neither at work nor at home to that question in the rest of my life, because I solved it at work, and the company owns that piece of code?

答:
How much would it cost your company for your additional time or lost time if you didn't have this resource?

As long as no compromising or proprietary info is given I feel that the posting solutions that you have found is compensation for answers that you have received.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
Im surprised that no one has mentioned the performance optimization benefits. Depending on the language a compiler can make a bunch of optimizations when dealing with immutable data because it knows the data will never change. All sorts of stuff is skipped over, which gives you tremendous performance benefits.

Also immutable objects almost eliminate the entire class of state bugs.

Its not as big as it should be because its harder, doesn't apply to every language and most people were taught imperative coding.

Also i have found that most programmers are happy in their box and are often resistant to new ideas that they don't completely understand. In general people dont like change.

Also remember, that the state of most programmers is bad. Most programming that is done in the wild is terrible and its caused by a lack of understanding and politics.


问:
what would be the best data structure for my situation
I have a list of unique string. I don't want to destroy this string i need it.I only need to find out weather an given string S exist in this unique list.What would be the best data structure for this purpose.

答:
Depends upon how many unique strings you have.  There are at least three ways to store your strings.

List (Vector/Array) - keep either a sorted, or unsorted list of strings.  You can then scan the list to find whether the string already exists.  Adding a new string is either an append or an insert (depending upon whether you keep the list sorted).

Hash (Map/Associative Array) - You store the strings as keys into a hash/map, and you can count the occurences of each string as the values contained in the hash heys.

Trie - An N-ary tree structure where each node of the tree has a list/array of children, where each child is indexed by a character-substring differing from all other children.  Leaves represent the terminal words (unique strings).  The tree has depth at most equal to the length of the longest string.

Also, a simple hybrid of Hash and lists used in symbol tables (a long time ago), would hash(first character, last character) to smaller lists of strings.  Provides reasonably quick access, a small number of compares on the list, and fairly easy to implement (a technique used in symbol tables a long time ago).

Another possibility: If you have a smaller number of strings to encode, a small possibility of false positives is not a concern, and you don't care to keep the string around, read about bloom filters.


答:
The answer lies in the written legal agreements you signed with your employer (your contract) and with the jurisdiction under which those agreements will be judged.  It is common for a legal agreement to list the jurisdiction which may or may not be the state you work in (though probably the country you work in, but not necessarily).

A great book is Intellectual Property and Open Source by Van Lindberg.  From p. 185:

There are no legal repercussions for [a company] overreaching when defining
  "proprietary information."  Several states limit the application of
  PIAs when an author or inventor doesn't use company property or time
  to create the new work... Even if state-imposed limits invalidate part
  of the PIA, other aspects of the agreement generally survive.

Read your contract.  Disclose your intentions to your employer before you act.  Then disclose your actions to your employer.  Disclose these things in writing and get their response/permission when applicable in writing.  At least that's what that book says.

I am not a lawyer, just interested in this stuff.  This is not legal advice, just friendly suggestions.  For myself, I don't casually make anything work-related public.  I have made some things public after lengthy discussions with my boss, full disclosure, clear license labeling, and an agreement in writing about what I'm releasing, but that is rare.

Title: Found a better solution to a problem at work - should I deter from posting the code snippet online?

Body:
I think most of us, programmers, used Stack Overflow to solve every day problems: looked for an efficient algorithm to do something.

Now imagine a situation: you have a problem to solve. Googled a bit, found a StackOverflow question but you are not really satisfied with the answers so far. So you have to do your own research: you need to do it because you want it in the company's app.

Eventually after some hours you have found the better solution. You're happy, you added it to the company's code base, then you want to submit your answer with a code snippet (just several lines) to the question you've found before to help others too.

But wait: the company's software is closed source, and you worked on it on the clock.

So does this mean I shouldn't post the answer neither at work nor at home to that question in the rest of my life, because I solved it at work, and the company owns that piece of code?


问:
Console keyboard input OOP
I am trying to build a very simple console-based game with a focus on using OOP instead of procedural programming because I intend to build up on that code for more complex projects.

I am wondering if there is a design pattern that nicely handles this use case:

There is a Player class with a MakeMove() method interacting with the board game.

The MakeMove() method has to somehow get the user input yet I do not want to code it into the Player class as this would reduce cohesion and augment coupling.

I was thinking of maybe having some controller class handle the sequence of events and thus the calls to keyboard input. However, that controller class would need to be able to handle differently the subclasses of Player (e.g. the AI class does not require keyboard input).

Thoughts ?

答:
For web-UI work I'm fond of compositing the user-input/HTML-DOM interaction stuff as an easily decoupled component of a given object. Usually by taking all the .click and .focus and blur stuff for say a combo box and having it trigger the combo box object's revealOptions or selectOption methods or what have you. That way I can trigger actions/listen to events on the object with a nice details-independent and easily understood by non-UI web devs API while still having all of that object bundled into the same easily ported space.

Essentially, your Player would have an internal object that could be easily swapped out and whose job it is to communicate to the environment and likewise for giving the player ways to respond to tweaks in the environment in a generic way. In web-ui JS that interal object would listen to browser events and then trigger methods of the outer object's API we're fussing about internally. Then it would listen to generic outer object's events and handle all the HTML transformation junk the guy manipulating the player object doesn't want to fuss with just to move a checker or something.

It's basically two sets of APIs and listeners used to decouple but it's all plugged into the same thing. If you want to override for a new environment you could just make that internal object something that can be replaced when you hand off a different one in the constructor or class or whatever...

Title: Console keyboard input OOP


问:
Cleaning a dataset of song data - what sort of problem is this?
I have a set of data about songs. Each entry is a line of text which includes the artist name, song title, and some extra text. Some entries are only "extra text". My goal is to resolve as many entries as possible to songs on Spotify using their web API.

My strategy so far has been to search for the entry via the API - if there are no results, apply a transformation such as "remove all text between ( )" and search again. I have a list of heuristics and I've had reasonable success with this but as the code gets more and more convoluted I keep thinking there must be a more generic and consistent way. I don't know where to look - any suggestions for what to try, topics to study, buzzwords to google?

答: I'm not sure what language you are using, but I would create a some objects/functions that can perform the transformation of the song data. I would pass these objects/functions to a transformation consumer. The consumer takes the lyrics,artists,etc. and loops over the transformation functions, each time passing in the lyrics,artist,etc., and then querying the api for a match with the transformed data. If their is a match then your done, otherwise the next transformation occurs and the next query occurs. Keep it modular.</p>


问:
Best way to choose random element from weighted list
I want to create a simple game. Every so often, a power up should appear. Right now the different kinds of power ups are stored in an array.

However, not every power up should appear equally often: For instance, a score multiplier should appear much more often than an extra life.

What is the best/fastest way to pick an element at random from a list where some of the elements should be picked more often than others?

答:
If the weight is a percent of times the item should be selected (say 1-100), what about going through the list and assigning each item a 'check' equal to the sum of its weight plus the previous weights.  Then take a random number between 1-100 (i.e., a standard random number between 0 and 1, multiplied by 100, tweaked so as to be a non-zero integer), and choose the first item whose 'check' value is greater than or equal to the random value?

So, if there are three elements "A" with weight 25%, "B" with weight 50%, and "C" with weight 25%, the 'score' values are: A=25 (25+0), B=75 (50+25), C=100 (25+75).  A random number of 12 would select A (since 12 <= 25).  Any random number from 1-25 selects A.  Any random number of 26-75 selects B.  Any random number between 76-100 selects C.

Would this work?

Possibly this is the same as suggested by Aaronaught -- to be honest I wasn't sure exactly what he or she meant by

write a bunch of if statements comparing a random number to a low/high
  bound


问:
How to support a product built with agile development?
Two of the functions our company provides our customers are:

Our Development team of ~10 employees creates software products for businesses in a particular industry. The software is used on hundreds of our customers' computers. Although the product is, for most customers, off-the-shell, larger customers drive its development, so it's somewhere between shrinkwrap software and custom software.

Our Support team of ~25 employees provides technical support for both our own software and a few other software products for which we are the vendor.

Our Development team recently switched to Scrum for their development methodology, and while I support this change, I worry that our Support team is going to have more trouble in the future.  With a quicker release cycle, our customers will have features and products in production which Support isn't even aware of until the customer calls. We've never been particularly good at getting documentation and information from Development to Support, but I fear Scrum will just exacerbate the problem.

What are good references on how companies reconcile Development's desire to release frequently with Support's desire to have full documentation and support information before customers see the product?  How should a company structure their release and change management when using agile methods?

EDIT: What I'm interested are specifics on how companies structure themselves to deal with these issues. Does the scrum team push releases to customers? Does the software have to go through a release/change management team who will not deploy until Support has been given documentation and brought up to speed?  How do you get releases to customers quickly yet still keep everyone informed of changes and new features?

答:
First thing to know is that at the end of the iteration, you don't have to release. The objective is to have a potentially shippable increment of the software, not necessarily to release it. Product owner should decide when to release.

Increase Collaboration

When you decide to release, it is quite obvious that the support is being informed and/or trained with the new changes. The support should be involved in the process. They should also be informed which bug has been fixed so they can inform the customers in the support ticket.

Depending on your situation it may be a good idea to invite one or more support team member to the spring planning meeting. It's also a good idea to invite them to the sprint review meeting as well. Try it to see if it works for you.

Write a Definition of Done

Each feature your developers build should comply to a Definition of Done you write and maintain that matches your organization & product specificities. Here is an example of DoD:

Code build, committed in the repos

Unit test coverage 80%

Technical documentation completed (just enough)

End user documentation completed (just enough)

Reviewed & approved by another developer

Fully tested

What's new file updated

The concept of Definition of Done alone is a strong company anti-procrastination technique. It forces you to advance, ... to ship.

Once a feature is "done", you have everything to release it already. Including what is needed by your support team.

Support Is Useful For Developers

I personnaly love support. It's the best source of strategic information for your software. It is better than any market study. This is why I think having developers in the support helps you to build on quality. Remember the expression Throw it over the wall?

I also think the product owner should be involved.


答:
Well, your basic algorithm sounds to be like this (in C#, but that does not really matter):

```<code>bool DoFullSearch(List<Transformation> transformationList, SearchData originalData)
{
    foreach(var transformation in transformationList)
    {
        var transformedData = transformation.Apply(originalData);
        bool success=DoSingleSearch(transformedData);
        if(success)
            return true;
    }
    return false;
}
</code>```

(The first transformation in the list maybe the "noop" transformation, just returning the original data unchanged).

IMHO that's not very convoluted - it is pretty straightforward. Of course, the key here is to provide a Transformation class with several subclasses, each one for each possible transformation, each one overriding the Apply method in a different manor.

Title: Cleaning a dataset of song data - what sort of problem is this?

Body:
I have a set of data about songs. Each entry is a line of text which includes the artist name, song title, and some extra text. Some entries are only "extra text". My goal is to resolve as many entries as possible to songs on Spotify using their web API.

My strategy so far has been to search for the entry via the API - if there are no results, apply a transformation such as "remove all text between ( )" and search again. I have a list of heuristics and I've had reasonable success with this but as the code gets more and more convoluted I keep thinking there must be a more generic and consistent way. I don't know where to look - any suggestions for what to try, topics to study, buzzwords to google?

Body:
Well, your basic algorithm sounds to be like this (in C#, but that does not really matter):

bool DoFullSearch(List<Transformation> transformationList, SearchData originalData)
{
    foreach(var transformation in transformationList)
    {
        var transformedData = transformation.Apply(originalData);
        bool success=DoSingleSearch(transformedData);
        if(success)
            return true;
    }
    return false;
}

(The first transformation in the list maybe the "noop" transformation, just returning the original data unchanged).

IMHO that's not very convoluted - it is pretty straightforward. Of course, the key here is to provide a Transformation class with several subclasses, each one for each possible transformation, each one overriding the Apply method in a different manor.


问:
Improving the performance of a db import process
I have a program in Microsoft Access that processes text and also inserts data in MySQL database. This operation takes 30 mins or less to finished.

I translated it into VB.NET and it takes 2 hours to finish.

The program goes like this:

A text file contains individual swipe from a corresponding person,
it contains their id, time and date of swipe in the machine, and an
indicator if it is a time-in or a time-out.

I process this text, segregate the information and insert the time-in and time-out per row.

I also check if there are double occurrences in the database.

After checking, I simply merge the time-in and time-out of the corresponding person into one row only.

This process takes 2 hours to finished in VB.NET considering I have a table to compare which contains 600,000+ rows.

Now, I read in the internet that python is best in text processing, i already have a test but i doubt in database operation.

What do you think is the best programming language for this kind of problem?

How can I speed up the process? My first idea was using python instead of VB.NET, but since people here telling me here on PSE that this most probably won't help I am searching for different solutions.

Here is a link to the test i've done.

答:
I find it very unlikely that changing the programming language will bring you any further. So apply the topmost rule of performance optimization:

Find the bottleneck by measuring the running time for the individual steps!.

It may be either the text processing, the DB operations or both. You did not show us any code, but in situations like this the DB operations would be the first suspect to me.

For example, you may consider to comment the DB operations out, leave only the text processing active and then measure and compare the running times.


问:
What's the reason exceptions are heavily used in managed (C# and Java) languages but not in C++?
AFAIK, a lot of C++ projects don't allow exceptions and deny them in coding guidelines. I have a lot of reasons, for example, exception is hard to handle correctly if your binary needs to be compiled by separate and different compilers.

But it doesn't fully convince me, there is a lot of projects which are just using one compiler. Compared to C++, exceptions are heavily used in C# and Java and the reason can only be that exception are not bringing enough benefit.

One point is debugbility in practice. Exception can not get the call stack in C++ code, but in C# and Java you can get the call stack from exception, it is significant and makes debugging easier. No-callstack is not the fault of the exception, it is the language difference, but it impacts the exception usage.

So what's the reason that exceptions are frowned upon in c++ programs?

答:
a lot of C++ projects don't allow exceptions and deny them in coding guidelines

I would say ignorance. They do not understand what exception means, and they even measure how long it takes to unwind the stack.

Exception are not bringing enough benefit.

The alternative to exceptions is kind of spaghetti code, and greatly increased complexity. Which directly translates to time/effort/money.

For example, what do you do if an object's construction fails?

By only adding exceptions to a c program (and nothing else from c++), the complexity would be greatly reduced.

Exception can not get the call stack in C++ code

It is possible to get the backtrace, and this answer shows how to do it.


问:
Is spreading code with refactoring comments a good idea?
I am working on a "spaghetti-code" project, and while I am fixing bugs and implementing new features, I also do some refactoring in order to make the code unit-testable.

The code is often so tightly coupled or complicated that fixing a small bug would result in a lot of classes being rewritten. So I decided to draw a line somewhere in the code where I stop refactoring. To make this clear, I drop some comments in the code explaining the situation, like:

```<code>class RefactoredClass {
    private SingletonClass xyz;

    // I know SingletonClass is a Singleton, so I would not need to pass it here.
    // However, I would like to get rid of it in the future, so it is passed as a
    // parameter here to make this change easier later.
    public RefactoredClass(SingletonClass xyz) {
        this.xyz = xyz;
    }
}
</code>```

Or, another piece of cake:

```<code>// This might be a good candidate to be refactored. The structure is like:
// Version String
//    |
//    +--> ...
//    |
//    +--> ...
//          |
//    ... and so on ...
//
Map map = new HashMap<String, Map<String, Map<String, List<String>>>>();
</code>```

Is this a good idea? What should I keep in mind when doing so?

答:
Is spreading code with refactoring comments a good idea?

If you have allocated time to finish your refactoring, and if you really do it, then yes - it will work out.

What should I keep in mind when doing so?

Modern IDEs have an option to find and show TODO lines. You should check them from time to time, and try to reduce their numbers whenever you can.