问:
Role-based REST API?
I'm building a REST API for which several users with different roles will have access to the resources it contains.

To keep the scope simple let's take the "student/teacher/class" domain:

GET /students is the resource to access.

Users might have roles like Student and/or Teacher

Students will only have access to students of their classes. Teachers will have access to students of the classes they teach. Some uses may be a student AND teach other classes too. They must have access to the students of their classes AND the students of the classes they teach.

Ideally I want to implement this as two functions - one per role and then "union" if a user have multiple roles.

My question is: Which pattern should I use for implementing this?

Externally

Should I split up my API per role? GET /teacher/students and GET /student/students It doesn't seems right to me.

Keep it all I'm one resource (preferred)

Internally

How should it be implemented internally?

Should every method start with a BIG switch/if per role?

Should I implement a repository per role?

Is there a design pattern that will help me in achieving this?

As a side comment: I'm using ASP.NET Web API and Entity Framework 6, but it really doesn't matter for the conceptual implementation.

答:
You should architect the API around resources, not around roles, e.g.:

```<code>/rest/students
</code>```

should be accessible to anyone with a role that allows them to see students.

Internally, you are implementing role-based security. How you go about that depends on the details of your application, but let's say you have a role table, each person has one or more roles, and those roles determine what each person can access. You have already stated the rules for accessing students:

students can access students in the classes they take

teachers can access students in the the classes they teach

So when a person calls:

```<code>/rest/students
</code>```

you call a method that accesses students, passing in the role of the person. Here is some pseudo code:

```<code>roles = person.roles; //array
students = getStudents( roles );
return students;
</code>```

and in that method, you could get the students for each role with separate calls, e.g.:

```<code>factory = getFactory();
classes= [];
students = [];
for( role in roles ){
    service = factory.getService( role );
    // implementation details of how you get classes for student/teacher are hidden in the service
    classes = classes.merge( service.getClasses( person ) );
    // classes[] has class.students[]
    // loop on classes and add each student to students, or send back classes with nested students? depends on use case
  }
}
</code>```

That's a very rough idea for what you could do and isn't necessarily going to fit your specific needs, but it should give you a sense of the pieces involved. If you want to return the classes with each student listed, this is a good approach. If you just want the students, you could extract them from each class and merge them into a collection of students.

No, you should not have a separate repository per role. All the role does is determine how you get the data, and maybe what you can do with the data (e.g. Teachers can enter Student grades). The data itself is the same.

As for patterns, this approach is using Factory Pattern to abstract away the service that gets data based on role. It may or may not be appropriate to have separate services by role. I like this approach because it minimizes the amount of code at each stage of the program and makes it more readable than a switch or if block.

Title: Role-based REST API?

Body:
You should architect the API around resources, not around roles, e.g.:

/rest/students

should be accessible to anyone with a role that allows them to see students.

Internally, you are implementing role-based security. How you go about that depends on the details of your application, but let's say you have a role table, each person has one or more roles, and those roles determine what each person can access. You have already stated the rules for accessing students:

students can access students in the classes they take

teachers can access students in the the classes they teach

So when a person calls:

/rest/students

you call a method that accesses students, passing in the role of the person. Here is some pseudo code:

roles = person.roles; //array
students = getStudents( roles );
return students;

and in that method, you could get the students for each role with separate calls, e.g.:

factory = getFactory();
classes= [];
students = [];
for( role in roles ){
    service = factory.getService( role );
    // implementation details of how you get classes for student/teacher are hidden in the service
    classes = classes.merge( service.getClasses( person ) );
    // classes[] has class.students[]
    // loop on classes and add each student to students, or send back classes with nested students? depends on use case
  }
}

That's a very rough idea for what you could do and isn't necessarily going to fit your specific needs, but it should give you a sense of the pieces involved. If you want to return the classes with each student listed, this is a good approach. If you just want the students, you could extract them from each class and merge them into a collection of students.

No, you should not have a separate repository per role. All the role does is determine how you get the data, and maybe what you can do with the data (e.g. Teachers can enter Student grades). The data itself is the same.

As for patterns, this approach is using Factory Pattern to abstract away the service that gets data based on role. It may or may not be appropriate to have separate services by role. I like this approach because it minimizes the amount of code at each stage of the program and makes it more readable than a switch or if block.


问:
Groups relationships - Detailed or Direct?

Current design

I have a Person model:

```<code>PersonId    Name
----------- ----------------
1           Jessica
2           Jennifer
</code>```

Then I have a ShareModel which have the Personand an Itemassociated.

```<code>ShareId     ItemId
----------- ----------------
1           1
2           2
</code>```

And finally I have a SharePeoplewhich tells all people that have access to that Item.

```<code>ShareId     PersonId
----------- ----------------
1           1
1           2
</code>```

New feature

Now a new feature must be added, which is Groups. So I thought about two aproaches and I would like to know which one is the more correct.

There are two things I see clearly:

add a new IsGroup property to the Person Model.

```<code>PersonId    Name             IsGroup
----------- ---------------- -----------
1           Jessica          False
2           Jennifer         False
3           Blondes          True
</code>```

create a GroupPeople table

```<code>GroupPersonId    ChildPersonId
-------------    ----------------
3                1
3                2
</code>```

The questions

OPTION 1 : Should I create the association on the SharePeople with the IsGroup rows directly:

```<code>ShareId     PersonId
----------- ----------------
2           3
</code>```

OPTION 2 : should I create the association always with the persons which are part of the group, and have another column on that will identify from which Group the association was made.

```<code>ShareId     PersonId            GroupPersonId
----------- ----------------    -------------
2           1                   3
2           2                   3
</code>```

The second option is more simple when getting data from tables, it will be fast and will create less impact, however it creates a lot of rows on the database.

The first option is cleaner but I will have to do a lot of logical statements inside my code wheter the row it's a Group or a single Person.

But bottom line is that I really don't know what's better concerning performance, and I also don't whant to do tons of odd code.

Thank you very much,

答:
For Option 1, you appear to be missing the data about which people are in each group, and now every query on the Person table has to know about these fake "group people", even ones that don't care about sharing or groups.

Option 2, by tying the person->group mapping to the share->person mapping (which really have nothing to do with each other), is effectively making the assumption that each person is part of at most one group. That's probably not a safe assumption.

Somewhere, there needs to be a table mapping peopleIds to groupIds, so you know who is in each group. Since this is probably a many-to-many relationship (a group can have N people, and a person can be in N groups), this should be a completely separate Groups table, not part of the Person or the Share tables.

This does mean your sharing/grouping queries will have more joins, but joins aren't hard, and a correct query that understandings grouping is many-to-many is much better than a simple but wrong query. Don't worry about performance until you have a measurable problem, and even then you should focus on standard database optimization features like indexes and replication (which are far more likely to improve performance than butchering your schema design).

ContentLicense: CC BY-SA 3.0


答:
Don't add isgroup to your person table. Make a group table as its own entity.

Role-based security model: person, role, group, roleonGroup, roleonUser, permission, itemPermission, itemPermissiononRole

or

person, role, group, roleonEntity, permission, itemPermission, itemPermissiononRole

where 'entity' can be a person or group. I prefer the former even though it requires more code.

I am suggesting itemPersmission instead of Share because you can have more than one permission on an item, e.g. create item, read item, write item, delete item, which can then be assigned by role.

You can adapt the names to your model, but the idea is that Share is a permission and does not need its own entity.

If this sounds like overkill for your needs, just consider what would happen if your requirements changed and in addition to Share, you had Modify. Very quickly your schema and code would get out of hand.

Title: Groups relationships - Detailed or Direct?

Body:
Current design

I have a Person model:

```<code>PersonId    Name
----------- ----------------
1           Jessica
2           Jennifer
</code>```

Then I have a ShareModel which have the Personand an Itemassociated.

```<code>ShareId     ItemId
----------- ----------------
1           1
2           2
</code>```

And finally I have a SharePeoplewhich tells all people that have access to that Item.

```<code>ShareId     PersonId
----------- ----------------
1           1
1           2
</code>```

New feature

Now a new feature must be added, which is Groups. So I thought about two aproaches and I would like to know which one is the more correct.

There are two things I see clearly:

add a new IsGroup property to the Person Model.

```<code>PersonId    Name             IsGroup
----------- ---------------- -----------
1           Jessica          False
2           Jennifer         False
3           Blondes          True
</code>```

