问:
Is Java package level scope useful?
I understand the idea of package scope, and at times have even thought I wanted it.  However, every time I set down with a serious intent to try using it I discovered it did not fit the needs I thought it would serve.

My main issue always seems to be that the things that I wish to limit the scope of are never in the same package.  They may conceptually all be linked, but the logical division of data within the application has them as separate child packages of a larger package.

For instance I may have a Mission model and I want only other Mission tools, like my missionServices, to use some methods.  However, I end up with Missions.models and Missions.services as my packages, so the MissionModel and MissionService are not the same package scope.  It never seems like there is a situation where packages appropriately contain the things that I would want to have elevated permissions without also included numerous things I do not wish to have those permissions; and rarely do I feel the advantage of package scoping a method justifies modifying my project architecture to place everything in the same package.  Often either Aspects or some sort of inversion of control turn out to be the better approach to whatever problem I briefly considered package scoping for.

I'm curious rather this is generally considered true across all Java developers, or is just a fluke of the work I do.  Is package scope utilized much in the real world?  Are there many cases where it's considered good form to use, or is it seen mostly as a legacy behavior to rarely be exploited in modern development?

I am not asking anything about why package private scope is default, I'm asking when it should be used regardless of the defaults.  Most discussions as to why it is default don't really get into when package scope is actually useful, instead arguing simply for why the other two commonly used scopes should not be default so package wins by process of elimination.  In addition, my question is about current state of development.  Specifically, have we developed to the point where other tools and paradigms make package scope less useful then it was back when the decision to make it default made sense.

答:
Throughout the java.util.* package there are instances where code is written with package level protection.  For example, this bit of java.util.String - a constructor in Java 6:

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
}
```

<p>or this getChars method:</p>

```/** Copy characters from this string into dst starting at dstBegin.
    This method doesn't perform any range checking. */
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, offset, dst, dstBegin, count);
}
```

The reason for this is that the designers of the code (and java.util.* can be thought of as a rather large library) wanted the ability to have faster performance at the cost of a loss of various safety (range checks on arrays, direct access to other fields that imply the implementation rather than the interface, 'unsafe' access to parts of the class that are otherwise considered to be immutable via public methods).

By restricting these methods and fields to only be accessed by other classes in the java.util package, it makes for closer coupling between them but also avoids exposing these implementation details to the world.

If you are working on an application and don't have need to worry about other users, package level protection isn't something you need to worry about. Other than various aspects of design purity, you could make everything public and be ok with that.

However, if you are working on a library that is to be used by others (or want to avoid entangling your classes too much for later refactoring), you should use the strictest level of protection afforded to you for your needs.  Often this means private. Sometimes, however, you need to expose a little bit of the implementation details to other classes in the same package to avoid repeating yourself or to make the actual implementation a bit easier at the expense of the coupling of the two classes and their implementations.  Thus, the package level protection.

Title: Is Java package level scope useful?

Body:
Throughout the java.util.* package there are instances where code is written with package level protection.  For example, this bit of java.util.String - a constructor in Java 6:

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
}

or this getChars method:

/** Copy characters from this string into dst starting at dstBegin.
    This method doesn't perform any range checking. */
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, offset, dst, dstBegin, count);
}

The reason for this is that the designers of the code (and java.util.* can be thought of as a rather large library) wanted the ability to have faster performance at the cost of a loss of various safety (range checks on arrays, direct access to other fields that imply the implementation rather than the interface, 'unsafe' access to parts of the class that are otherwise considered to be immutable via public methods).

By restricting these methods and fields to only be accessed by other classes in the java.util package, it makes for closer coupling between them but also avoids exposing these implementation details to the world.

If you are working on an application and don't have need to worry about other users, package level protection isn't something you need to worry about. Other than various aspects of design purity, you could make everything public and be ok with that.

However, if you are working on a library that is to be used by others (or want to avoid entangling your classes too much for later refactoring), you should use the strictest level of protection afforded to you for your needs.  Often this means private. Sometimes, however, you need to expose a little bit of the implementation details to other classes in the same package to avoid repeating yourself or to make the actual implementation a bit easier at the expense of the coupling of the two classes and their implementations.  Thus, the package level protection.


问:
Should the ternary operator be used outside of assignment statements?
Edit This isn't a question of whether or not the ternary operator is harmful. It's about whether or not there's a consensus about whether or not it should be used outside of assignment statements. /Edit

Based on a boolean, I want to call one of two different functions (with no return value). I wrote this bit of javascript:

```<code>(condition) ? doThis(arg) : doThat(arg)
</code>```

Which I think looks cleaner than writing out an if-else statement:

```<code>if(condition) {
    doThis(arg);
}
else {
    doThat(arg);
}
</code>```

My colleagues strongly believe ternary statements should only be used in assignment statements. I can't find style guides that discuss this, probably because languages like Java and C# don't allow this at all (their compilers require ternary operators to return a value). Should this be considered a bad use of the ternary statement? Why?

答:
A couple of cases, that are not assignments, where I find ternary operators useful are:

In function arguments: in my opinion

```<code>f( e1, .. cond ? em : dm, .. en);
</code>```

is less error prone than

```<code>if ( cond) f( e1, .. em, .. en); else f( e1, .. dm, .. en);
</code>```

When you want to call one function or another with identical arguments: again I find

```<code>(cond ? f : g)( /* long and complex argument list */);
</code>```

less error prone than

```<code>if ( cond) f( /* long and complex argument list */);
else g( /* long and complex argument list */);
</code>```

As I see it the key thing in each case is that the ? form has less repetition.  Repetition opens up the possibility of changing one instance and forgetting to change the other.

ContentLicense: CC BY-SA 3.0

Body:
A couple of cases, that are not assignments, where I find ternary operators useful are:

In function arguments: in my opinion

f( e1, .. cond ? em : dm, .. en);

is less error prone than

if ( cond) f( e1, .. em, .. en); else f( e1, .. dm, .. en);

When you want to call one function or another with identical arguments: again I find

(cond ? f : g)( /* long and complex argument list */);

less error prone than

if ( cond) f( /* long and complex argument list */);
else g( /* long and complex argument list */);

As I see it the key thing in each case is that the ? form has less repetition.  Repetition opens up the possibility of changing one instance and forgetting to change the other.


答:
Sometime i escalate the visibility of private or protected methods to package
to allow a junit-test to access some implementation detail that should no be accessed from outside.

since the junit-test has the same package as item-under-test it can access these implementation details

example

```<code>  public class MyClass {
    public MyClass() {
        this(new MyDependency());
    }

    /* package level to allow junit-tests to insert mock/fake implementations */
    MyClass(IDependency someDepenency) {...}
  }
</code>```

It is debatable if this is a "good" usage or not but it is pragmatic

Title: Is Java package level scope useful?

Body:
I understand the idea of package scope, and at times have even thought I wanted it.  However, every time I set down with a serious intent to try using it I discovered it did not fit the needs I thought it would serve.

My main issue always seems to be that the things that I wish to limit the scope of are never in the same package.  They may conceptually all be linked, but the logical division of data within the application has them as separate child packages of a larger package.

For instance I may have a Mission model and I want only other Mission tools, like my missionServices, to use some methods.  However, I end up with Missions.models and Missions.services as my packages, so the MissionModel and MissionService are not the same package scope.  It never seems like there is a situation where packages appropriately contain the things that I would want to have elevated permissions without also included numerous things I do not wish to have those permissions; and rarely do I feel the advantage of package scoping a method justifies modifying my project architecture to place everything in the same package.  Often either Aspects or some sort of inversion of control turn out to be the better approach to whatever problem I briefly considered package scoping for.

I'm curious rather this is generally considered true across all Java developers, or is just a fluke of the work I do.  Is package scope utilized much in the real world?  Are there many cases where it's considered good form to use, or is it seen mostly as a legacy behavior to rarely be exploited in modern development?

I am not asking anything about why package private scope is default, I'm asking when it should be used regardless of the defaults.  Most discussions as to why it is default don't really get into when package scope is actually useful, instead arguing simply for why the other two commonly used scopes should not be default so package wins by process of elimination.  In addition, my question is about current state of development.  Specifically, have we developed to the point where other tools and paradigms make package scope less useful then it was back when the decision to make it default made sense.

Body:
Sometime i escalate the visibility of private or protected methods to package
to allow a junit-test to access some implementation detail that should no be accessed from outside.

since the junit-test has the same package as item-under-test it can access these implementation details

example

  public class MyClass {
    public MyClass() {
        this(new MyDependency());
    }

    /* package level to allow junit-tests to insert mock/fake implementations */
    MyClass(IDependency someDepenency) {...}
  }

It is debatable if this is a "good" usage or not but it is pragmatic


问:
Is catching general exceptions really a bad thing?
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:

CA1031: Do not catch general exception types

I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change.

For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

Maybe a better example:

```<code>public void Foo()
{
    // Some logic here.
    LogUtility.Log("some message");
}