create a GroupPeople table

```<code>GroupPersonId    ChildPersonId
-------------    ----------------
3                1
3                2
</code>```

The questions

OPTION 1 : Should I create the association on the SharePeople with the IsGroup rows directly:

```<code>ShareId     PersonId
----------- ----------------
2           3
</code>```

OPTION 2 : should I create the association always with the persons which are part of the group, and have another column on that will identify from which Group the association was made.

```<code>ShareId     PersonId            GroupPersonId
----------- ----------------    -------------
2           1                   3
2           2                   3
</code>```

The second option is more simple when getting data from tables, it will be fast and will create less impact, however it creates a lot of rows on the database.

The first option is cleaner but I will have to do a lot of logical statements inside my code wheter the row it's a Group or a single Person.

But bottom line is that I really don't know what's better concerning performance, and I also don't whant to do tons of odd code.

Thank you very much,


问:
Forming heavy use case diagram
We have a use case diagram for our software engineering course project that we have many use cases in every system and about 5-6 actors. How should we separate this heavy diagram to light weight diagrams? What is standard way to do it?

Should we separating per actor or per system?

By per actor I mean: e.g. for a management system that has two actors we open a diagram with that system and just show actor #1. After that we open other diagram put the same system in it but show just other actor (actor #2).

答:
The scope of a use case diagram is typically per-system. One of the symbols used on a diagram is called the "system boundary box". This is simply a box drawn around use cases and labeled with the system name. If further detail is needed, the same notation can be used to provide subsystems within a system by drawing a box around the use cases that are part of a subsystem and labeling that with the subsystem name. However, some methods have extended the use of a system boundary box to denote releases (usually in incremental processes) where all of the indicated use cases are part of a single system and each box would indicate the intended release for each use case.

Something else to consider is that I've rarely seen use case diagrams used outside of academic settings. Even Martin Fowler in UML Distilled describes the diagram type, but prefers textual notations. Textual descriptions provide much more detail that would be useful in more detailed design and implementation activities.

Title: Forming heavy use case diagram


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
I don't put a hard line limit on anything because some functions implement algorithms that are inherently complex and any attempt to make them shorter would make the interactions between the new, shorter functions so complicated that the net result would be no reduction in simplicity.  I also don't believe that the idea that a function should only do "one thing" is a good guide, since "one thing" at a high level of abstraction can be "many things" at a lower level.

To me, a function is definitely too long if its length causes subtle violations of DRY right now, and extracting part of the function into a new function or class could solve this.  A function may be too long if this isn't the case, but a function or class could easily be extracted that would make the code more modular in a way that is likely to be useful in the face of foreseeable change down the road.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
Alistair Cockburn (The Use Case Guru) recommends to separate by different concerns called "design scopes" and "goal levels" as shown in Stack Overflow: UML Use case: Waiting for another use case to finish.

See also

Wikipedia: Use case for introductory signposts

book Cockburn, Alistair. Writing Effective Use Cases. Addison-Wesley, 2001 (draft version #3 is available online)

Title: Forming heavy use case diagram

Body:
We have a use case diagram for our software engineering course project that we have many use cases in every system and about 5-6 actors. How should we separate this heavy diagram to light weight diagrams? What is standard way to do it?

Should we separating per actor or per system?

By per actor I mean: e.g. for a management system that has two actors we open a diagram with that system and just show actor #1. After that we open other diagram put the same system in it but show just other actor (actor #2).


问:
What is the correct project file structure for a versioned rest api?
Should I have resource directories inside version directory, like

```<code>app/
  v1/
   book/
   author/
  v2/
   author/
</code>```

or version directories inside resource folder

```<code>app/
  book/
    v1/
  author/
    v1/
    v2/
</code>```

which one would be easier to maintain and which is commonly used today?

答:
I hope you are not confusing the URL pattern, with the file system.

The URL pattern is something flexible and where (and how) your source code is written or structured is completely different.

You should not confuse the two.

As for the convention, it is common to use the version handler before the resource (or collection) name: http://www.example.com/api/v1/books/ for example. This is best practice as demonstrated by most public REST apis. You can also choose to version your API differently; for example api/2014-01/books/ or api/1.0.1/books etc.

The notable exception is facebook which has the version as an optional parameter to the URL, ?v=1.

You should keep the version number as most to the left of the URI as possible, as this gives it the highest scope.

In any case, you should always properly document your API versions and if there is a backwards-incompatible change, document that and give your developers a chance to migrate.


答:
Most common way: I think it is "version first, resources inside". At least I've seen it in APIs of different social networks. And I've never actually seen the other way.

It is the only logical way of two: there are resources inside (different versions of) your API, not APIs inside resources. It is easier to drop older versions that way: just respond with 404 on all subresources' requests, providing a message like "This version of API is no longer exists" - that makes it clear that it is not just a typo in URL. For that reason, I think it is also much easier to maintain, at least in frameworks I've used: I'd just add another rule in my router, which matches all the older versions, and responds properly.

So, in my experience, first version (version first, resources inside) is the only one I've seen being used, and is much easier to maintain.

Header-based versioning (e.g. Accept: application/vnd.service.v2+json) is very different from URL nesting: versioning a whole API vs. versioning a single entity. Changes in API may include adding, moving and deleting resources, which is not something you can effectively describe using a version of entity.

Also, REST requires HATEOAS (see Richardson Maturity Model for in-depth explaination of this), which would be difficult (or impossible) to implement with header-based versioning. For example, is it even possible to fit header-based versions into HAL? You'd have to invent a way to add version into links, which would probably require custom format (not URL).

Some people think the opposite is true, but still I disagree, because it is not about versioning resources, but rather versioning the whole API. All resources inside each version of an API have the same version, no matter if those resources are the same as in previous versions.

Title: What is the correct project file structure for a versioned rest api?

Body:
Should I have resource directories inside version directory, like

```<code>app/
  v1/
   book/
   author/
  v2/
   author/
</code>```

or version directories inside resource folder

```<code>app/
  book/
    v1/
  author/
    v1/
    v2/
</code>```

which one would be easier to maintain and which is commonly used today?


问:
Using subroutines to return values?
I'm currently learning FORTRAN (I am familiar with MatLab) and I am very confused about the point of subroutines. Why would anyone use them as opposed to functions. Also, how is it that they can return values when called in the main programs? For example:

```<code>PROGRAM SUBDEM
    REAL A,B,C,SUM,SUMSQ
    CALL INPUT( + A,B,C)
    CALL CALC(A,B,C,SUM,SUMSQ)
    CALL OUTPUT(SUM,SUMSQ)
END

SUBROUTINE INPUT(X, Y, Z)
    REAL X,Y,Z
    PRINT *,'ENTER THREE NUMBERS => '
    READ *,X,Y,Z
    RETURN
 END

SUBROUTINE CALC(A,B,C, SUM,SUMSQ)
    REAL A,B,C,SUM,SUMSQ
    SUM = A + B + C
    SUMSQ = SUM **2
    RETURN
END

SUBROUTINE OUTPUT(SUM,SUMSQ)
    REAL SUM, SUMSQ
    PRINT *,'The sum of the numbers you entered are: ',SUM
    PRINT *,'And the square of the sum is:',SUMSQ
    RETURN
END
</code>```

My question is essentially, how do I know what each subroutine is returning?
Thank you.

答:
As a rough guide, functions are generally used to enclose a small segment of code that has no side-effects. For example, we can write

```<code>x = 2*foo(a) + foo(b)/4
</code>```

if the order of execution is not critical (either because of no side-effects or the side-effects don't influence the result). If the code segment is large and/or contains many side-effects, it might be better to use a subroutine. A subroutine call is always a separate statement and thus the execution order is always unambiguous.

A subroutine is like a C function with a void return type and with some arguments passed by reference (by default all, actually). Ignoring good style and code safety, it is in principle possible to use only functions or only subroutines when writing modern Fortran.

Title: Using subroutines to return values?

Body:
As a rough guide, functions are generally used to enclose a small segment of code that has no side-effects. For example, we can write

x = 2*foo(a) + foo(b)/4

if the order of execution is not critical (either because of no side-effects or the side-effects don't influence the result). If the code segment is large and/or contains many side-effects, it might be better to use a subroutine. A subroutine call is always a separate statement and thus the execution order is always unambiguous.

A subroutine is like a C function with a void return type and with some arguments passed by reference (by default all, actually). Ignoring good style and code safety, it is in principle possible to use only functions or only subroutines when writing modern Fortran.


问:
Algorithm for detection of overlapping between vectors
I am currently developing a math-physics program and I need to calculate if two vectors overlap one another, the one is vertical and the other is horizontral. Is there any fast algorithm to do this because what I came up so far, has a lot of repeats. Eg lets say we have vector V1((0,1),(2,1)) and a V2((1,0),(1,2)) where the first parenthesis is the coordinates starting and the second coordinates that the vector reaches. I want as a result to take that they overlap at (1,1)

So far the only idea I came up is to ''expand'' each vector to a list of points and then compare the lists e.g for V1 its list would be (0,1) (1,1) (2,1)

答:
Another algorithm is described here, which is based on these slides.

Given line segments p1 -> q1 and p2 -> q2, the line segments intersect if:

General Case:

if (p1, q1, p2) and (p1, q1, q2) have different orientations and

(p2, q2, p1) and (p2, q2, q1) have different orientations

Special Case

if (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and

the x-projections of (p1, q1) and (p2, q2) intersect and

the y-projections of (p1, q1) and (p2, q2) intersect

where the 'orientation' can be 'clockwise', 'counterclockwise' or 'collinear'.

Intuitively: if a line segment does not cross another line segment, it is entirely 'on one side' of the other segment. Only then will tracing (p1, q1, p2) and (p1, q1, q2) or (p2, q2, p1) and (p2, q2, q1) result in tracing the triangle in the same direction.


问:
How do you unit-test code using graph structures?
I am writing (recursive) code that is navigating a dependency graph looks for cycles or contradictions in the dependencies. However, I am not sure how to approach unit testing this. The problem is that one of our main concerns is will the code handle on all the interesting graph structures that can arise and making sure that all nodes will be handled appropriately.

While usually 100% line or branch coverage is sufficient to be confident that some code works, it feels like even with 100% path coverage you'd still have doubts.

So, how does one go about selecting graph structures for test cases to have confidence that their code could handle all the conceivable permutations you'll find in real world data.

PS- If it matters, all edges in my graph are labelled "must have" xor "cannot have" and there are no trivial cycles, and there is only one edge between any two nodes.

PPS- This additional problem statement was originally posted by the question's author in a comment below:

For all vertices N in forest F, for all vertices M, in F, such that if there are any walks between N and M they all must either use only edges labelled 'conflict' or 'requires'.

答: You could try doing a topological sort and seeing if it succeeds.  If it doesn't, then you have at least one cycle.</p>


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
1) Array comprehension in the style of Python list comprehension:

```<code>$newlist = array($x->something for $x in $oldlist);

//with short array syntax:
$newlist = [$x->something for $x in $oldlist];
</code>```

2) Short array syntax

```<code>$newlist = [1,2,3,4,...];
</code>```

3) Make empty() not consider the string '0' as true

Body:
1) Array comprehension in the style of Python list comprehension:

$newlist = array($x->something for $x in $oldlist);

//with short array syntax:
$newlist = [$x->something for $x in $oldlist];

2) Short array syntax

$newlist = [1,2,3,4,...];

3) Make empty() not consider the string '0' as true


问:
Is it OK to use Promises for Caching
Is it an acceptable (not surprising) to use promises to cache results?  The idea is to generate a promise once, and just return that same promise again on subsequent calls.

For example, a getAll() function that returns a promise would perform a time-intensive function only on the first call, and then return the same promise on repeat calls.

Example (in JavaScript, but I didn't actually try it, so more like pseudo-code):

```<code>var oldPromise = null;

function getAll() {
    var newPromise;

    if (!oldPromise) {

        // first time called
        newPromise = new Promise(function (resolve, reject) {
            timeIntensiveFunction(function callback(data) {
                resolve(data);
            });
        });

        oldPromise = newPromise

        return newPromise;
    } else {

        // already did it
        return oldPromise;
    }
}
</code>```

答:
Well, calling a time intensive function within asynchronous flow is not acceptable because that blocks everything until it returns.  That's the fundamental performance problem with cooperative multi-tasking.

Secondly, be sure to test possible flows with your actual promise library.  Specifically test what happens if the promise is returned twice, and starts running twice, and tries to finish twice.  Different promise libraries may do different things in this situation.  The safe solution is to assume that it is up to you to avoid actually running the long thing twice, so you do not attempt to resolve twice.

Third, your snippet does not show where data arrives from.  Be sure not to return the results of computing with the wrong set of data!

Fourth, if in doubt, comment on the purpose of what you are doing.  Don't confuse the maintenance programmer!

Those are a lot of caveats.  If you're comfortable with them, then this does seem to be a reasonable solution.  I'd personally be inclined to more up front caching mechanisms which make it obvious what is going on.  But this should work.

Title: Is it OK to use Promises for Caching


问:
override resolution behavior in c#
I tried the following piece of code

```<code>public abstract class Entry3
{
    public abstract void Method1();
    public virtual void Method2() { Console.WriteLine("Entry3.Method2"); }
}

public abstract class Entry31 : Entry3
{
    public override void Method1()
    {
        Console.WriteLine("Entry31.Method1");
    }
    public virtual void Method2() { Console.WriteLine("Entry31.Method2"); }
}

public class Entry32 : Entry31
{
    public override void Method1()
    {
        Console.WriteLine("hi");
    }
    public override void Method2() { Console.WriteLine("Entry32.Method2"); }
}

public class Main4
{
    public static void Main()
    {
        Entry32 e32 = new Entry32();
        e32.Method1();

        //((Entry31)e32).Method1();
        ((Entry3)e32).Method1();

        e32.Method2();
        ((Entry31)e32).Method2();
        ((Entry3)e32).Method2();

        Console.ReadKey();
    }
}
</code>```

The response was "Entry3.Method2" for the last line ((Entry3)e32).Method2();. I have overridden the base Entry31 Method2 in Entry32. Is C# finding that the Entry3 Method2 not being overridden in Entry32 and calling Entry3.Method2. Can anyone help me understand this behavior

答: Entry32::Method2 overrides Entry31::Method2, not Entry3::Method2. Since the override chain is broken between Entry3 and Entry31 (it is a shadow - completely different functions as far as the runtime is concerned) the virtual dispatch doesn't pass there.

Title: override resolution behavior in c#


问:
How are virtual methods slower in C#?
I read that virtual calls make the code slower than calling non-virtual ones in C#.
However, the IL instruction for both are the same callvirt except in cases where base.somemethod() is called.

So how does virtual method hurt performance?

答:
Since myself and others found the @Euphoric benchmark above illuminating, below is an expanded version that adds interfaces, lambdas, delegates and static. As one example, with .Net 4.5.2 and x86 output the result (in million iterations per seconds) consistently grouped into three buckets:

```<code>No function                   1,388.9 MOps/s
Non-virtual                   1,479.3 MOps/s
Static                        1,201.9 MOps/s

Virtual via class               456.2 MOps/s
Overridden via class            425.9 MOps/s
Base class                      394.3 MOps/s
Non-virtual via interface       357.4 MOps/s
Virtual via interface           466.0 MOps/s

Lambda                          286.9 MOps/s
Delegate                        277.6 MOps/s
</code>```

Expanded benchmark:

```<code>using System;
using System.Diagnostics;

    interface IClassA
    {
        int Func1(int a);
        int Func2(int a);
    }

    class ClassA : IClassA
    {
        public int Func1(int a)
        {
            return a + 2;
        }

        public virtual int Func2(int a)
        {
            return a + 2;
        }

        public static int StaticFunc(int a)
        {
            return a + 2;
        }
    }

    class ClassB : ClassA
    {
        public override int Func2(int a)
        {
            return a + 2;
        }
    }

    delegate int MyDelegate(int a);

    class Program
    {
        static int forDelegate(int a)
        {
            return a + 2;
        }

        public static void Main()
        {
            MethodCall();
        }

        public static void MethodCall()
        {
            const int loops = 500000000;
            int x = 0;
            ClassA a = new ClassA();
            ClassB b = new ClassB();
            ClassA c = new ClassB();

            Console.WriteLine("Method Call Overhead:");

            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < loops; i++)
            {
                x = x + 2;
            }
            watch.Stop();
            Report("No function", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = a.Func1(x);
            }
            watch.Stop();
            Report("Non-virtual", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = ClassA.StaticFunc(x);
            }
            watch.Stop();
            Report("Static", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = a.Func2(x);
            }
            watch.Stop();
            Report("Virtual via class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = b.Func2(x);
            }
            watch.Stop();
            Report("Overridden via class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = c.Func2(x);
            }
            watch.Stop();
            Report("Base class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            IClassA iClassA = a;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = iClassA.Func1(x);
            }
            watch.Stop();
            Report("Non-virtual via interface", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = iClassA.Func2(x);
            }
            watch.Stop();
            Report("Virtual via interface", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            Func<int, int> func = l => l + 2;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = func(x);
            }
            watch.Stop();
            Report("Lambda", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            MyDelegate myDelegate = forDelegate;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = myDelegate(x);
            }
            watch.Stop();
            Report("Delegate", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            System.Console.ReadKey();
            System.Console.WriteLine(x); // so the compiler doesn't optimize it away
        }

        static void Report(string message, int iterations, long milliseconds)
        {
            System.Console.WriteLine(string.Format("{0,-26:} {1,10:N1} MOps/s, {2,7:N3} s", message, (double)iterations / 1000.0 / milliseconds, milliseconds / 1000.0));
        }
    }
</code>```

Hope it helps!

Title: How are virtual methods slower in C#?

Body:
Since myself and others found the @Euphoric benchmark above illuminating, below is an expanded version that adds interfaces, lambdas, delegates and static. As one example, with .Net 4.5.2 and x86 output the result (in million iterations per seconds) consistently grouped into three buckets:

No function                   1,388.9 MOps/s
Non-virtual                   1,479.3 MOps/s
Static                        1,201.9 MOps/s

Virtual via class               456.2 MOps/s
Overridden via class            425.9 MOps/s
Base class                      394.3 MOps/s
Non-virtual via interface       357.4 MOps/s
Virtual via interface           466.0 MOps/s

Lambda                          286.9 MOps/s
Delegate                        277.6 MOps/s

Expanded benchmark:

using System;
using System.Diagnostics;

    interface IClassA
    {
        int Func1(int a);
        int Func2(int a);
    }

    class ClassA : IClassA
    {
        public int Func1(int a)
        {
            return a + 2;
        }

        public virtual int Func2(int a)
        {
            return a + 2;
        }

        public static int StaticFunc(int a)
        {
            return a + 2;
        }
    }

    class ClassB : ClassA
    {
        public override int Func2(int a)
        {
            return a + 2;
        }
    }

    delegate int MyDelegate(int a);

    class Program
    {
        static int forDelegate(int a)
        {
            return a + 2;
        }

        public static void Main()
        {
            MethodCall();
        }

        public static void MethodCall()
        {
            const int loops = 500000000;
            int x = 0;
            ClassA a = new ClassA();
            ClassB b = new ClassB();
            ClassA c = new ClassB();

            Console.WriteLine("Method Call Overhead:");

            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < loops; i++)
            {
                x = x + 2;
            }
            watch.Stop();
            Report("No function", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = a.Func1(x);
            }
            watch.Stop();
            Report("Non-virtual", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = ClassA.StaticFunc(x);
            }
            watch.Stop();
            Report("Static", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = a.Func2(x);
            }
            watch.Stop();
            Report("Virtual via class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = b.Func2(x);
            }
            watch.Stop();
            Report("Overridden via class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = c.Func2(x);
            }
            watch.Stop();
            Report("Base class", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            IClassA iClassA = a;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = iClassA.Func1(x);
            }
            watch.Stop();
            Report("Non-virtual via interface", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = iClassA.Func2(x);
            }
            watch.Stop();
            Report("Virtual via interface", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            Func<int, int> func = l => l + 2;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = func(x);
            }
            watch.Stop();
            Report("Lambda", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            MyDelegate myDelegate = forDelegate;
            watch.Restart();
            for (int i = 0; i < loops; i++)
            {
                x = myDelegate(x);
            }
            watch.Stop();
            Report("Delegate", loops, watch.ElapsedMilliseconds);
            x -= 2 * loops;

            System.Console.ReadKey();
            System.Console.WriteLine(x); // so the compiler doesn't optimize it away
        }

        static void Report(string message, int iterations, long milliseconds)
        {
            System.Console.WriteLine(string.Format("{0,-26:} {1,10:N1} MOps/s, {2,7:N3} s", message, (double)iterations / 1000.0 / milliseconds, milliseconds / 1000.0));
        }
    }

Hope it helps!


问:
What default features is Windows missing that are required for programmers?
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.

答:
A compiler and a useful shell.

Clarification based on the comments:

I was unclear, I should have written C/C++ compiler. Compilers for C# or Fortran doesn't count, as much of the tools and libraries you need requires a C or C++ compiler. It used to be really bad, where you could not build C extensions for Python with another compiler than Microsofts, because that's what Python was compiled with, I think MinGW has solved this and you can do it with MinGW now, but that's a good reason why a standard C/C++ compiler should have been included or made available for free 20 years ago. Microsoft is only lately starting to understand the power of having an army of hobby programmers available.

I haven't used powershell, maybe it is good. But the usefulness of bash for me is not in the shell language. The *sh family of languages are horrid beasts anyway. I even prefer batch files. ;) It's things like the command history recall and search which relatively basic in Windows, and having pipelines and such that I'm talking about (and I see powershell has pipelines, so that's good).