public static void Log()
{
    try
    {
        // Actual logging here.
    }
    catch (Exception ex)
    {
        // Eat it. Logging failures shouldn't stop us from processing.
    }
}
</code>```

If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException?

答:
Maybe. There are exceptions to every rule, and no rule should be followed uncritically. You example might conceivably be one of the instances where it makes sense to swallow all exceptions. For example if you want to add tracing to a critical production system, and you want to make absolutely sure that you changes don't disrupt the main task of the app.

However, you should think carefully about possible reasons for failure before you decide to silently ignore them all. For example, what if the reason for the exception is:

a programming error in the logging method which causes it to always throw a particular exception

an invalid path to the logging file in the configuration

the disk is full

Don't you want to be notified immediately that this problem is present, so you can fix it? Swallowing the exception means you never know something went wrong.

Some problems (like the disk is full) might also cause other parts of the application to fail - but this failure is not logged now, so you never know!


问:
How can I create an abstract parent class which uses data from an inherited class?
I'm getting my feet wet with Android app development and tying to find a good way to manage database interactions across multiple similar objects. My goal was to have a structure like:

```<code>public abstract class DatabaseObject{

    public static abstract String getTableName();
    public static abstract SQLiteDatabase getDB();
    public static void dropTable(){
        getDB().execSQL("DROP TABLE IF EXISTS " + getTableName());
    }
}

public class Book extends DatabaseObject{

    public static final String TABLE_NAME = "book";
    private String author;
    private static SQLiteDatabase _db;

    public static setDB(SQLiteDatabase db){
        _db = db;
    }

    @Override
    public static String getTableName(){
        return TABLE_NAME;
    }

    @Override
    public static SQLiteDatabase getDB(){
        return _db;
    }

    public String getAuthor(){
        return author;
    }