There are things that are good in Windows too, but that's another topic. ;)


问:
What is the Discount Factor for in the Value Iteration Algorithm?
Can someone please explain what the discount factor means in the Value Iteration Algorithm for solving Markov Decision Processes?

I understand the equation, but I don't understand why it requires the discount factor (gamma).

答:
Here's what I understand: discount factor represents the preference of short-term solutions over long-term solutions.

For example, if I could earn $1 today, I'd value it more than $1 which I could earn tomorrow, and much more than $1 which I could earn on Jan 1, 2050, because random factor change situation more and more as time passes. Discount factor shows how much is today's $1 more valuable than tomorrow's $1.

Since the whole algorithm is about making decisions where the outcome partly depends on random inputs which can drift away over time, invalidating initial decision, it makes sense to prefer decisions which a better as short-term solutions.


问:
How to map the english dictionary to UNSPSC codes?
Is there a db which maps the words from the english dictionary to the UNSPSC codes?(http://www.unspsc.org/)

My problem is the following:
I am building a search system. And the customer searches for 'pencil' and 'pencil sharpeners' are also returned. Each of the returned item has a UNSPSC code associated with it.

So one possible solution would be to search only for those items in the categories the search word belongs to. But this solution would require a mapping from english words to the UNSPSC codes...

答:
Each UNSPSC-code has a title. 'pencil' is part of the following UNSPSC-codes:

```<code>44111509    Pen or pencil holders
42295401    Battery operated surgical cautery pencils
60121519    Wax based colored drawing pencils
42295425    Surgical silver nitrate sticks or pencils or crystals
53141611    Fabric markers or fabric pencils or fabric chalk
44121619    Manual pencil sharpener
44121636    Electric pencil sharpener
60121518    Graphite pencils
60121520    Charcoal pencils
44121706    Wooden pencils
44121705    Mechanical pencils
44121702    Pen or pencil sets
44121707    Colored pencils
44121715    Combination pen or pencil
60121531    Pink pencil erasers
60121521    Watercolor pencils
44121714    Pencil or pen grips
</code>```

Is this the list you look for? You could take this values and check if they fit to the UNSPSC-codes from your search.

The complete list of UNSPSC is available at UNSPSC.org (you must be a member or pay $100 per version).

Body:
Each UNSPSC-code has a title. 'pencil' is part of the following UNSPSC-codes:

44111509    Pen or pencil holders
42295401    Battery operated surgical cautery pencils
60121519    Wax based colored drawing pencils
42295425    Surgical silver nitrate sticks or pencils or crystals
53141611    Fabric markers or fabric pencils or fabric chalk
44121619    Manual pencil sharpener
44121636    Electric pencil sharpener
60121518    Graphite pencils
60121520    Charcoal pencils
44121706    Wooden pencils
44121705    Mechanical pencils
44121702    Pen or pencil sets
44121707    Colored pencils
44121715    Combination pen or pencil
60121531    Pink pencil erasers
60121521    Watercolor pencils
44121714    Pencil or pen grips

Is this the list you look for? You could take this values and check if they fit to the UNSPSC-codes from your search.

The complete list of UNSPSC is available at UNSPSC.org (you must be a member or pay $100 per version).


问:
"One of some"-type
Say that you have some different classes that does not really have any functionality in common, but somewhere in your program, you need one of them (which one is not necessarily important) because they have a functionality in that context. What is the best way to do that?

I know that you can take an Object and use instanceof to check whether it is one of those types, but I am looking for a way to let the type system ensure that it will just be one of those types. Or is that impractical/impossible?

What I thought about doing was to create an empty interface and implement it in all the classes that needed it. but I have seen that you are supposed to use annotations instead of a marker interface, but I am not sure if that applies in this situation because I do not really care about run-time information. Another thing I am worried about is that implementing that interface in those classes will cause spaghetti code. Those classes should not really have to know anything about how they are used elsewhere.

答:
You cannot meld three classes so that an instance of this chimeric class can be used as an instance of either of the three types (as in LSP).

You can make an umbrella class that, unlike an empty interface, gives you real type-checking.

```<code>class AppleBookCar() {
   final Apple apple;
   final Book book;
   final Car car;
   private AppleBookCar(Apple a, Book b, Car c) {
     apple = a; book = b; car = c;
   }
   public static AppleBookCar fromApple(Apple apple) {
     return AppleBookCar(a, null, null);
   }
   public static AppleBookCar fromBook(Book book) {
     return AppleBookCar(null, book, null);
   }
   public static AppleBookCar fromCar(Car car) {
     return AppleBookCar(null, null, car);
   }
   public Apple asApple() { return this.apple; }
   public Book asBook() { return this.book; }
   public Car asCar() { return this.car; }
}
</code>```

This boilerplate is, of course, boring; better languages would write it for you.

Title: "One of some"-type

Body:
You cannot meld three classes so that an instance of this chimeric class can be used as an instance of either of the three types (as in LSP).

You can make an umbrella class that, unlike an empty interface, gives you real type-checking.

class AppleBookCar() {
   final Apple apple;
   final Book book;
   final Car car;
   private AppleBookCar(Apple a, Book b, Car c) {
     apple = a; book = b; car = c;
   }
   public static AppleBookCar fromApple(Apple apple) {
     return AppleBookCar(a, null, null);
   }
   public static AppleBookCar fromBook(Book book) {
     return AppleBookCar(null, book, null);
   }
   public static AppleBookCar fromCar(Car car) {
     return AppleBookCar(null, null, car);
   }
   public Apple asApple() { return this.apple; }
   public Book asBook() { return this.book; }
   public Car asCar() { return this.car; }
}

This boilerplate is, of course, boring; better languages would write it for you.


答:
This is an absolutely sensible use of promises. Its one of the primary ways that promises are intended to be used.

The way that promises can have .then() added before or after being resolved is directly to allow this kind of usage. The point is that you might have the value right away, or it might not show up until some time later. In either case, the promise api runs the same way.

On the side, your code can be simplified

```<code>var promise = null;

function getAll() {
    if (!promise) {

        // first time called
        promise = new Promise(function (resolve, reject) {
            timeIntensiveFunction(function callback(data) {
                resolve(data);
            });
        });
    }
    return promise;
}
</code>```

Or using lodash or underscore

```<code>getAll = _.memoize(function() {
   return new Promise(function (resolve, reject) {
       timeIntensiveFunction(function callback(data) {
           resolve(data);
       });
   });
});
</code>```

Title: Is it OK to use Promises for Caching

Body:
Is it an acceptable (not surprising) to use promises to cache results?  The idea is to generate a promise once, and just return that same promise again on subsequent calls.

For example, a getAll() function that returns a promise would perform a time-intensive function only on the first call, and then return the same promise on repeat calls.

Example (in JavaScript, but I didn't actually try it, so more like pseudo-code):

```<code>var oldPromise = null;

function getAll() {
    var newPromise;

    if (!oldPromise) {

        // first time called
        newPromise = new Promise(function (resolve, reject) {
            timeIntensiveFunction(function callback(data) {
                resolve(data);
            });
        });

        oldPromise = newPromise

        return newPromise;
    } else {

        // already did it
        return oldPromise;
    }
}
</code>```

Body:
This is an absolutely sensible use of promises. Its one of the primary ways that promises are intended to be used.

The way that promises can have .then() added before or after being resolved is directly to allow this kind of usage. The point is that you might have the value right away, or it might not show up until some time later. In either case, the promise api runs the same way.

On the side, your code can be simplified

var promise = null;

function getAll() {
    if (!promise) {

        // first time called
        promise = new Promise(function (resolve, reject) {
            timeIntensiveFunction(function callback(data) {
                resolve(data);
            });
        });
    }
    return promise;
}

Or using lodash or underscore

getAll = _.memoize(function() {
   return new Promise(function (resolve, reject) {
       timeIntensiveFunction(function callback(data) {
           resolve(data);
       });
   });
});


答: A decent shell, plus a compiler would be a good start as far as "default" features are concerned.</p>

Title: What default features is Windows missing that are required for programmers?

Body:
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.


问:
How can I find what Resources a Java EE container provides?
How can I find what "Resources" a Java EE container provides? Can I discover this programmatically, or is there documentation I should refer to? (Note that the Java EE tutorial is vague on this subject.)

Here is an example of what I'm talking about:

I was reading the Java EE 6 documentation for Using the Timer
  Service,
  and I noticed that it doesn't really explain what the TimerService
  technically is. If you read the documentation, you eventually see an
  example that a TimerService is obtainable using the @Resource
  annotation.

From this I take it that a TimerService is a Resource provided by the
  container. If it weren't for the example, I never would have realized
  this without reading a third-party blog post: at no point does the
  official tutorial say that "TimerService is a container-provided
  Resource". TimerService is very useful, so I would like to know what
  other Resources are available.

To be clear, I'm not looking for a third-party blog post, and the official Java EE tutorial is just that, a tutorial: it's not comprehensive. And I briefly checked the Java EE 7 Platform JSR, but I couldn't find a reference to TimerService.

Is there a way to programmatically find the Resources a container provides, or is there a documented list of Resources a Java EE container must provide?

答:
You're under a bit of misconception here. First, divorce the @Resource annotation from javax.ejb.TimerService. Now read the following excerpt from the JavaEE api:

The Resource annotation marks a resource that is needed by the application. This annotation may be applied to an application component class, or to fields or methods of the component class. When the annotation is applied to a field or method, the container will inject an instance of the requested resource into the application component when the component is initialized. If the annotation is applied to the component class, the annotation declares a resource that the application will look up at runtime.

What that implies is that anything can be declared a resource, to be injected by @Resource. The annotation can be used to inject anything, ranging from primitive <env-entry/> definitions in the web.xml, to various connection managers (Java Mail, Datasources e.t.c) and it is done on-demand

Typically, it's items that are eligible for JNDI-based access, that are injected using @Resource. What this means is that, you need to have a JNDI name, to address a resource before going to look for it (the default value of the name element is the field name
qualified by the class name). JSR-250, which defines the @Resource annotation lists all the viable targets for that annotation.

If however, you're confident you really want to know everything that the container might be able to inject, you could try listing all available JNDI entries. I don't recommend it.

As for TimerService in specific, a container must provide an implementation of TimerService in order to be JavaEE compliant. This is a quote from JSR 345:

The container must provide the implementation of the TimerService,
  Timer, and TimerHandle interfaces.

If you look at the table of contents of JSR 345, you'll see that TimerService gets a chapter to itself, at the same level as topics like "Security Management". This just goes to show that while TimerService may feel like a utility class, it's arguably at the same level of abstraction as any other container-provided service

If you're looking for an authoritative list of mandatory container-provided services, the spec is the place to look. Knowing which spec to look at can be tricky, but as TimerService is in the javax.ejb package, the EJB spec is a good guess.


问:
Is it okay to have code smells if it admits an easier solution to another problem?
A group of friends and I have been working on a project for the past little while, and we wanted to invent a nice OOP way of representing a scenario specific to our product. Basically, we're working on a Touhou-style bullet hell game, and we wanted to make a system where we could easily represent any possible behaviour of bullet we could dream up.

So that's exactly what we did; we made a really elegant architecture that allowed us to section off the behaviour of a bullet into different components that could be attached to bullet instances at will, kind of like Unity's component system. It worked nicely, it was easily extensible, it was flexible and covered all our bases, but there was a slight problem.

Our application also involves a heavy amount of procedural generation, namely we procedurally generate the behaviours of the bullets. Why is this a problem? Well, our OOP solution to representing bullet behaviour, while elegant, is a little complicated to work with without a human. Humans are smart enough to think of solutions to problems that are both logical and clever. Procedural generation algorithms aren't that smart yet, and we've found it difficult to implement an AI that uses our OOP architecture to its fullest potential. Admittedly, that is a flaw of the architecture is that it's not intuitive in all situations.

So to remedy this problem, we basically shoved all the behaviours offered by different components into the bullet class, so that everything we could ever imagine is offered directly in each bullet instance as opposed to in other associated component instances. This makes our procedural generation algorithms a little easier to work with, but now our bullet class is a huge god object. It is easily the largest class in the program so far with more than five times as much code as anything else. It's a bit of a pain to maintain as well.

Is it okay that one of our classes turned into a god object, just to make it easier to work with another problem? In general, is it okay to have code smells in your code if it admits an easier solution to a different problem?

答:
Interesting question. I am a bit biased though due to my previous experiences, which prompts me to answer with No.

Short answer: We never stop learning. When you hit a wall like that, it is a chance to improve your architectural/design skills, not an excuse to add code smells.

The longer version is that I have been asked similar questions a lot of times in my projects at work now, but inevitably, we ended up discussing the issue in much more depth, then the original questioner gave it credit for. You want to include mentalities like root cause analysis with that.

I found the 5 Whys particularly helpful. Your explanation here reads just like the first why:

"We have this god class now" Why?

"Because it simplifies the procedural generation algorithm"

What is it exactly that is simplified? And why is that so? Keep on going along that line and what typically happens is that you start to recognize way more fundamental problems, but at the same time, they allow you more fundamental solutions just as well.

Long story short, after thinking more deeply about the problem at hand and in particular its causes, in my experience the original question ended up being void and utterly uninteresting to all participants. If you have doubts, challenge them and either they will be gone, or you'll know what you have to do. Mind you, it is a good sign in my opinion to have these doubts about code/design. Others call it a gut feeling, but in order to challenge these problems, you must first recognize them. Since you made that first step, congratulations! Now go down the rabbit hole ...


答:
When building real-world programs, there is often a trade-off between staying pragmatic on one hand, and staying 100% clean on the other. If staying clean prohibits you to ship your product in time, then you are better off with a little bit of duct-tape to get the d***d thing out of the door.

Said that, your description sounds different - it sounds you are not going to add a little bit of duct tape, it sounds like you are going to ruin your whole architecture because you did not look long and hard enough for a better solution. So instead of seeking for someone here on PSE who gives you a blessing on this, you might better ask a different question where you describe some details of the problems you have in-depth, and look if someone offers you an idea which avoids the god-class approach.

Maybe the bullet class can be designed to be facade to a bunch of other classes, so the bullet class becomes smaller. Maybe the strategy pattern can help so the bullet can delegate different behaviours to different strategy objects. Maybe you need just an adapter between your bullet component and your procedural generator. But honestly, without knowing more details of your system, one can only guess around.

Title: Is it okay to have code smells if it admits an easier solution to another problem?

Body:
A group of friends and I have been working on a project for the past little while, and we wanted to invent a nice OOP way of representing a scenario specific to our product. Basically, we're working on a Touhou-style bullet hell game, and we wanted to make a system where we could easily represent any possible behaviour of bullet we could dream up.

So that's exactly what we did; we made a really elegant architecture that allowed us to section off the behaviour of a bullet into different components that could be attached to bullet instances at will, kind of like Unity's component system. It worked nicely, it was easily extensible, it was flexible and covered all our bases, but there was a slight problem.

Our application also involves a heavy amount of procedural generation, namely we procedurally generate the behaviours of the bullets. Why is this a problem? Well, our OOP solution to representing bullet behaviour, while elegant, is a little complicated to work with without a human. Humans are smart enough to think of solutions to problems that are both logical and clever. Procedural generation algorithms aren't that smart yet, and we've found it difficult to implement an AI that uses our OOP architecture to its fullest potential. Admittedly, that is a flaw of the architecture is that it's not intuitive in all situations.

So to remedy this problem, we basically shoved all the behaviours offered by different components into the bullet class, so that everything we could ever imagine is offered directly in each bullet instance as opposed to in other associated component instances. This makes our procedural generation algorithms a little easier to work with, but now our bullet class is a huge god object. It is easily the largest class in the program so far with more than five times as much code as anything else. It's a bit of a pain to maintain as well.

Is it okay that one of our classes turned into a god object, just to make it easier to work with another problem? In general, is it okay to have code smells in your code if it admits an easier solution to a different problem?


答:
In some cases this is definitely acceptable. However, I find it hard to believe there is no good solution using both procedural generation and your nice attached/component based behavior architecture. If all behaviors where just pulled into the bullet class there is no functional difference between the god object, and neat architectured version. What made it so hard for your procedural generation algorithms to use?

I think a new question (maybe here, or on gamedev.stackexchange.com?), where you outline what problems you had with your architecture in combination with proc. gen., would be really interesting. Let us know here if too if you do make a new question!


答:
include better hypertext-links support, i.e. a function/class-method that can be used to change the browser's current-uri. or to create a totally new one.
using $_SERVER[ 'REQUEST_URI' ] || $_SERVER[ 'PATH_INFO' ] to understand the resource that is requested. This might make something like developing REST-apps easier.   (   according rfc's UriScheme and it's default scheme implementation, maybe make it possible to implement other UriSchemes extending the UriBase)

Provide something like a UriResource class, enabling requesting small snippets of functionality in a way that could also benefit http-requests from a client.

Make a function that can be called before and after a template, enabling short-tags between those two function-calls. Between those function-calls the only variables that are made available are those passed to the first function-call( as associative array( using extract)).
This might ease template-development in php itself( no-framework framework).
The no-framework PHP MVC framework

All in all i think the many php frameworks out there have certain similarities which could easily be integrated into php in a common way.

but whoami :)

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

OwnerDisplayName: immeëmosol


问:
SOA: Make each level of a service stack a package (NuGet etc.)?
Say I have a service that has the following hierarchy:

Controller

Business Logic

Data Adapter

All of these make up a service that presents an HTTP API that can be used by other services. Together these layers form a functional piece of an application.

Does it make sense to package each of these layers together as 1 versioned unit? Or to package each individualy with its own version and then consume eachother as a package dependency using NuGet for example. Controller consumes the business logic package which in turn consumes the data adapter package.

Would there be any benefit over the other?

Essentially what I'm asking is should packages be left for shared code across many services/applications or should the guts of a service also use packages to manage its internal dependencies in its own stack?

答:
It depends on your application.

For example, I have a product that comprises a server installation which is several services, and a client application. We package these as 2 pieces - whilst each of the server side components could be installed individually, nobody ever does (or will) so it makes sense to install them as a single item. This allows us to reduce the effort required in making different versions of these pieces works together.

However, nobody likes upgrading the clients as it requires an engineer to visit some remote sites, so we install those separately and ensure old clients can still talk to updated server.

So we have half a dozen components, but these end up as 2 installers. Its all down to your system, and your dependancy management between them. It also depends on your customer- if these packages are being created for developers, then maybe it will make sense to package each one up individually to allow changes to be acquired quicker.