    public void getAuthor(String auth){
        author = auth;
    }
}
</code>```

Lately I've been working on a project that uses Hibernate, so I'm used to having a class that can be used throughout the application and also contains the ability to persist its data to the database. Unfortunately, "static abstract" isn't allowed in Java, so this wouldn't work.

My current plan is to have each of the classes like "Book" that I plan to use implement an interface and have an external class handle the common db interactions instead of the ancestor class.

Is there a better way to accomplish what I'm trying to do?

答:
Easy.

Pass the table name from Book (and all other concrete classes) into a constructor of the abstract class.

Store the table name in the abstract class and use it directly where needed.

Remove the getTableName method

Sorry my answer is so brief, I'm editing in the mobile app.


问:
Designing a ticketing system where the User and Administrator have similar but different functionality
I am designing a simple ticketing system in Laravel 4. The system will simply allow a User to create a ticket, and an Administrator to answer it.

The User will be able to:

View a list of his tickets.

Create a new ticket.

View the replies to one of his own ticket.

Add a reply to a one of his own ticket.

Close a one of his own ticket.

Perform the above tasks via the url www.example.com/support

The Administrator will be able to:

View a list of all tickets.

Cannot create a new ticket.

View the replies to any ticket.

Add a reply to any ticket.

Close any ticket.

Perform the above tasks via the url www.example.com/admin/support

In other words, a User and Administrator can perform very similar, but different functionality. What are ways that I can design this system to reduce the amount of copying and pasting that must be done?

So far, I have came up with two possibilities.

Create two sets of Routes with two Controllers - one for the user and one for the admin. Copy and paste most of the logic between the Controllers, but changing a few variables so that users can only see his own tickets. Both Controllers share the same Views and Model. Add in an additional check in the Views so that the admin do not see a button to create a new ticket.

The down side of this is that I have to put logic in the Views in order to hide certain things from the admin, and other things from the user. I am also copying and pasting code between controllers.

Create two sets of Routes but use the same Controller. Use if statements in the Controller to show different Views depending on whether it is a User or an Administrator.

However, now I am copying and pasting code between views. Having two different set of logic in the same Controller may be a bit confusing as well.

Is there a better way to go about this?

答:
Did you look at role-based permissions?
One controller, one route, returns/accepts different results depending on a user role.

E.g. a GET request to http://blah.com/tickets will return all tickets if requester is an admin, or user's own tickets otherwise.
A post to this route will return 200 for user, but 40x error (405 would fit here, I think?) for administrator.
Etc.


问:
behaviour of SQL BETWEEN operator
This is kind of philosophical question...

Today i spent way too much time to debug a method which was generating a SQL command.

I figured out the error was because the code was generating something like:

```<code>WHERE X BETWEEN 10 AND 5
</code>```

which wasn't returning any value, while the correct form was:

```<code>WHERE X BETWEEN 5 AND 10
</code>```

My question is, if you can use the BETWEEN syntax which is more close to the natural language than WHERE X >= lowerBound AND X <= upperBound wouldn't make sense to have designed it to automatically detect which is the lower bound and the upper bound?

I mean, if i say i want numbers between 10 and 5 or between 5 and 10 in a natural language i guess everyone would tell me the number in the interval [5,10]

Am I pretending too much from sql ?

答:
Indeed, you are asking too much from your database.

Databases are designed for DBAs and developers. Those are not the sort of persons who would usually consider that a..b = b..a in a context of a database or a program, and would naturally tend to put the minimum first, and the maximum second.

Probably for that reason, the designers of the database you are using considered that the inverse, that is a..b with a > b, constitutes an edge case which is not worth special treatment. After all, the goal of the database engine is to be hugely fast, and that means removing edge cases from the code.

Less code means less risks of an error within it, less debugging, less logging, less testing and, ultimately, less CPU cycles and memory usage.

If the same persons were designing not a database, but a product targeting ordinary users, they may have taken the opposite decision, considering that a simple user would consider that “a is between b and c” is exactly the same as “a is between c and b”.

How did they decide when creating the spec? Maybe they made an educated guess. Maybe they couldn't care less and considered that they don't want to write more code. Or maybe they actually observed programmers using their database engine, and determined that the frequency of the mistake you did is too small to care about. For the same reason, many databases ten years ago would respond faster to select a, b from c than select * from c, but this is not always true any longer: by watching thousands of programmers using * when they shouldn't, designers of some database engines ended up handling this case specifically in order to give the same or very similar performance for both queries.

Title: behaviour of SQL BETWEEN operator


问:
Should Objects with lots of fields be broken up?
When I have an Object that has lots of fields is it better to have them all as fields or try to find logical groupings as their own Objects and make those the fields?

I guess it comes down to which is the greater evil, too many Objects or too many fields in an Object.

Less Objects, more fields:

```<code>public class LotsOfFields Object {

    private Foo foo;
    private Bar bar;
    private Baz baz;
    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

More Objects, less fields:

```<code>public class LessFields Object {

    private ClicheMetaSyntacticVariables vars;
    private Animals animals;

    // Getters and setters...

}

public class ClicheMetaSyntacticVariables {

    private Foo foo;
    private Bar bar;
    private Baz baz;

    // Getters and setters...

}

public class Animals {

    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

As an aside, if the "more Objects" approach is better, is it better to have the classes as members of the original class (assuming they'd never be used elsewhere) or does that defeat the purpose of not cluttering an Object?

Edit to defend my question not being a duplicate: This is about a more specific issue than "what is the purpose of a class" and to me that alone is enough. To go on, I am really talking more about what makes a more readable/usable class, I'll take the blame for not specifying that though.

答:
The important figure is complexity, not pure object/member count. You can have a simple class with roughly up to 20 members (that's already really smelly, though), and you can have a much too complex class with only five.

Anyway, just grouping members by type won't help. The questions are: Which members have to work together? And, which sub-services can they provide? These questions are important, because you want your small objects to provide good abstractions that actually simplify things in the class that binds them together, not just containers for your data members.

(foo.bar.baz is a codesmell in and of itself!)


问:
Flux Pattern dispatcher broadcast
I'm trying to get a better understanding of the flux pattern Facebook introduced a while ago.

From what I understand the dispatchers dispatches every payload to all registered callbacks. Does anyone know what the main motivation behind this broadcast is? Why not use something more like an observer pattern and only send the actions to specific stores? Or am I misunderstanding something?

答:
When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected.

For an example let's say we have two views: menu and content. They represent typical main menu and content area of a web page. When a menu item is clicked it triggers events through the dispatcher. The events are received and handled by the stores updating their data as needed. The stores then notify the views that they should rerender themselves.

As you said, the stores receive all the events from the dispatcher. As a benefit, this design is simple and needs no configuration per store. There is no need to register observers to receive events. And with observer you would also need to filter the events. The number of events dispatched is not an issue because there is one-to-one relation with views and stores and typically you have only a handful of views in the application. IMHO the observer design in this case would be far worse.

Title: Flux Pattern dispatcher broadcast


答:
I guess it comes down to which is the greater evil, too many Objects or too many fields in an Object.

It depends.

The greater evil is having classes do too many things or too many classes for one thing.

In your example, it looks like you have three distinct groupings that have nothing to do with each other. So those shouldn't be the same class. But if all were very related and interact, then there is less problem having them in the same class.

And each example will be different. There's no universal "do this in every case" policy.

Basically, good design should drive which members go in each class. You shouldn't be designing your classes based around making sure you have an arbitrary max of 5 objects/class, for example.

Title: Should Objects with lots of fields be broken up?

Body:
When I have an Object that has lots of fields is it better to have them all as fields or try to find logical groupings as their own Objects and make those the fields?

I guess it comes down to which is the greater evil, too many Objects or too many fields in an Object.

Less Objects, more fields:

```<code>public class LotsOfFields Object {

    private Foo foo;
    private Bar bar;
    private Baz baz;
    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

More Objects, less fields:

```<code>public class LessFields Object {

    private ClicheMetaSyntacticVariables vars;
    private Animals animals;

    // Getters and setters...

}

public class ClicheMetaSyntacticVariables {

    private Foo foo;
    private Bar bar;
    private Baz baz;

    // Getters and setters...

}

public class Animals {

    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

As an aside, if the "more Objects" approach is better, is it better to have the classes as members of the original class (assuming they'd never be used elsewhere) or does that defeat the purpose of not cluttering an Object?

Edit to defend my question not being a duplicate: This is about a more specific issue than "what is the purpose of a class" and to me that alone is enough. To go on, I am really talking more about what makes a more readable/usable class, I'll take the blame for not specifying that though.


答:
It's not all that useful, especially as a default, in a world where people tend to use the dotted names of packages as if they were sub-packages. Because Java has no such thing as a sub-package, so x.y.internals has no more access to x.y than it does to a.b. Package names are either the same or different, a partial match is no different from having nothing in common.

I guess the original developers never expected that convention to be used, and wanted to keep things simple without adding the complexity of Ada-style hierarchical packages.

Java 9 is sort of addressing this, in that you can put several packages in a module and only export some. But that will make the package scope even more redundant.

In an ideal world, they would change the default scope to 'module scope, if a containing module exists, otherwise package scope'. Then you can use it for sharing implementation within a module, allowing refactoring without breaking exported interfaces. But maybe there is some subtlety why that would break backwards compatibility, or be otherwise bad.

Title: Is Java package level scope useful?


问:
Are "technical user stories" allowed in Scrum?
Are technical user stories allowed in Scrum? If so, what is the standard template for writing technical user stories in Scrum?
Is it the same As a <user> I want to do <task> so that I can <goal> ??

I have read in some blogs that as-a-developer-is-not-a-user-story,
but I have also read that Scrum does not mandate these.  There are few blogs where they have shared user stories with system as user, its like as a <user who is not end user> i want to <system functionality> so that <some techinical thing>. So which one is the standard?

For instance, there are user stories like:

As a reviewer I want to upload photos of any hotel/food so that other users can see and like them

As a user I want to add photo comments so that I can explain my view better

Now for both these user stories, there is a big technical item - Saving and retrieving the image

So can I add a technical story titled "Image storing and retrieving mechanism", with the following description?

As a developer I want to develop a mechanism to store and retrieve images so that users can add/view images wherever required

答:
This is a good question. I don't have an official answer but where I work we add technical user stories and call them technical debt. If they weren't permitted, I would find some other way to get them added for the mere purpose of having my work recorded and communicated to the business. Likewise, having this documentation reminds us of what is needed for future projects.

As an example, the disconnect in a new application, if we're not allowed to add technical stories, is that I'll be humming along for a week after the start of a sprint creating database  models and waiting for my data modeler to approve them, iterate w/ the modeler and when done send the scripts to the dba and wait for them to create the db objects. In the meantime, I'll create a new code project, some base ORM functionality, and my source control layout and when all is said and done I'll have time to create one blank landing page and deploy.

Day by day while this is going on, if I don't record the info, the business is clambering that our team is not working on the project when in fact we are. Having these items in the stories means that we can check off our work, have documented work, and communicate to the business that we're making progress.

If there's a better best practice to do this I'm all ears.


问:
How to write a good exception message
I'm currently doing a code review and one of the things I'm noticing are the number of exceptions where the exception message just seems to reiterate where the exception occurred. e.g.

```<code>throw new Exception("BulletListControl: CreateChildControls failed.");
</code>```

All three items in this message I can work out from the rest of the exception. I know the class and method from the stack trace and I know it failed (because I've got an exception).

It got me thinking about what message I put in exception messages. First I create an exception class, if one does not already exist, for the general reason (e.g. PropertyNotFoundException - the why), and then when I throw it the message indicates what went wrong (e.g. "Unable to find property 'IDontExist' on Node 1234" - the what). The where is in the StackTrace. The when may end up in the log (if applicable). The how is for the developer to work out (and fix)

Do you have any other tips for throwing exceptions? Specifically with regard to the creating new types and the exception message.

答:
As a general rule, an exception should help developers pinpoint the cause by giving useful information (expected values, actual value, possible causes/solution, etc.).

New exception types should be created when none of the built-in types make sense. A specific type enables other developers to catch a specific exception and handle it. If the developer would know how to handle your exception but the type is Exception, he won't be able to handle it properly.

ContentLicense: CC BY-SA 2.5

Title: How to write a good exception message


问:
Explaining new or uncommon syntax in comments
As per the title, should I be explaining syntax that I use in my code when I have a reasonable expectation that a developer looking at my code in the future will not be familiar with it? Short caveats or explanations could be added in-line while more complex constructions would be referred to by name and version number to allow a quick lookup in the documentation.

The two main reason they might not understand the syntax are because it's a new addition to the language or it's syntax that is rarely used by "average" developers. Assume that using this syntax is the recommended approach and not about me wanting to write fancy code. (No, I'm not XOR swapping in high-level languages.)

On the one hand, comments are there to facilitate maintenance and if I provide that explanation I could save a future developer a lot of effort and reading. On the other hand, I could argue that syntax documentation is readily available and that any decent developer could be expected to keep up to date on new developments or, failing that, shouldn't have any trouble figuring it out using the tools (IDE help) and documentaiton available to him.

For context, this question was prompted by recent updates to SAP's ABAP syntax which adds new grouping and filtering mechanics to loops and a number of other statements. Many legacy developers and client-side maintenance teams won't be familiar with this syntax for years (if ever).

For this question, assume that commenting your code is a good practice.

As csw comments, one option is to simply not use this new syntax until the maintainers have caught up, but as I hinted, some of those maintainers simply won't ever catch up. In my industry maintenance of the code is often handed over to small in-house developers once the project is delivered and they can be notorious for being stuck in "legacy mode". Writing functionally obsolete code as a crutch for out-of-touch programmers just doesn't seem like a good or defensible practice.

In my particular situation, the ABAP syntax updates offer some dramatic performance and readability improvements. They introduce a number of common modern operations to the ancient ABAP language like casting operators. The GROUP BY I linked is another good example that replaces complex, illegible and bug-prone code with a simple alternative. For a concrete syntax example, I can replace

```<code>READ TABLE itab WITH ... TRANSPORTING NO FIELDS.
IF sy-subrc = 0.
    ...
ENDIF.
</code>```

with:

```<code>IF line_exists( itab[ ... ] ).
    ...
ENDIF.
</code>```

For those interested, this PDF covers many of the new features. Slide 29 and 30 offer two good example of how drastic the difference can be.

Regarding the suggested duplicate, there are some useful answers there but my question covers a more specific case. You could probably summarise my question as "Should I ignore the document *why* rather than *how* paradigm when when doing so might greatly simplify maintenance for inexperienced developers?".

答:
In one respect I think this is a bit of an X-Y problem.

For the sake of my example I'd like anyone reading this to consider C++'s recent C++11 overhaul. In particular I would like to focus on constexpr. It's purpose is to allow certain functions to be run by the compiler (e.g. a factorial function) at compile time, thus preventing constant values having to be calculated at run-time.

Say for argument's sake that I am in a dev team full of C++ developers who haven't read about any of the C++11 features (let's say we're in 2012 to make this scenario a bit more realistic). I take our int factorial(int n) function and add constexpr. Now I have to document this. Do I write a comment explaining why I've added constexpr or does that sort of thing really belong on the project change log?

I would argue that comments are for explaining the current state of the code, not the changes it has gone through. You do not leave a comment for every bug you have removed, you make a note of it in a change log or an error log. Likewise the reasons for making factorial a constexpr should be expressed in the changelog.

The comment should still be changed however as I have changed the behaviour of the function. It no longer operates at run-time but instead runs at compile-time. Hence I change the comment from //Calculates the result of the factorial operation to //Calculates the result of the factorial operation at compile time.

"Aha, you have just explained the feature" I hear people think. No I have not. What I have done is make the comment describe the behaviour of the function. What I have not done is explain all the caveats involved in the use of constexpr (i.e. I have not explained in what situations applying constexpr to a function results in a compilation error).

Had I changed some syntax to use a more readable form, I would not be documenting such a change in a comment because I would not have changed the behaviour of the code itself. Instead I would be documenting the change in the change log.

Now in response to some specific points:

assume this syntax is the recommended approach

If it is the recommended approach it should be used. The only reasons to not use it would be if it breaks something or is not yet widely supported by the tools you use (such as some of C++11's features).

On the one hand, comments are there to facilitate maintenance and if I
  provide that explanation I could save a future developer a lot of
  effort and reading.

And deprive them of learning the full ins and outs of a language feature? You don't give someone a spanner and leave out the fact it's adjustable. If one of the other coders misses an important fact because they've read your summary instead of the full caveats of a syntax feature then it will effectively be your fault if they introduce a bug because of it. Sure it will be their fault for not reading the documentation, but why didn't they read it? Because they learnt about the feature through a comment.

once the project is delivered and they can be notorious for being
  stuck in "legacy mode"

And by forcing them to read the documentation you are forcing them out of this habit. This is a good thing™. For what it's worth I downloaded the pdf, the new syntax is much more in line with modern thinking. Again, this is a good thing™, you should be encouraging the adopting of new features when they improve readability, performance or maintainability of your code. Time spent reading documentation is never a waste if the reader learns something.

ContentLicense: CC BY-SA 4.0


答:
As always, it depends. I don't see why would it be wrong. I had classes with as many fields, maybe even more, in a project which scrapped data from a website, so one page was one object (lots of data + some calculated values to speed up things across multiple runs). They were perfectly related to each other.

If fields contained in one class have little to do with each other, it may be a sign of bad design.

It's a red flag, certainly, but a red flag never killed anybody by itself, right? If it makes sense, go for it.


答:
Note: I am not very familiar with ABAP, so I am answering as if someone asked about using lambdas in Java, in the understanding that the issue is similar (AFAIK it is). If I am wrong, please inform me.

This does not belong to comments (part of the code) as it is an specification issue of the project. In fact, it should not be a programmer who decides to use the new features, but the project manager or even the product owner who will decide which version/s of ABAP the project should be compatible with.

Somewhere in the project documentation should be written something like "Supports ABAP X". Now:

If X is 1990, you should not use any features that are not compatible with ABAP 1990. If you feel that those new features give so much added value that a change of X to 2015 is desirable, talk to the people in charge of doing that decission so they update the project specs (or not).

If X is 2015, any new programmer will know that they must have some knowledge of the new features just to be able to read the code, it is up to them to learn (or request formation for) such a version of the language, if they are not still familiar with it.

Title: Explaining new or uncommon syntax in comments

Body:
As per the title, should I be explaining syntax that I use in my code when I have a reasonable expectation that a developer looking at my code in the future will not be familiar with it? Short caveats or explanations could be added in-line while more complex constructions would be referred to by name and version number to allow a quick lookup in the documentation.

The two main reason they might not understand the syntax are because it's a new addition to the language or it's syntax that is rarely used by "average" developers. Assume that using this syntax is the recommended approach and not about me wanting to write fancy code. (No, I'm not XOR swapping in high-level languages.)

On the one hand, comments are there to facilitate maintenance and if I provide that explanation I could save a future developer a lot of effort and reading. On the other hand, I could argue that syntax documentation is readily available and that any decent developer could be expected to keep up to date on new developments or, failing that, shouldn't have any trouble figuring it out using the tools (IDE help) and documentaiton available to him.

For context, this question was prompted by recent updates to SAP's ABAP syntax which adds new grouping and filtering mechanics to loops and a number of other statements. Many legacy developers and client-side maintenance teams won't be familiar with this syntax for years (if ever).

For this question, assume that commenting your code is a good practice.

As csw comments, one option is to simply not use this new syntax until the maintainers have caught up, but as I hinted, some of those maintainers simply won't ever catch up. In my industry maintenance of the code is often handed over to small in-house developers once the project is delivered and they can be notorious for being stuck in "legacy mode". Writing functionally obsolete code as a crutch for out-of-touch programmers just doesn't seem like a good or defensible practice.

In my particular situation, the ABAP syntax updates offer some dramatic performance and readability improvements. They introduce a number of common modern operations to the ancient ABAP language like casting operators. The GROUP BY I linked is another good example that replaces complex, illegible and bug-prone code with a simple alternative. For a concrete syntax example, I can replace

```<code>READ TABLE itab WITH ... TRANSPORTING NO FIELDS.
IF sy-subrc = 0.
    ...
ENDIF.
</code>```

with:

```<code>IF line_exists( itab[ ... ] ).
    ...
ENDIF.
</code>```

For those interested, this PDF covers many of the new features. Slide 29 and 30 offer two good example of how drastic the difference can be.

Regarding the suggested duplicate, there are some useful answers there but my question covers a more specific case. You could probably summarise my question as "Should I ignore the document *why* rather than *how* paradigm when when doing so might greatly simplify maintenance for inexperienced developers?".


问:
PHP objects with configurable data interfaces
I have a User class which needs to load data from a variety of sources, e.g. the main user database, WordPress user metadata, authorizations from another app, etc. For the sake of organization, I want to separate out those different data loaders into their own classes. Calls to $user->get_name() would appropriately delegate down to whatever backend object provides this information.

How might this look in PHP? Is there a name for this pattern? (And hopefully it's not an anti-pattern.)

I can anticipate people suggesting some embedded objects, like $user->wordpress as an interface to the WordPress loader. I have an additional complicating factor, that not all users are present in all of our data stores. My loaders are able to identify if they understand and have data for a given username/id, and they're loaded into the User object with a priority level. A given identifier may only trigger a subset of data loaders, so $user->get_name() essentially is a consistent interface to user data, wherever it's stored.

I'm evaluating my setup in an effort to make things more testable, and I believe this is an appropriate first step.

答:
Hey maybe you could implement a Composite pattern, looking something like:

The component execute() method could call al its datasources and so on till you reach a basicDatasource witch may have another hireachy, representing each source.

Now back to you needs, the get_name() function could look like:

```<code>public function get_name()
{
  $datasource = $this->getDataSourcesForName();
  return $datasource->execute();
}
</code>```

Also a strategy patter may apply.

Hope this helps!

Body:
Hey maybe you could implement a Composite pattern, looking something like:

The component execute() method could call al its datasources and so on till you reach a basicDatasource witch may have another hireachy, representing each source.

Now back to you needs, the get_name() function could look like:

public function get_name()
{
  $datasource = $this->getDataSourcesForName();
  return $datasource->execute();
}

Also a strategy patter may apply.

Hope this helps!


问:
Is it a good idea to modify the array keys in foreach
Some times I need to modify an array key for example something like:

$temp = array();
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2) == 0) {
        $temp['odd_' . $key] = $value;
    } else {
        $temp[$key] = $value;
    }
}
```

<p>I always use a temp array to achieve that, but I had a memory problem when working on a project that had some big arrays. Of course the best solution is to increase the memory but, but i was just wondering is it so bad to just do it like:</p>

<pre class="lang-php prettyprint-override"><code>foreach($arrayIWantToModify as $key => $value) {
    if(($value % 2) == 0) {
        $arrayIWantToModify['odd_' . $key] = $value;
        unset($arrayIWantToModify[$key]);
    }
}
</code>```

It seems to work but I always saw it as a bad practice because you are changing an array you are iterating.

答:
I would agree that this is not a good idea. Even if the language you're using defines what should happen in this situation (I don't know if PHP does; that's a question for StackOverflow) most people who see code like this would still have to look up whether or not it's defined behavior before they could have any confidence in it.

If the list of desired modifications is typically much smaller than the array being modified, I would always prefer using a temporary array to contain the desired modifications until the iterating is complete, just like your first example. If you're running out of memory doing that, that tells me you're modifying such a huge portion of the array that you'd be better off with a map operation (I believe PHP calls it array_map) that's designed to efficiently modify all elements without any risk of processing an element more or less than one time.


问:
Performance of list concatenation followed by scanning
Consider the following code snippet:

```<code>-- list_1 = [1, 2, 3]
-- list_2 = [4, 5, 6]
final_list =  list_1 ++ list_2
result = map (+1) final_list
</code>```

Is the time spent by it proportional just to the length of final_list, and the price of list concatenation is not paid?

My idea is that concatenation is done lazily; to quote the source of GHC Base.hs,

```<code>(++) :: [a] -> [a] -> [a]
(++) []     ys = ys
(++) (x:xs) ys = x : xs ++ ys
</code>```

Since map constantly chips away the head of the list, I suppose that the concatenation as done by the recursive call in the last line is always done in lockstep with the map execution, so list_1 is effectively scanned only once.

Is this correct?

答:
That's correct.  It's easy to test your theory by making list_2 infinite:

```<code>list_1 = [1, 2, 3]
list_2 = repeat 4
final_list = list_1 ++ list_2
result = map (+1) final_list

print $ take 10 result
-- Outputs [2,3,4,5,5,5,5,5,5,5]
</code>```

Congratulations!  You just ran an infinite loop in a few microseconds! (Not really).

Body:
That's correct.  It's easy to test your theory by making list_2 infinite:

list_1 = [1, 2, 3]
list_2 = repeat 4
final_list = list_1 ++ list_2
result = map (+1) final_list

print $ take 10 result
-- Outputs [2,3,4,5,5,5,5,5,5,5]

Congratulations!  You just ran an infinite loop in a few microseconds! (Not really).


问:
Should an application configuration interface be broken into multiple interfaces to reduce feature creep?
My windows service is neatly separated into 5 components - each with their own interface and pulled together by a bootstrapper. One of my requirements is to provide configuration options in my app.config for the different pieces of the application.

I started with the following interface:

```<code>public interface IConfiguration
{
    /// <summary>
    /// The amount of time database records are allowed to be in the system before they're removed.
    /// </summary>
    TimeSpan OldSignalValuePurgePeriod { get; }

    /// <summary>
    /// The lowest log level that will be written to the log file.
    /// </summary>
    LogSeverity MinimumLogSeverity { get; }

    /// <summary>
    /// The period of time to wait for a signal metadata response before re-requesting it.
    /// </summary>
    TimeSpan SignalMetadataRerequestPeriod { get; }
}
</code>```

which I'd planned to pass a constructed instance of to each of my components requiring configuration. The thing is, each of the above properties is a configuration option for a different component. There's a very good chance I will be adding some more properties at a later date to this interface. Obviously I'm populating the properties of the interface in the implementing object's constructor by reading the app.config file.

What I'm struggling with is this: since each component doesn't care about the configuration options of the other components, how can I separate this interface into pieces specific to each component that isn't a pain to construct, and one that Jimmy will understand immediately?

I've thought of doing something like this:

```<code>public interface IRepositoryConfiguration
{
    TimeSpan OldSignalValuePurgePeriod { get; }
}

public interface ILoggingConfiguration
{
    LogSeverity MinimumLogSeverity { get; }
}

public interface IDataManagerConfiguration
{
    TimeSpan SignalMetadataRerequestPeriod { get; }
}

public class ConfigurationImplementation
    : IRepositoryConfiguration,
      ILoggingConfiguration,
      IDataManagerConfiguration
{

}
</code>```

where each component takes an instance of their own configuration interface, but I feel like that is overkill and starts to get unmanageable.

Input?

答:
If I could tell everyone who tackles the problem of injecting values from configs into a DI paradigm one thing, it would be this:

You don't have to put all config access through one monolithic dependency. Just because your settings all come from one place under the hood doesn't mean they all belong together, and that you have to persist the config as one giant object all the way through your layers.

I would recommend starting simple and injecting values directly from the config via your bootstrapper. Then if you find a group of several settings you find yourself injecting repeatedly throughout your objects, put them in a class that the bootstrapper populates from config and injects, similar to Doc Brown's answer. However, I would never group them under an IConfiguration. You just don't need to.

OwnerDisplayName: Brandon


答:
The type of cohesion your describing is not really the best example of where you would use package access.   Package is handy for creating components, modules that are interchangable on an interface.

Here is a rough example of a scenario.  Suppose your code was reorganized to be more around functional cohesion and componentization.  Perhaps 3 jars like:

```<code>**MissionManager.jar** - an application which uses the Java Service Provider Interface to load some implementation of missions, possible provided by a 3rd party vendor.

**missions-api.jar** - All interfaces, for services and model
    com...missions
        MissionBuilder.java   - has a createMission method
        Mission.java - interface for a mission domain object
    com...missions.strategy
        ... interfaces that attach strategies to missions ...
    com...missions.reports
        .... interfaces todo with mission reports ....

   **MCo-missionizer-5000.jar** -  provides MCo's Missionizer 5000 brand mission implementation.
       com...missions.mco
                  Mission5000.java - implements the Mission interface.
       com...missions.strategy.mco
              ... strategy stuff etc ...
</code>```

By using package level in the Mission5000.java, you can unsure that no other package, or component such as the MissionManager can tight couple to mission implemetation.  That is only the "3rd party" provided component from "M co" actually creates there own special branded implementation of a Mission.  The Mission Manager must call the MissionBuiler.createMission(...) and use the defined interface.

This way if the Mission implementation component is replaced we know that the implementers of MissionManager.jar didn't bypass the api and use MCo's implementation directly.

Hence we can swap out MCo-missionizer5000.jar with a competing product. (Or perhaps a Mock for unit testing the Mission Manager)

Conversely MCo can do some amount of hidding their proprietary missionizer trade secrets.

(This is related enforcing Instability and Abstractness ideas in components as well.)

Title: Is Java package level scope useful?

Body:
The type of cohesion your describing is not really the best example of where you would use package access.   Package is handy for creating components, modules that are interchangable on an interface.

Here is a rough example of a scenario.  Suppose your code was reorganized to be more around functional cohesion and componentization.  Perhaps 3 jars like:

**MissionManager.jar** - an application which uses the Java Service Provider Interface to load some implementation of missions, possible provided by a 3rd party vendor.

**missions-api.jar** - All interfaces, for services and model
    com...missions
        MissionBuilder.java   - has a createMission method
        Mission.java - interface for a mission domain object
    com...missions.strategy
        ... interfaces that attach strategies to missions ...
    com...missions.reports
        .... interfaces todo with mission reports ....

   **MCo-missionizer-5000.jar** -  provides MCo's Missionizer 5000 brand mission implementation.
       com...missions.mco
                  Mission5000.java - implements the Mission interface.
       com...missions.strategy.mco
              ... strategy stuff etc ...

By using package level in the Mission5000.java, you can unsure that no other package, or component such as the MissionManager can tight couple to mission implemetation.  That is only the "3rd party" provided component from "M co" actually creates there own special branded implementation of a Mission.  The Mission Manager must call the MissionBuiler.createMission(...) and use the defined interface.

This way if the Mission implementation component is replaced we know that the implementers of MissionManager.jar didn't bypass the api and use MCo's implementation directly.

Hence we can swap out MCo-missionizer5000.jar with a competing product. (Or perhaps a Mock for unit testing the Mission Manager)

Conversely MCo can do some amount of hidding their proprietary missionizer trade secrets.

(This is related enforcing Instability and Abstractness ideas in components as well.)


问:
Should we include all relationships in the domain entity?
I have a question on modelling an Entity\Aggregate root in DDD. I am refactoring a project that uses Entity Framework and business logic as services, the services contain lots of logic which I believe should be in entities in DDD.

```<code>public class Contractor
{
   public int Id {get;set;}
   public DateTime ContractStartDate {get;set;}
   public DateTime ContractEnddate {get;set;}
   public string PhoneNumber {get;set;}
   public Address Address {get;set;}
   /*Bunch of other properties */
   public ICollection<Site> ContractorSites {get;set;}
}
public class Site
{
   public int Id {get;set;}
   /*Bunch of other properties */
}
</code>```

Now I am trying to model the Contractor as an Entity. The problem I am facing is with the ContractorSites property. A contractor can have one or more sites associated to him.

Now when I am modelling a contractor as an Entity, should I include this property? If I include this does this mean that every time I want to fetch a contractor's details from the database and create this entity, I will have to fetch the related sites as well?

My question boils down to "should we include all relationships in the domain entity?"

答:
In general, you need more concepts and more relationships between them, or you'll have problems as your modeling expands.

For one, it seems to me that you are missing a notion of Contract.  The notion of start date and end date relate more to the specific contract rather than the contractor (the contract then relates to the contractor).  I think you should make Contractor, Contract, Contract Site all as separate entities -- there may be a single aggregate root for starters, but I suspect you'll eventually make some of these separate roots as well.

Also, you should allow for multiplicities in Contact Information, meaning they should probably also be separated.


答:
A contractor can be assigned to several sites.

A site can have multiple contractors assigned to it.

When you fetch sites for a contractor, will you also fetch each site's associated contractors? And will you then fetch their sites?

Letting the lazy evaluation and reference resolution already implemented in EF do the work for you really pays dividends in terms of time saved. Implementing these relationships by hand in your domain layer over top of Entity Framework is a lot of work for little benefit.

Instead of struggling to answer this question now, I would hold off and let a pattern emerge that shows what kind of relationships are frequently required by your app, or alternatively, wait for a (non-refactor-induced) problem to emerge that requires a tweak to existing design.

I would also consider returning your EF entities to the application layer unless you have a really good reason not to. Although your entities become somewhat cross-cutting concerns, the work required to reimplement and map objects across application layers (especially if there is little to no reuse by other applications) may not be worth it.

Title: Should we include all relationships in the domain entity?

Body:
I have a question on modelling an Entity\Aggregate root in DDD. I am refactoring a project that uses Entity Framework and business logic as services, the services contain lots of logic which I believe should be in entities in DDD.

```<code>public class Contractor
{
   public int Id {get;set;}
   public DateTime ContractStartDate {get;set;}
   public DateTime ContractEnddate {get;set;}
   public string PhoneNumber {get;set;}
   public Address Address {get;set;}
   /*Bunch of other properties */
   public ICollection<Site> ContractorSites {get;set;}
}
public class Site
{
   public int Id {get;set;}
   /*Bunch of other properties */
}
</code>```

Now I am trying to model the Contractor as an Entity. The problem I am facing is with the ContractorSites property. A contractor can have one or more sites associated to him.

Now when I am modelling a contractor as an Entity, should I include this property? If I include this does this mean that every time I want to fetch a contractor's details from the database and create this entity, I will have to fetch the related sites as well?

My question boils down to "should we include all relationships in the domain entity?"


问:
Rewriting a library licensed under AGPL but keeping the public interface
We need a JSON Schema Validator for .NET.
The only library that we found is Newtonsoft Json Schema.
The problem with this library is that has a "strange" AGPL license with limitations, from the site:

AGPL 3.0  : Free with limitations (1000 validations per hour)

Otherwise we should get a commercial license for each developer.
Maybe the management will decide to buy the commercial license but my question is:

If we decide to rewrite it, it is fine/legal to use the same API interface? Basically rewriting all the actual validating code but keeping the same public method and properties name (changing only the namespace).

In other words is the interface of a library also under the AGPL license or only the implementation/algorithm?

答: Doing this would not be a good idea as it could put your company in violation of the license. The license covers all aspects of the source code including the APIs. In addition, if you changed all the code behind the API, it could still be interpreted that the code was derived from the original code and would have to comply with the original licensing.</p>


问:
Best way to design a database interface
This is my situation
I have a website, mobile client and desktop client.

They can all pretty much do the same operations (website might be able to do more now but in the future they might have the exact operation set)

The technologies varies: for website ruby, for desktop c#, for mobile objective c and java

I am wondering about two solutions

1) create an api that will be used for everyone. website, desktop and mobile. Api is the only one that can connect to the database.

2) create an api for dekstop and mobile. Website will connect to the database directly

Personally I like the approach 1) because I think its more modular and I think that its more consistent. I think the downfall is that it might be a little bit harder to test on the web side and that some features might be harder to implement (like oauth). But overall I think its a better choice.

2) is easier for the web programmer obviously but i see some drawbacks like possibly duplicating code for the same thing, not being able to be certain that the same data will be given to all clients (because the code if different) and also we loose some security with direct database access here.

I am wondering what do you guys think? And also how do big companies like facebook do it? They have a similar scenario. I guess because they are so large they might choose a more perfomance based solution like 2) but how large do you have to be before you go into that direction?

答:
I think it depends on complexity of the interface. If the set of calls that you can make against the database is going to be significant, then something like a REST service in front of the database would make sense to limit the server side implementation and support efforts. It will slow things down by being inserted into all flows but it will enable centralized security and performance management efforts. Otherwise, you could make it language specific in the interest of shortened delivery times.

So, the question would be how important performance and latency are and how important is it minimize the short term development effort?

Title: Best way to design a database interface


答:
According to Vaughn Vernon it is best to use entity framework as state objects when designing aggregates when designing aggregates because they are inflexible compared to other ORMs.

With that in mind. Why are you starting with entities? In DDD you need an aggregate root to maintain the consistency boundary. An aggregate root may have entities and value objects.

To address your question. Unless Site is a value object you cannot share a site between multiple contractors. If multiple contractors could logically belong to the same site you need to either make Site an aggregate root and then only store the ID. Or see it as an immutable value object and just store the same copy under multiple aggregates.


问:
When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?
Generally when estimating using an Agile points system on an experienced project team, the points have meaning relative based on past experience - that take into account:

understanding of the business domain

skill and experience of the team

obvious traps in the technical environment (service integrations and environment issues)

So based on the past velocity of the team - you can forecast how long a project is likely to take.

Now imagine a completely new team thrown into a new business problem domain, new technical environment, with unknown skill levels. You can estimate with points, but you have no velocity track record.

Now you can augment this lack of historic velocity with a 'default velocity' - with the caveats that the three factors above are unknown, and so your tolerance for delivery date is much higher.

But is there an agile reason not to do this?

My question is: When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?

答:
In my opinion the velocity during the first sprints is meaningless, because the team is normally busy with other things in the so called Forming and Storming phase. Dealing with velocity from the beginning may frustrate the team members even more. The best time is to bring in velocity during the Norming Phase.

See: Tuckman's Stages of Group Development


问:
btnBack vs backButtonField
For blackberry GUI developement.  I am using the name convention like backButtonField and some of my colleagues are using btnBack.

But sometimes I stuck with the names like loginVerticalFieldManager its a very long name.  At that time vfmLogin looks better

So for GUI components names what convention should I follow?

答:
not being familiar with Blackberry stuff this may be completely unsuitable, but I tend to just use a name, as the type system will tell you what it actually is.

```<code>Button back;
Button forward;
</code>```

Controversial I know.

Title: btnBack vs backButtonField

Body:
not being familiar with Blackberry stuff this may be completely unsuitable, but I tend to just use a name, as the type system will tell you what it actually is.

Button back;
Button forward;

Controversial I know.


问:
What are the differences between Event Sourcing and Service Layer pattern?
I am reading a book on architecting enterprise applications. In this book the Event Sourcing pattern is introduced which can be used as the "command" part of a Command and Query Responsibility Segregation (CQRS) architecture. Event Sourcing is described by Martin Fowler as:

The fundamental idea of Event Sourcing is that of ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.

I am used to applications that use the Service Layer pattern, which I would describe as: changes in the UI call a method, which then triggers the appropriate service call in a middleware layer which delegates the call to the backend where information is updated and notifies the caller of the result.

This description of a Service Layer does, to me, not seem very different from Event Sourcing.

What are the differences between Event Sourcing and the Service Layer pattern?

答:
Those two things do not much have in common, except the fact that also in the Service Layer pattern some kind of "events" may be involved. But that is where commonalities end.

in the "Service Layer pattern", there are different layers calling each other and triggering some system change. But the calls are not necessarily "captured in event objects", nor are the calls necessarily stored anywhere.

in Event Sourcing, there is not necessarily a result notification back to the caller, that is not part of the pattern

Actually, one way of implementing Event sourcing is to let the service layer take the UI calls, encapsulate them in event objects and feed them to the event queue. The service layer can also try to generate an appropriate result notification for the UI. So these two patterns can work perfectly together, but mostly because they are orthogonal.


问:
C++ Runtime and runtime-linking
I was installing boost and I came across an option named "runtime-link". After searching a bit, I came across yet another complex topic: "runtime system"

that according to Wikipedia:

The runtime system is the gateway by which a running program interacts with the runtime environment, which contains state values that are accessible during program execution, as well as active entities that can be interacted with during program execution. For example, environment variables are features of many operating systems, and are part of the runtime environment; a running program can access them via the runtime system. Likewise, hardware devices such as a DVD drive are active entities that a program can interact with via a runtime system.

yet another topic " Runtime enviroment " comes up

the runtime system of the C language is a particular set of instructions inserted into the executable image by the compiler. Among other things, these instructions manage the processor stack, create space for local variables, and copy function-call parameters onto the top of the stack

Based on above statement, is it safe to say that "C++ runtime is basically an API to system-calls for cross platform implementation of C++ keywords and statements" and that "runtime environment is basically OS kernel" (please note that I'm only talking about c++)?

And still I have no clue about runtime-linking and why it can be static or shared? Is it related to static and dynamic libraries? (I'm completely familiar with those, so you don't have to explain that, only relation if there is any) and most of all i am confused due to "runtime hierarchy".

答:
You seem to be confused because “runtime” is both a noun and an adjective. Your question asks about the three distinct concepts of the “run-time environment”, the “language runtime”, and “run-time linking”:

As a noun, the “run-time environment” of a program, or phrased differently: the “environment of a process”, refers to the (changing) state of the outside world. This state is most obviously accessible and modifiable by doing I/O, such as reading or writing {from,to} {terminals,files,block devices,network sockets}. The environment can also include concepts such as the “current working directory” or “environment variables”.

As a noun, a runtime of a programming language refers to the part of a language implementation that provides run-time semantics. This is most visible in interpreted implementations, where the interpreter is the runtime. But standard library functions can also be part of the runtime, such as malloc in C.

Some parts of the runtime might be compiled into the program rather than being accessible via a library. The way how destructors are invoked in C++ would be an example of this – the compiler inserts instructions to destroy stack objects when their scope is left, and instructions to destroy member variables when a class instance is destroyed. Another example of runtime-supplied code is the program entry point, which is not int main(). How the entry point is determined depends on the executable format. But at that real entry point, the compiler will have emitted code that e.g. takes care of initializing static members. This code will then invoke the programmer-supplied main(), but that may be non-trivial in itself. E.g. in C++ this implies dealing with uncaught exceptions, whereas Java has to also spawn the main thread. After main() returns, the runtime has to perform various cleanup, and then communicate the exit code to the OS and terminate the process. Note that complex systems such as languages or frameworks implemented on top of C add more layers to finding the real, user-perceived program entry point.

It is not generally useful to view the OS as part of a language runtime,
but that view changes when writing assembly.
Some assemblers include runtime-like code generation features,
but doing anything interesting usually involves syscalls to the OS kernel. In user space, the point of the C language runtime and its extensions such as POSIX is to abstract over these syscalls and other system-specific details, so that the interface provided by the OS is totaly subsumed by the language runtime interface.

As an adjective, “runtime” in “run-time linking” is used to differentiate dynamic linking from static linking. In nearly all computer-science contexts, the word “dynamic” can be substituted for “run-time” to get the intended meaning. Misusing Ancient Greek words is way cooler than using boring olde English, so we keep on talking about “dynamic typing” or “dynamic linking” or “dynamic dispatch” (in its original sense, “dynamic” means “powerful” or “involving energy”, but via the meaning “changing” it seems to have arrived at its current computer science-specific meaning).

Title: C++ Runtime and runtime-linking


问:
Should a new type be created though it only wraps a single field?
Say I have an interface Species that's defined as

```<code>public interface Species {

    String getId();

    String getDescription();
}
</code>```

The question is simply this: Should I create different classes to represent these two fields, even though it does not add additional clarity to the code? For example

```<code>public interface SpeciesIdentifier {

    String getValue();
}

public interface SpeciesDescription {

    String getValue();
}

public interface Species {

    SpeciesIdentifier getId();

    SpeciesDescription getDescription();
}
</code>```

The primary use of the Species class is as a DTO.

答:
Creating interfaces for single values may make sense if you want to create a very robust API, which should endure even if requirements change, or if you are not sure how the values will be implemented (will id be a String or int? Will description be simple String, or an object with more structured data, such as group, textual note, comments).

Generally, it is better to keep things simple if you don't anticipate many changes or you can afford to change also all clients.

Beware that if you pass the values between multiple modules or even through remote invocation, not only interfaces must be in classpath on both sides, but also their implementations.


答:
To complete Doc's response, events are not meant to return values, this would be a violation of the CQS pattern (separation of commands and queries, aka read/write). They capture business intentions, creating a kind of audit trail for all that happen in the system. They can be the only data source in the system. In that case, there may be no need to have a database anymore (other than the events store), as it is possible to "mount" the entire system in RAM from the events store and an initial state. It is also possible to create snapshots of the system, given a reference date. PaaS do now support that kind of systems.

The service pattern is also about defining limited scopes and responsibilities for the components you are about to develop (concerning business and data). The service pattern allow components to handle read/write queries.

Title: What are the differences between Event Sourcing and Service Layer pattern?

Body:
I am reading a book on architecting enterprise applications. In this book the Event Sourcing pattern is introduced which can be used as the "command" part of a Command and Query Responsibility Segregation (CQRS) architecture. Event Sourcing is described by Martin Fowler as:

The fundamental idea of Event Sourcing is that of ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.

I am used to applications that use the Service Layer pattern, which I would describe as: changes in the UI call a method, which then triggers the appropriate service call in a middleware layer which delegates the call to the backend where information is updated and notifies the caller of the result.

This description of a Service Layer does, to me, not seem very different from Event Sourcing.

What are the differences between Event Sourcing and the Service Layer pattern?


问:
Are file-scope `static` variables in C as bad as `extern` global variables?
In C, you'd often/sometimes (as a matter of style) use a file-scope static variable where you'd use a private class member variable in C++. When scaling to multithreaded programs, simply adding thread_local in C11 or the long-supported extension __thread fits well. I know you can do exactly the same in C as C++ by putting everything inside a struct and making a set of functions that takes a pointer to that struct as its first argument. Some libraries do this extensively. But my personal style is to keep a struct as small as possible, if needed.

I often read or hear some people arguing 'global' variables are so much bad. I follow their reasons, and most of their argument seems to be related to extern global variables in C terms. What they say is certainly true. I sometimes use 1 or 2 of extern declared variables throughout the whole program when it'll simplify things a lot and when it's easy to keep track of them, but going further will easily make a program unpredictable.

What about static variables? Do they still have the same problem as 'real' global variables? Maybe I don't even have to ask this question and go on if I think what I'm doing is right, but today I saw another 'global variables are BAD' kind of post, and finally came here thinking perhaps this is a right place for such kind of question. What is your thought?

This question is not a duplicate of this because this question asks about extern and static non-local variables while the other question is about file-scope and block-scope static variables.

答: I do not consider variables with file-scope as bad as global variables. After all, all accesses to these variables are confined to one single source file. With that restriction, file-scope variables are pretty much as good or bad as a C++ private static data member, and you don't forbid their use, do you?</p>


问:
Why do I need to use recursion on the classic employee manager database relationship?
Take the data from the Oracle scott database.  I have modified it to have multiple levels of management from the original,

```<code>select * from scott.emp order by mgr desc;

empno       ename  job        mgr   hiredate   sal   comm   deptno

7839    KING    PRESIDENT       11-17-1981  5000        10
7369    SMITH   CLERK   7902    12-17-1980  800     20
7900    JAMES   CLERK   7844    12-03-1981  950     30
7654    MARTIN  SALESMAN    7844    09-28-1981  1250    1400    30
7698    BLAKE   MANAGER 7839    05-01-1981  2850        30
7566    JONES   MANAGER 7839    04-02-1981  2975        20
7782    CLARK   MANAGER 7839    06-09-1981  2450        10
7876    ADAMS   CLERK   7788    05-23-1987  1100        20
7934    MILLER  CLERK   7782    01-23-1982  1300        10
7521    WARD    SALESMAN    7698    02-22-1981  1250    500 30
7844    TURNER  SALESMAN    7698    09-08-1981  1500    0   30
7499    ALLEN   SALESMAN    7698    02-20-1981  1600    300 30
7788    SCOTT   ANALYST 7654    04-19-1987  3000        20
7902    FORD    ANALYST 7566    12-03-1981  3000        20
</code>```

If I want to know who is whose manager,

```<code>select
  E.EMPNO, E.ENAME, E.job, E.MGR,
   M.EMPNO, M.ENAME, M.job, M.MGR
from SCOTT.EMP E, SCOTT.EMP M
where E.MGR = M.EMPNO
order by M.mgr desc;

7698    BLAKE   MANAGER 7839    7839    KING    PRESIDENT
7566    JONES   MANAGER 7839    7839    KING    PRESIDENT
7782    CLARK   MANAGER 7839    7839    KING    PRESIDENT
7788    SCOTT   ANALYST 7654    7654    MARTIN  SALESMAN    7844
7499    ALLEN   SALESMAN    7698    7698    BLAKE   MANAGER 7839
7521    WARD    SALESMAN    7698    7698    BLAKE   MANAGER 7839
7844    TURNER  SALESMAN    7698    7698    BLAKE   MANAGER 7839
7902    FORD    ANALYST 7566    7566    JONES   MANAGER 7839
7934    MILLER  CLERK   7782    7782    CLARK   MANAGER 7839
7900    JAMES   CLERK   7844    7844    TURNER  SALESMAN    7698
7654    MARTIN  SALESMAN    7844    7844    TURNER  SALESMAN    7698
7876    ADAMS   CLERK   7788    7788    SCOTT   ANALYST 7654
7369    SMITH   CLERK   7902    7902    FORD    ANALYST 7566
</code>```

I can see that,

73609 (smith) has a manager 7902 (ford) who has a manager 7566 (jones) who has a manager 7839 (president, null mgr).

Why would I need to use recursion here as I see so many do with Common Table Expressions?  Is it just for display reasons?

答:
If you only care about direct reports, you do not need to use recursion. Every employee (except the CEO) reports to exactly one manager.

If you want to know direction and indirect reports, you need recursion. This would answer the question "who are all the reports of this director, including managers, supervisors, and peons." It might not be at the same granularity of department, which is in your table. You need to look for the direct reports of the director, then query the direct reports of those employees, and recurse until nobody reports to the employees you just fetched.

SQL is inherently not a recursive language. Standard SQL did not have recursion for many years because it is poorly modeled by the underlying relational calculus. However, Common Table Expressions (CTE) were added in SQL:1999. While not generally useful, they are very helpful in certain niches.

Pretty much all of the Enterprise-class databases such as SQL Server and Oracle have added recursive queries, but some smaller databases such as MySQL lag behind the standard.


答:
In a well-design C program, a file-static variable is similar to a private static member of a class:

It can only be accessed by functions in that file, similar to how a private static member variable can only be accessed by functions in the class in which it is defined.

There is only one copy of the variable.

Its lifetime is the program lifetime.

An extern variable would be a true global variable as in any language that supports them.

A static non-global variable is not as bad as a global; in fact, they are necessary in some cases.

Access is controlled through functions you write. This helps with data integrity including both bounds checking as well as thread-safety. (note: this does not guarantee thread-safety, it is simply one tool to help along the way)

Data is encapsulated: only that file can access it. This is as close as C can get to encapsulation where multiple functions can access a static variable.

Global variables are bad no matter what. Static file variables have the benefits of a private static variable but none of the drawbacks of a global variable.

The only issue is unlike with a true private static variable as in C++, other files can declare an extern variable matching the declaration and you cannot prevent access. In other words, you are relying on the honor system to avoid turning it into a global variable.

Title: Are file-scope `static` variables in C as bad as `extern` global variables?

Body:
In C, you'd often/sometimes (as a matter of style) use a file-scope static variable where you'd use a private class member variable in C++. When scaling to multithreaded programs, simply adding thread_local in C11 or the long-supported extension __thread fits well. I know you can do exactly the same in C as C++ by putting everything inside a struct and making a set of functions that takes a pointer to that struct as its first argument. Some libraries do this extensively. But my personal style is to keep a struct as small as possible, if needed.

I often read or hear some people arguing 'global' variables are so much bad. I follow their reasons, and most of their argument seems to be related to extern global variables in C terms. What they say is certainly true. I sometimes use 1 or 2 of extern declared variables throughout the whole program when it'll simplify things a lot and when it's easy to keep track of them, but going further will easily make a program unpredictable.

What about static variables? Do they still have the same problem as 'real' global variables? Maybe I don't even have to ask this question and go on if I think what I'm doing is right, but today I saw another 'global variables are BAD' kind of post, and finally came here thinking perhaps this is a right place for such kind of question. What is your thought?

This question is not a duplicate of this because this question asks about extern and static non-local variables while the other question is about file-scope and block-scope static variables.


答:
Global state, including extern variables and non-const static variables in file scope or in functions can frequently be an easy solution to a given problem, but there are three issues:

static makes code untestable, because static variables tend to be non-replaceable dependencies. Or in more OOP-y words: you aren't following the Dependency Inversion Principle. I came to C and C++ from dynamic languages such as Perl, so my cost model is slanted towards virtual dispatch and function pointers and so on. With current languages, there's some conflict between testability and good architecture, but I think the minor nuisance of making your dependencies explicit and letting them be overridden in tests is noticeably offset by the ease of writing tests, and thus making sure your software is working as expected. Without making your code more dynamic, the only available mechanism to inject dependencies for a test is conditional compilation.

Global state makes it difficult to reason about correctness, and that leads to bugs. The more bits and pieces have access to a variable and can modify it, the easier it is to lose track of what's happening. Instead: prefer single assignment of variables! Prefer const wherever reasonable! Prefer guarding variables through getters and setters where you can introduce correctness checks. As long as the state is static and not extern, it is still possible to maintain correctness, but it's always better to assume me-in-a-week won't be as smart as me-right-now. Especially in C++, we can use classes to model various abstractions that make it impossible to misuse something, so try to utilize the type system rather than your intelligence – you have more important stuff to think about.

Global state might imply that your functions are not re-entrant, or that they can only be used in one context at a time. Imagine a database driver that could only manage one connection! That's a totally unnecessary restrictions. In reality, the limitations are often subtler, such as a global variable that's used to aggregate results. Instead, make your data flow explicit and pass everything through function parameters. Again, C++ classes can make this more manageable.

Obviously, static const NAMED_CONSTANTS are OK. Using static inside of functions is a lot trickier: while it is useful for lazily initialized constants, it may be fairly untestable. A compromise is to separate calculating the initial value from the static variable, so that both parts can be tested separately.

In small, self-contained programs, all of this won't matter, and you can keep using static state to your hearts delight. But as you pass around 500 LOC or if you are writing a reusable library, you should really start thinking about good architecture and a good interface without unnecessary restrictions.


问:
Should Objects with lots of fields be broken up?
When I have an Object that has lots of fields is it better to have them all as fields or try to find logical groupings as their own Objects and make those the fields?

I guess it comes down to which is the greater evil, too many Objects or too many fields in an Object.

Less Objects, more fields:

```<code>public class LotsOfFields Object {

    private Foo foo;
    private Bar bar;
    private Baz baz;
    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

More Objects, less fields:

```<code>public class LessFields Object {

    private ClicheMetaSyntacticVariables vars;
    private Animals animals;

    // Getters and setters...

}

public class ClicheMetaSyntacticVariables {

    private Foo foo;
    private Bar bar;
    private Baz baz;

    // Getters and setters...

}

public class Animals {

    private Dog dog;
    private Cat cat;
    private Goat goat;

    // Getters and setters...

}
</code>```

As an aside, if the "more Objects" approach is better, is it better to have the classes as members of the original class (assuming they'd never be used elsewhere) or does that defeat the purpose of not cluttering an Object?

Edit to defend my question not being a duplicate: This is about a more specific issue than "what is the purpose of a class" and to me that alone is enough. To go on, I am really talking more about what makes a more readable/usable class, I'll take the blame for not specifying that though.

答:
Ask yourself this, if you separate out the members into separate classes, are the classes doing any meaningful independent work? If the classes are co-dependent, and can do nothing without access to the other members then its probably a bad idea to separate them out.

On the other hand, if one class can meaningfully lessen the workload of the other class or be used independently from the other class then you might consider separating them.