答:
Having a god class like this is never desirable, as it does not only mean that your bullets are now monolithic objects, but the same goes for your procedural generation algorithm as well.

The first step would have been to analyze, why exactly your AI did have so much trouble with dealing with the complexity of your pattern?

Did you, by chance, tried to turn your AI into a god class object as well, fully aware about the semantics of every single possible property? If you did, that's where the problem originated.

The solution would then not have been to integrate all strategies into the bullet class itself, but instead offloading the hinting for the AI from the AI core to the strategy implementations themselves.

That would have given you the flexibility you originally desired, including the option to extend the system by new strategies as you wish without the fear of running into side effects with legacy behaviors.

Instead you have now all the problems associated with god objects: No only your god class itself is a hard to understand, hard to debug monolith, but the same goes also for all other components accessing such a god class. Due to the lack of abstraction, your AI is now bound to turn into an abomination of similar complexity as it has to be aware of all the redundant, individual properties now.

Even right now, you are already experiencing problems with maintenance. These problems are getting worse, especially as soon as you loose the team members who still have a cognitive model of how that class is supposed to work.

So far every single project I encountered which used such god classes or god functions either was completely rewritten from scratch or ceased, no exceptions.


问:
Upgrade object in PHP
I cannot find information on this anywhere so I assume it doesn't exist.

It makes much sense for me for such functionality to exist and I want to ask whether it actually does and I am wrong in my assumption, or is there any good reasons it does not and why I should not attempt to create it.

```<code>class User {
    public $name;
    public function __construct($name){
        $this->name = $name;
    }
}

class Admin extends User {
    private $permissions = 0777; // dumb example
}

$user = new User('Tom');

// we decide tom should be an admin
$user->upgrade('\Admin');

get_class($user); // returns "Admin"
</code>```

Eventually this will also eliminate the need of factories.

答:
Your example is already flawed, as Admin gains new properties over the base class which makes it incompatible. It would have been smarter to place the $permissions property straight away in the base class.

Ask yourself, in what cases could it be desirable to introduce new properties on an existing object?

Both instantiating an object as an instance of a specific class or using a factory with proper type hinting gives you a guarantee that your generated object has specific properties and interfaces, and the behavior of each single interface is constant over the lifetime of the object.

By promoting the object to a different class during live time, you are violating that promise, making it hard to trace which implementation your code is actually using over the course of its lifetime.

It also creates another problem, if you choose to dynamically extend your object during runtime, there is no way of going back to choose a different refinement. Each interface you are expecting your object to have, should therefor already be present at creation.

If, like in your example, you have a case where a special case of a class is more advanced in only a single aspect, consider offloading that behavior into a separate class. In your case:

```<code>class User {
    private $permission;
    private $name
    public function __construct($name, Permission $permission){
        $this->name = $name;
        $this->permission = $permission;
    }
    public function changePermissionModell(Permission $permission) {
        $this->permission = $permission;
    }
}
interface Permission {
    public function checkPermission($scope);
}
class ACLPermission implements Permission {
    public function checkPermission($scope) {
        return ACL::checkPermission($scope);
    }
}
class RootPermission implements Permission {
    public function checkPermission($scope) {
        return true;
    }
}
$defaultPermission = new ACLPermission();
$user = new User("Tom", $defaultPermission);
// Promote "Tom" to admin
$user->changePermissionModell(new RootPermission());
</code>```

Title: Upgrade object in PHP

Body:
Your example is already flawed, as Admin gains new properties over the base class which makes it incompatible. It would have been smarter to place the $permissions property straight away in the base class.

Ask yourself, in what cases could it be desirable to introduce new properties on an existing object?

Both instantiating an object as an instance of a specific class or using a factory with proper type hinting gives you a guarantee that your generated object has specific properties and interfaces, and the behavior of each single interface is constant over the lifetime of the object.

By promoting the object to a different class during live time, you are violating that promise, making it hard to trace which implementation your code is actually using over the course of its lifetime.

It also creates another problem, if you choose to dynamically extend your object during runtime, there is no way of going back to choose a different refinement. Each interface you are expecting your object to have, should therefor already be present at creation.

If, like in your example, you have a case where a special case of a class is more advanced in only a single aspect, consider offloading that behavior into a separate class. In your case:

class User {
    private $permission;
    private $name
    public function __construct($name, Permission $permission){
        $this->name = $name;
        $this->permission = $permission;
    }
    public function changePermissionModell(Permission $permission) {
        $this->permission = $permission;
    }
}
interface Permission {
    public function checkPermission($scope);
}
class ACLPermission implements Permission {
    public function checkPermission($scope) {
        return ACL::checkPermission($scope);
    }
}
class RootPermission implements Permission {
    public function checkPermission($scope) {
        return true;
    }
}
$defaultPermission = new ACLPermission();
$user = new User("Tom", $defaultPermission);
// Promote "Tom" to admin
$user->changePermissionModell(new RootPermission());


答:
Operator overloading:</p>

```<code>$result = $MatrixA + $MatrixB * $MatrixC;
</code>```

Body:
Operator overloading:

$result = $MatrixA + $MatrixB * $MatrixC;


问:
Project architecture for application with dynamic database
We've a project that has some tables are defined and some will be generated runtime, means dynamic and no pre-defined structure.

We generally use Entity Framework to communicate to the database(in our case MS SQL).

But for this kind of requirement, what should we do for database communication as the database will be dynamic and column names are also dynamic.

Tables and columns of database are generated dynamically so in case of Entity Framework, I'm not sure it might work or not?

If we're choosing Entity Framework with Code First, in that case we need to create classes runtime and update database as well, which I guess not possible.

If we're choosing Entity Framework with Model First,in that scenario we also need to update model file (.edmx) runtime, which I guess not possible.

So the last option come is to use ADO.Net from which we can dynamic query the database and get result without defining model as well.

So I need help here to design the architecture and a good way to archive it.
We're ready to go with NoSql but the thing "dynamic database".

Is there a way so we can use Entity Framework?

答:
I've seen dynamically changing DB systems- driven by configuration where the customer adds columns "on the fly" for metadata that they want stored in addition to a few fixed columns.

In all cases, you're now driving your application using configuration, and that means your queries have to be calculated at runtime - this rules out all systems that determine the DB structure at compile time, such as pretty much every ORM there is. So you'll be using SQL queries built in code, that you have to generate yourself. Then use normal SQL client commands to call the DB - SQLClient or ODBC.

You can redesign such a system to place the dynamic data in a single column as a blob of XML but then you lose the ability to search or query on that data - NoSQL DBs resolve this, but if you need to use a combination of both Postgresql allows you to place dynamic 'nosql' data in a column that can be indexed by the DB engine, giving you the best of both worlds.


问:
Is using triggers best solution for this scenario
A large SQL transactional database has more than 100 tables (and it will grow). One of them is called Order. Then, there is another table WorkLoad which derives from Order and many other joined table which contains a list of all active order. Every time an order record is created, if it meets certain conditions, it should be instantly inserted into WorkLoad table. And finally, there is a third table WorkLoadAggregation which displays aggregated data grouped by date and shop and it is completely built from WorkLoad table. WorkLoadAggregation should also display live data meaning that if a record is inserted in WorkLoad table then matching date/shop aggregation should also be updated.

My idea was to handle this by triggers:

When record is inserted in Order table, trigger calls stored procedure which inserts record into WorkLoad table

When Order record is deleted trigger deletes the record from WorkLoad table

When Order record is updated in a way that it doesn't meet WorkLoad conditions, trigger deletes the record from WorkLoad table

When record is inserted/deleted/updated in WorkLoad table, trigger calls stored procedure which updates matching date/shop aggregated record in WorkLoadAggregation table

I haven't used triggers that much in such large transaction dbs and for such frequent calls. Is there anything bad in this approach? My biggest concern is usage of "chained triggers", meaning that trigger on one table activates trigger on another table. I've been reading few articles which state that developers should be very cautious when using triggers. Are there any better solutions? Should I consider any NoSQL solution?

答:
I'll discourage the option to use triggers in such case. You might be better off thinking in API terms to your model. As the comments point out, use stored procedures, as they will be easier to debug in case something goes not according to plan, keep in mind that you have a quite complex situation ;-)

Some helpful references,

wikipedia article about triggers

nice answer in this website

another external article about the topic


答: Strings should be objects</p>

Body: Strings should be objects


问:
Under what cirumstances would type 'System.Object' qualify for serialization?
I'm in charge of a comprehensive serialization format with support to serialize runtime objects (any derived type of Object). I can't find a sane scenario where one would choose to serialize an instance of System.Object immediately. In my purview, Object is undefinitive, and belongs in a binary format, not in a human-readable text.

With the introduction of Generics, instances of type Object should no longer identify data. Any insights to get me over the edge? For consideration, note that both Data Contracts and JSON.NET support serialization of System.Object.

答:
In my purview, Object is undefinitive, and belongs in a binary format, not in a human-readable text.

I don't see the relationship between these two things; there are plenty of good reasons to choose text versus binary: this is not one of them. How it appears is an implementation detail only.

any derived type of Object

The biggest challenge, then, is deciding how you are going to encode the type data. In many serializers, the answer is simply: you don't. This avoids an entire family of problems with refactoring and version (renaming types, assembly-names, etc). You could limit yourself to [Serializable] types, but by the time you've done that you might as well just use the (terrible, IMO) BinaryFormatter. Of course, some key questions here might be: why do you want to write your own serializer? What is the feature(s) you are after that aren't satisfied by the existing platform tools and 3rd-party / open-source tools?

Then you have a range of protocol / formatting considerations; mapping serialized data back into types is ... non-trivial. If the type is going to require configuration (think: [XmlElement(...)] etc), you could reasonably limit yourself to types that have the basic configuration evidence. This is kinda what DataContractSerializer does, except it falls back into a more basic field-level serializer if that configuration data is missing.

I'm also a big advocate for the view that entity models make lousy serialization types, so it is quite reasonable to expect there to exist a DTO model that broadly reflects your serialization needs; and if that is the case, it is not unreasonable to expect that the DTO type might be annotated in some way (or at least advertised to the serializer in some way - perhaps at runtime if attributes aren't an option).


答:
All bad code since the dawn of time has a story behind its evolution that makes it look reasonable step by step.  Yours is no exception.  Coders learn by coding.  There are aspects of your problem you could not have foreseen that seem obvious now.  There are decisions you made that were entirely reasonable incrementally, but led your architecture in the wrong direction overall.  You need to identify and reexamine those decisions.

Ask around your office if people have any ideas for how to fix it.  Most places I've worked, around 10-20% of the programmers have a real knack for that sort of thing, and have just been waiting for the chance.  Figure out who those people are.  Often, it's your new hires who aren't historically invested in the current architecture who can most easily see alternatives.  Pair them with one of your veterans and you might be amazed what they come up with together.


问:
Questions about LGPL license
I have a similar problem than this: http://sourceforge.net/p/tcpdf/discussion/435311/thread/32a59ca0/ Developer answered to ask a lawyer but it costs money... a lot?

I only use TCPDF, I have not edited it. Software takes input from users and makes PDF files based on that. It will be used commercially as a service so user will have an account and code will be on my server.

So the question is, can I use TCPDF commercial - I think I can since it is LGPL v3 licensed and these couple of sites like choosealicense and tldrlegal said I can.

So is there anyone who knows and understands this law text.

答:
Of course you can use LGPL-licensed libraries, but you have to fulfil the requirements stated in the license.

First of all, you are not required to do anything unless you choose to convey/distribute the library or an application that is “linked” to the library (see also §2 of the GPL v3). Since your application resides on your server, you are not distributing the library or an application that depends on this library to your users. Therefore, you may use it as you please, without any restrictions or requirements.

Things change if you want to distribute your server code (e.g. sell it) – see §4 of the LGPL v3 for details. Your code may still be closed-source legally, but users must be able to swap out and modify the LGPL-licensed library. This is typically no problem with normal PHP code, since users could simply edit the .php files of the library. Also, you need to acknowledge your use of the library in the same place where you would state your copyright and license for your code (e.g. a LICENSE or README file in a tarball).

Title: Questions about LGPL license


答:
I'd love to see unification of Errors and Exceptions into a single concept (Exceptions). Its great to be able to catch exceptions and write them to a log, to find and fix bugs that way. But if there's something fundamentally wrong (read: PHP Error) in a codepath that is very rarely hit, there's no good way to funnel that info into that same database of issues. </p>

<p>Please, Santa, introduce a switch in php.ini that would make all errors into exceptions - ideally, exceptions I can catch in my code. </p>

Body:
I'd love to see unification of Errors and Exceptions into a single concept (Exceptions). Its great to be able to catch exceptions and write them to a log, to find and fix bugs that way. But if there's something fundamentally wrong (read: PHP Error) in a codepath that is very rarely hit, there's no good way to funnel that info into that same database of issues.

Please, Santa, introduce a switch in php.ini that would make all errors into exceptions - ideally, exceptions I can catch in my code.


问:
oauth 2 authenticate with other authorization server
Let's assume i have a mobile app backed up by a Server. the server is both an Authorization and Resource Server.

Now i want to enable users to register / login to the app using Facebook API. After the user authenticated through Facebook he gets an AccessToken. now i have few options:

send the accessToken to my authorization server (with user fbId), make sure it's a real accessToken, store the accessToken as the user authentication token and manage the Oauth2 autherization process using that accessToken with My Authorization server.

same as the other but create after authenticating in the server side, create new accessToken with an optional refreshToken and never use the facebook AccessToken again (only to retrieve information from Facebook)

on each call to my resource server, user the Facebook authorization server (please let it not be the answer (-;)

Also if someone is familiar with a blog post / online resource that discuss such a situation please let me know ( i've failed to find one )

答:
To log in into your application with Facebook account:

Authenticate the client with Facebook API, getting user access token as a result. At this point your client is sure about user identity, but your server is not yet.

Send user access token to the server. Now server has user access token, but is not sure if it is valid.

Debug the token from the server to make sure it is valid. Here you use your application access token to check user access token. You need to make sure that user token is valid, not expired, and was issued for your application. If it is OK, your server now is also sure about user identity.

From now on, don't use Facebook user access token, unless you need some data from Facebook account. Instead, use normal session mechanism: provide some cookie or other custom token, just like you would do with with your own authentication mechanism.

Basically, you just switch your normal username/password check with Facebook user access token check. You do it just once when a session starts.

For additional info, check login security best practices.


问:
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?

答:
The question is specifically asking why do so many exceptions thrown by "system components" (aka standard library classes) not contain useful details.

Unfortunately, most developers do not write the core components in standard libraries, nor are detailed design documents or other design rationale necessarily made public. In other words, we may never know for sure.

However, there are two key points to keep in mind as to why detailed exception information might not be desirable or important:

An exception may be used by calling code in any way: a standard library cannot place constraints on how the exception is used. Specifically, it may be displayed to the user. Consider an array index out of bounds: this may give useful information to an attacker. The language designer has no idea how an application will use the thrown exception or even what type of application it is (e.g. web app or desktop), so leaving out information may be safer from a security perspective.

Exceptions should not be displayed to the user. Instead, display a friendly error message and log the exception to a location an attacker has no access (if applicable). Once the error is identified, a developer should debug through the code, inspecting stack frames and logic paths. At this point, the developer has more information than an exception could ever hope to have.


答:
Why is it that many common exceptions from system components do not contain useful details?

In my experience, there are a number of reasons that exceptions do not contain useful information. I expect that these sorts of reasons would also apply to system components - but I don't know for sure.

Security focused people see exceptions as a source of information leakage (for example). Since the default behavior of exceptions is to display that information to the user, programmers sometimes err on the side of caution.

In C++, I've heard arguments against allocating memory in catch blocks (where at least some of the context to make good messages lies). That allocation is hard to manage, and worse, can cause an out of memory exception there - often crashing your app or leaking memory. It's hard to format exceptions nicely without allocating memory, and that practice may have migrated between languages as programmers do.

They don't know. I mean, there are scenarios where the code has no idea what went wrong. If the code doesn't know - it can't tell you.

I've worked at places where localization concerns prevented putting English only strings into the system - even for exceptions that would only be read by the English speaking support staff.

Some places, I've seen exceptions used more like asserts. They're there to provide a clear, loud message during development that something isn't done, or a change has been done in one place, but not another. These are often unique enough that a good message would be duplicated effort or simply confusing.

People are lazy, programmers more than most. We spend far less time on the exceptional path than the happy path, and this is a side effect.

Are my expectations out of line? Am I using Exceptions wrong that I even notice this?

Kinda? I mean, exceptions should have nice messages, but they're also exceptions. You should be spending your time designing code to avoid exceptional conditions, or writing code to handle exceptional conditions (ignoring the message), not using them as a sort of interactive feedback mechanism when coding. It's unavoidable to use them for debugging purposes, but in most situations that should be kept to a minimum. That you notice this problem makes me concerned that you're not doing a good enough job at preventing them.

Title: Why do many exception messages not contain useful details?

Body:
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?